blob: 2f5f76736ffb519f0e8ed34064ce6c838f6a1ab8 [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 Warsaw9981d221997-12-03 05:25:48 +00001136 (let (line file bol)
1137 (save-excursion
1138 (set-buffer buf)
1139 (beginning-of-buffer)
1140 (while (re-search-forward py-traceback-line-re nil t)
1141 (setq file (match-string 1)
1142 line (string-to-int (match-string 2))
1143 bol (py-point 'bol))
1144 (py-highlight-line bol (py-point 'eol) file line))
1145 (when (and py-jump-on-exception line)
1146 (beep)
1147 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001148 )))
1149
Barry Warsaw9981d221997-12-03 05:25:48 +00001150
Barry Warsawa97a3f31997-11-04 18:47:06 +00001151
1152;;; Subprocess commands
1153
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001154;; only used when (memq 'broken-temp-names py-emacs-features)
1155(defvar py-serial-number 0)
1156(defvar py-exception-buffer nil)
1157(defconst py-output-buffer "*Python Output*")
1158
Barry Warsawa97a3f31997-11-04 18:47:06 +00001159;;;###autoload
1160(defun py-shell ()
1161 "Start an interactive Python interpreter in another window.
1162This is like Shell mode, except that Python is running in the window
1163instead of a shell. See the `Interactive Shell' and `Shell Mode'
1164sections of the Emacs manual for details, especially for the key
1165bindings active in the `*Python*' buffer.
1166
1167See the docs for variable `py-scroll-buffer' for info on scrolling
1168behavior in the process window.
1169
1170Warning: Don't use an interactive Python if you change sys.ps1 or
1171sys.ps2 from their default values, or if you're running code that
1172prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1173distinguish your output from Python's output, and assumes that `>>> '
1174at the start of a line is a prompt from Python. Similarly, the Emacs
1175Shell mode code assumes that both `>>> ' and `... ' at the start of a
1176line are Python prompts. Bad things can happen if you fool either
1177mode.
1178
1179Warning: If you do any editing *in* the process buffer *while* the
1180buffer is accepting output from Python, do NOT attempt to `undo' the
1181changes. Some of the output (nowhere near the parts you changed!) may
1182be lost if you do. This appears to be an Emacs bug, an unfortunate
1183interaction between undo and process filters; the same problem exists in
1184non-Python process buffers using the default (Emacs-supplied) process
1185filter."
1186 ;; BAW - should undo be disabled in the python process buffer, if
1187 ;; this bug still exists?
1188 (interactive)
1189 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001190 (switch-to-buffer-other-window
Barry Warsaw8f972b71998-02-05 20:45:49 +00001191 (apply 'make-comint "Python" py-python-command nil py-python-command-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001192 (make-local-variable 'comint-prompt-regexp)
1193 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1194 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1195 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001196 ;; set up keybindings for this subshell
1197 (local-set-key [tab] 'self-insert-command)
1198 (local-set-key "\C-c-" 'py-up-exception)
1199 (local-set-key "\C-c=" 'py-down-exception)
1200 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001201
Barry Warsawa97a3f31997-11-04 18:47:06 +00001202(defun py-clear-queue ()
1203 "Clear the queue of temporary files waiting to execute."
1204 (interactive)
1205 (let ((n (length py-file-queue)))
1206 (mapcar 'delete-file py-file-queue)
1207 (setq py-file-queue nil)
1208 (message "%d pending files de-queued." n)))
1209
1210(defun py-execute-region (start end &optional async)
1211 "Execute the the region in a Python interpreter.
1212The region is first copied into a temporary file (in the directory
1213`py-temp-directory'). If there is no Python interpreter shell
1214running, this file is executed synchronously using
1215`shell-command-on-region'. If the program is long running, use an
1216optional \\[universal-argument] to run the command asynchronously in
1217its own buffer.
1218
1219If the Python interpreter shell is running, the region is execfile()'d
1220in that shell. If you try to execute regions too quickly,
1221`python-mode' will queue them up and execute them one at a time when
1222it sees a `>>> ' prompt from Python. Each time this happens, the
1223process buffer is popped into a window (if it's not already in some
1224window) so you can see it, and a comment of the form
1225
1226 \t## working on region in file <name>...
1227
1228is inserted at the end. See also the command `py-clear-queue'."
1229 (interactive "r\nP")
1230 (or (< start end)
1231 (error "Region is empty"))
1232 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001233 (temp (if (memq 'broken-temp-names py-emacs-features)
1234 (prog1
1235 (format "python-%d" py-serial-number)
1236 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001237 (make-temp-name "python-")))
1238 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001239 (write-region start end file nil 'nomsg)
1240 (cond
1241 ;; always run the code in it's own asynchronous subprocess
1242 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001243 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001244 (start-process "Python" buf py-python-command "-u" file)
1245 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001246 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001247 ))
1248 ;; if the Python interpreter shell is running, queue it up for
1249 ;; execution there.
1250 (proc
1251 ;; use the existing python shell
1252 (if (not py-file-queue)
1253 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001254 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001255 (push file py-file-queue)
1256 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001257 (t
1258 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001259 (shell-command-on-region start end py-python-command py-output-buffer)
1260 (setq py-exception-buffer (current-buffer))
1261 (py-postprocess-output-buffer py-output-buffer)
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001262 (pop-to-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001263 ))))
1264
1265;; Code execution command
1266(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001267 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001268If the file local variable `py-master-file' is non-nil, execute the
1269named file instead of the buffer's file.
1270
Barry Warsaw7ae77681994-12-12 20:38:05 +00001271If there is a *Python* process buffer it is used. If a clipping
1272restriction is in effect, only the accessible portion of the buffer is
1273sent. A trailing newline will be supplied if needed.
1274
1275See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001276 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001277 (if py-master-file
1278 (let* ((filename (expand-file-name py-master-file))
1279 (buffer (or (get-file-buffer filename)
1280 (find-file-noselect filename))))
1281 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001282 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001283
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001284
1285
1286(defun py-jump-to-exception (file line)
1287 (let ((buffer (cond ((string-equal file "<stdin>")
1288 py-exception-buffer)
1289 ((and (consp py-exception-buffer)
1290 (string-equal file (car py-exception-buffer)))
1291 (cdr py-exception-buffer))
1292 ((py-safe (find-file-noselect file)))
1293 ;; could not figure out what file the exception
1294 ;; is pointing to, so prompt for it
1295 (t (find-file (read-file-name "Exception file: "
1296 nil
1297 file t))))))
1298 (pop-to-buffer buffer)
1299 (goto-line line)
1300 (message "Jumping to exception in file %s on line %d" file line)))
1301
1302(defun py-mouseto-exception (event)
1303 (interactive "e")
1304 (cond
1305 ((fboundp 'event-point)
1306 ;; XEmacs
1307 (let* ((point (event-point event))
1308 (buffer (event-buffer event))
1309 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1310 (info (and e (extent-property e 'py-exc-info))))
1311 (message "Event point: %d, info: %s" point info)
1312 (and info
1313 (py-jump-to-exception (car info) (cdr info)))
1314 ))
1315 ;; Emacs -- Please port this!
1316 ))
1317
1318(defun py-goto-exception ()
1319 "Go to the line indicated by the traceback."
1320 (interactive)
1321 (let (file line)
1322 (save-excursion
1323 (beginning-of-line)
1324 (if (looking-at py-traceback-line-re)
1325 (setq file (match-string 1)
1326 line (string-to-int (match-string 2)))))
1327 (if (not file)
1328 (error "Not on a traceback line."))
1329 (py-jump-to-exception file line)))
1330
1331(defun py-find-next-exception (start buffer searchdir errwhere)
1332 ;; Go to start position in buffer, search in the specified
1333 ;; direction, and jump to the exception found. If at the end of the
1334 ;; exception, print error message
1335 (let (file line)
1336 (save-excursion
1337 (set-buffer buffer)
1338 (goto-char (py-point start))
1339 (if (funcall searchdir py-traceback-line-re nil t)
1340 (setq file (match-string 1)
1341 line (string-to-int (match-string 2)))))
1342 (if (and file line)
1343 (py-jump-to-exception file line)
1344 (error "%s of traceback" errwhere))))
1345
1346(defun py-down-exception (&optional bottom)
1347 "Go to the next line down in the traceback.
1348With optional \\[universal-argument], jump to the bottom (innermost)
1349exception in the exception stack."
1350 (interactive "P")
1351 (let* ((proc (get-process "Python"))
1352 (buffer (if proc "*Python*" py-output-buffer)))
1353 (if bottom
1354 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1355 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1356
1357(defun py-up-exception (&optional top)
1358 "Go to the previous line up in the traceback.
1359With optional \\[universal-argument], jump to the top (outermost)
1360exception in the exception stack."
1361 (interactive "P")
1362 (let* ((proc (get-process "Python"))
1363 (buffer (if proc "*Python*" py-output-buffer)))
1364 (if top
1365 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001366 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001367
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001368
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001369;; Electric deletion
1370(defun py-electric-backspace (arg)
1371 "Deletes preceding character or levels of indentation.
1372Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001373with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001374
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001375If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001377Otherwise, if point is at the leftmost non-whitespace character of a
1378line that is neither a continuation line nor a non-indenting comment
1379line, or if point is at the end of a blank line, this command reduces
1380the indentation to match that of the line that opened the current
1381block of code. The line that opened the block is displayed in the
1382echo area to help you keep track of where you are. With numeric arg,
1383outdents that many blocks (but not past column zero).
1384
1385Otherwise the preceding character is deleted, converting a tab to
1386spaces if needed so that only a single column position is deleted.
1387Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001388 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001389 (if (or (/= (current-indentation) (current-column))
1390 (bolp)
1391 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001392 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001394 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001395 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396 ;; force non-blank so py-goto-block-up doesn't ignore it
1397 (insert-char ?* 1)
1398 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001399 (let ((base-indent 0) ; indentation of base line
1400 (base-text "") ; and text of base line
1401 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001402 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001403 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001404 (condition-case nil ; in case no enclosing block
1405 (progn
1406 (py-goto-block-up 'no-mark)
1407 (setq base-indent (current-indentation)
1408 base-text (py-suck-up-leading-text)
1409 base-found-p t))
1410 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001411 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001412 (delete-char 1) ; toss the dummy character
1413 (delete-horizontal-space)
1414 (indent-to base-indent)
1415 (if base-found-p
1416 (message "Closes block: %s" base-text)))))
1417
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001418
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001419(defun py-electric-delete (arg)
1420 "Deletes preceding or following character or levels of whitespace.
1421
1422The behavior of this function depends on the variable
1423`delete-key-deletes-forward'. If this variable is nil (or does not
1424exist, as in older Emacsen), then this function behaves identical to
1425\\[c-electric-backspace].
1426
1427If `delete-key-deletes-forward' is non-nil and is supported in your
1428Emacs, then deletion occurs in the forward direction, by calling the
1429function in `py-delete-function'."
1430 (interactive "*p")
1431 (if (and (boundp 'delete-key-deletes-forward)
1432 delete-key-deletes-forward)
1433 (funcall py-delete-function arg)
1434 ;; else
1435 (py-electric-backspace arg)))
1436
1437;; required for pending-del and delsel modes
1438(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1439(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1440(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1441(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1442
1443
1444
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001445(defun py-indent-line (&optional arg)
1446 "Fix the indentation of the current line according to Python rules.
1447With \\[universal-argument], ignore outdenting rules for block
1448closing statements (e.g. return, raise, break, continue, pass)
1449
1450This function is normally bound to `indent-line-function' so
1451\\[indent-for-tab-command] will call it."
1452 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001453 (let* ((ci (current-indentation))
1454 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001455 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001456 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001457 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001458 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459 (if (/= ci need)
1460 (save-excursion
1461 (beginning-of-line)
1462 (delete-horizontal-space)
1463 (indent-to need)))
1464 (if move-to-indentation-p (back-to-indentation))))
1465
1466(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001467 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001468This is just `strives to' because correct indentation can't be computed
1469from scratch for Python code. In general, deletes the whitespace before
1470point, inserts a newline, and takes an educated guess as to how you want
1471the new line indented."
1472 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001473 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001474 (if (< ci (current-column)) ; if point beyond indentation
1475 (newline-and-indent)
1476 ;; else try to act like newline-and-indent "normally" acts
1477 (beginning-of-line)
1478 (insert-char ?\n 1)
1479 (move-to-column ci))))
1480
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001481(defun py-compute-indentation (honor-block-close-p)
1482 ;; implements all the rules for indentation computation. when
1483 ;; honor-block-close-p is non-nil, statements such as return, raise,
1484 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001485 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001486 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001487 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001488 (pps (parse-partial-sexp bod (point)))
1489 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001490 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001491 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001492 ((or (and (nth 3 pps) (nth 3 boipps))
1493 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001494 (save-excursion
1495 (if (not py-align-multiline-strings-p) 0
1496 ;; skip back over blank & non-indenting comment lines
1497 ;; note: will skip a blank or non-indenting comment line
1498 ;; that happens to be a continuation line too
1499 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1500 (back-to-indentation)
1501 (current-column))))
1502 ;; are we on a continuation line?
1503 ((py-continuation-line-p)
1504 (let ((startpos (point))
1505 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001506 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001507 (if open-bracket-pos
1508 (progn
1509 ;; align with first item in list; else a normal
1510 ;; indent beyond the line with the open bracket
1511 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1512 ;; is the first list item on the same line?
1513 (skip-chars-forward " \t")
1514 (if (null (memq (following-char) '(?\n ?# ?\\)))
1515 ; yes, so line up with it
1516 (current-column)
1517 ;; first list item on another line, or doesn't exist yet
1518 (forward-line 1)
1519 (while (and (< (point) startpos)
1520 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1521 (forward-line 1))
1522 (if (< (point) startpos)
1523 ;; again mimic the first list item
1524 (current-indentation)
1525 ;; else they're about to enter the first item
1526 (goto-char open-bracket-pos)
1527 (+ (current-indentation) py-indent-offset))))
1528
1529 ;; else on backslash continuation line
1530 (forward-line -1)
1531 (if (py-continuation-line-p) ; on at least 3rd line in block
1532 (current-indentation) ; so just continue the pattern
1533 ;; else started on 2nd line in block, so indent more.
1534 ;; if base line is an assignment with a start on a RHS,
1535 ;; indent to 2 beyond the leftmost "="; else skip first
1536 ;; chunk of non-whitespace characters on base line, + 1 more
1537 ;; column
1538 (end-of-line)
1539 (setq endpos (point) searching t)
1540 (back-to-indentation)
1541 (setq startpos (point))
1542 ;; look at all "=" from left to right, stopping at first
1543 ;; one not nested in a list or string
1544 (while searching
1545 (skip-chars-forward "^=" endpos)
1546 (if (= (point) endpos)
1547 (setq searching nil)
1548 (forward-char 1)
1549 (setq state (parse-partial-sexp startpos (point)))
1550 (if (and (zerop (car state)) ; not in a bracket
1551 (null (nth 3 state))) ; & not in a string
1552 (progn
1553 (setq searching nil) ; done searching in any case
1554 (setq found
1555 (not (or
1556 (eq (following-char) ?=)
1557 (memq (char-after (- (point) 2))
1558 '(?< ?> ?!)))))))))
1559 (if (or (not found) ; not an assignment
1560 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1561 (progn
1562 (goto-char startpos)
1563 (skip-chars-forward "^ \t\n")))
1564 (1+ (current-column))))))
1565
1566 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001567 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001568
Barry Warsawa7891711996-08-01 15:53:09 +00001569 ;; Dfn: "Indenting comment line". A line containing only a
1570 ;; comment, but which is treated like a statement for
1571 ;; indentation calculation purposes. Such lines are only
1572 ;; treated specially by the mode; they are not treated
1573 ;; specially by the Python interpreter.
1574
1575 ;; The rules for indenting comment lines are a line where:
1576 ;; - the first non-whitespace character is `#', and
1577 ;; - the character following the `#' is whitespace, and
1578 ;; - the line is outdented with respect to (i.e. to the left
1579 ;; of) the indentation of the preceding non-blank line.
1580
1581 ;; The first non-blank line following an indenting comment
1582 ;; line is given the same amount of indentation as the
1583 ;; indenting comment line.
1584
1585 ;; All other comment-only lines are ignored for indentation
1586 ;; purposes.
1587
1588 ;; Are we looking at a comment-only line which is *not* an
1589 ;; indenting comment line? If so, we assume that its been
1590 ;; placed at the desired indentation, so leave it alone.
1591 ;; Indenting comment lines are aligned as statements down
1592 ;; below.
1593 ((and (looking-at "[ \t]*#[^ \t\n]")
1594 ;; NOTE: this test will not be performed in older Emacsen
1595 (fboundp 'forward-comment)
1596 (<= (current-indentation)
1597 (save-excursion
1598 (forward-comment (- (point-max)))
1599 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001600 (current-indentation))
1601
1602 ;; else indentation based on that of the statement that
1603 ;; precedes us; use the first line of that statement to
1604 ;; establish the base, in case the user forced a non-std
1605 ;; indentation for the continuation lines (if any)
1606 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001607 ;; skip back over blank & non-indenting comment lines note:
1608 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001609 ;; happens to be a continuation line too. use fast Emacs 19
1610 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001611 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001612 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001613 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001614 (let (done)
1615 (while (not done)
1616 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1617 nil 'move)
1618 (setq done (or (eq py-honor-comment-indentation t)
1619 (bobp)
1620 (/= (following-char) ?#)
1621 (not (zerop (current-column)))))
1622 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001623 ;; if we landed inside a string, go to the beginning of that
1624 ;; string. this handles triple quoted, multi-line spanning
1625 ;; strings.
Barry Warsawf64b4051998-02-12 16:52:14 +00001626 (let* ((pps3 (nth 3 (parse-partial-sexp bod (point))))
1627 (delim (and pps3 (int-to-char pps3)))
1628 (skip (and delim (make-string 1 delim))))
1629 (when skip
1630 (save-excursion
1631 (py-safe (search-backward skip))
1632 (if (and (eq (char-before) delim)
1633 (eq (char-before (1- (point))) delim))
1634 (setq skip (make-string 3 delim))))
1635 ;; we're looking at a triple-quoted string
1636 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001637 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001638 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001639 (+ (current-indentation)
1640 (if (py-statement-opens-block-p)
1641 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001642 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001643 (- py-indent-offset)
1644 0)))
1645 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001646
1647(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001648 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001649By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001650`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001651Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001652`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001653their own buffer-local copy), both those currently existing and those
1654created later in the Emacs session.
1655
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001656Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657There's no excuse for such foolishness, but sometimes you have to deal
1658with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659`py-indent-offset' to what it thinks it was when they created the
1660mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001661
1662Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001663looking for a line that opens a block of code. `py-indent-offset' is
1664set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001665statement following it. If the search doesn't succeed going forward,
1666it's tried again going backward."
1667 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001668 (let (new-value
1669 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001670 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671 (found nil)
1672 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001673 (py-goto-initial-line)
1674 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001675 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1676 (not (py-in-literal restart)))
1677 (setq restart (point))
1678 (py-goto-initial-line)
1679 (if (py-statement-opens-block-p)
1680 (setq found t)
1681 (goto-char restart))))
1682 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683 (goto-char start)
1684 (py-goto-initial-line)
1685 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001686 (setq found (and
1687 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1688 (or (py-goto-initial-line) t) ; always true -- side effect
1689 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001690 (setq colon-indent (current-indentation)
1691 found (and found (zerop (py-next-statement 1)))
1692 new-value (- (current-indentation) colon-indent))
1693 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001694 (if (not found)
1695 (error "Sorry, couldn't guess a value for py-indent-offset")
1696 (funcall (if global 'kill-local-variable 'make-local-variable)
1697 'py-indent-offset)
1698 (setq py-indent-offset new-value)
1699 (message "%s value of py-indent-offset set to %d"
1700 (if global "Global" "Local")
1701 py-indent-offset))
1702 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001703
1704(defun py-shift-region (start end count)
1705 (save-excursion
1706 (goto-char end) (beginning-of-line) (setq end (point))
1707 (goto-char start) (beginning-of-line) (setq start (point))
1708 (indent-rigidly start end count)))
1709
1710(defun py-shift-region-left (start end &optional count)
1711 "Shift region of Python code to the left.
1712The lines from the line containing the start of the current region up
1713to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001714shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715
1716If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001717many columns. With no active region, outdent only the current line.
1718You cannot outdent the region if any line is already at column zero."
1719 (interactive
1720 (let ((p (point))
1721 (m (mark))
1722 (arg current-prefix-arg))
1723 (if m
1724 (list (min p m) (max p m) arg)
1725 (list p (save-excursion (forward-line 1) (point)) arg))))
1726 ;; if any line is at column zero, don't shift the region
1727 (save-excursion
1728 (goto-char start)
1729 (while (< (point) end)
1730 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001731 (if (and (zerop (current-column))
1732 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001733 (error "Region is at left edge."))
1734 (forward-line 1)))
1735 (py-shift-region start end (- (prefix-numeric-value
1736 (or count py-indent-offset))))
1737 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738
1739(defun py-shift-region-right (start end &optional count)
1740 "Shift region of Python code to the right.
1741The lines from the line containing the start of the current region up
1742to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744
1745If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001746many columns. With no active region, indent only the current line."
1747 (interactive
1748 (let ((p (point))
1749 (m (mark))
1750 (arg current-prefix-arg))
1751 (if m
1752 (list (min p m) (max p m) arg)
1753 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001755 (or count py-indent-offset)))
1756 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757
1758(defun py-indent-region (start end &optional indent-offset)
1759 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001760
Barry Warsaw7ae77681994-12-12 20:38:05 +00001761The lines from the line containing the start of the current region up
1762to (but not including) the line containing the end of the region are
1763reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764character in the first column, the first line is left alone and the
1765rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001766region is reindented with respect to the (closest code or indenting
1767comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768
1769This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770control structures are introduced or removed, or to reformat code
1771using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001772
1773If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001774the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001775used.
1776
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778is called! This function does not compute proper indentation from
1779scratch (that's impossible in Python), it merely adjusts the existing
1780indentation to be correct in context.
1781
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001782Warning: This function really has no idea what to do with
1783non-indenting comment lines, and shifts them as if they were indenting
1784comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001786Special cases: whitespace is deleted from blank lines; continuation
1787lines are shifted by the same amount their initial line was shifted,
1788in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001789initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791 (save-excursion
1792 (goto-char end) (beginning-of-line) (setq end (point-marker))
1793 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794 (let ((py-indent-offset (prefix-numeric-value
1795 (or indent-offset py-indent-offset)))
1796 (indents '(-1)) ; stack of active indent levels
1797 (target-column 0) ; column to which to indent
1798 (base-shifted-by 0) ; amount last base line was shifted
1799 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001800 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001801 0))
1802 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001803 (while (< (point) end)
1804 (setq ci (current-indentation))
1805 ;; figure out appropriate target column
1806 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807 ((or (eq (following-char) ?#) ; comment in column 1
1808 (looking-at "[ \t]*$")) ; entirely blank
1809 (setq target-column 0))
1810 ((py-continuation-line-p) ; shift relative to base line
1811 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001812 (t ; new base line
1813 (if (> ci (car indents)) ; going deeper; push it
1814 (setq indents (cons ci indents))
1815 ;; else we should have seen this indent before
1816 (setq indents (memq ci indents)) ; pop deeper indents
1817 (if (null indents)
1818 (error "Bad indentation in region, at line %d"
1819 (save-restriction
1820 (widen)
1821 (1+ (count-lines 1 (point)))))))
1822 (setq target-column (+ indent-base
1823 (* py-indent-offset
1824 (- (length indents) 2))))
1825 (setq base-shifted-by (- target-column ci))))
1826 ;; shift as needed
1827 (if (/= ci target-column)
1828 (progn
1829 (delete-horizontal-space)
1830 (indent-to target-column)))
1831 (forward-line 1))))
1832 (set-marker end nil))
1833
Barry Warsawa7891711996-08-01 15:53:09 +00001834(defun py-comment-region (beg end &optional arg)
1835 "Like `comment-region' but uses double hash (`#') comment starter."
1836 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001837 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001838 (comment-region beg end arg)))
1839
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840
1841;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842(defun py-previous-statement (count)
1843 "Go to the start of previous Python statement.
1844If the statement at point is the i'th Python statement, goes to the
1845start of statement i-COUNT. If there is no such statement, goes to the
1846first statement. Returns count of statements left to move.
1847`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001848 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001849 (if (< count 0) (py-next-statement (- count))
1850 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001851 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001852 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854 (> count 0)
1855 (zerop (forward-line -1))
1856 (py-goto-statement-at-or-above))
1857 (setq count (1- count)))
1858 (if (> count 0) (goto-char start)))
1859 count))
1860
1861(defun py-next-statement (count)
1862 "Go to the start of next Python statement.
1863If the statement at point is the i'th Python statement, goes to the
1864start of statement i+COUNT. If there is no such statement, goes to the
1865last statement. Returns count of statements left to move. `Statements'
1866do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001867 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868 (if (< count 0) (py-previous-statement (- count))
1869 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001870 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001871 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001873 (> count 0)
1874 (py-goto-statement-below))
1875 (setq count (1- count)))
1876 (if (> count 0) (goto-char start)))
1877 count))
1878
1879(defun py-goto-block-up (&optional nomark)
1880 "Move up to start of current block.
1881Go to the statement that starts the smallest enclosing block; roughly
1882speaking, this will be the closest preceding statement that ends with a
1883colon and is indented less than the statement you started on. If
1884successful, also sets the mark to the starting point.
1885
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001886`\\[py-mark-block]' can be used afterward to mark the whole code
1887block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888
1889If called from a program, the mark will not be set if optional argument
1890NOMARK is not nil."
1891 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892 (let ((start (point))
1893 (found nil)
1894 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895 (py-goto-initial-line)
1896 ;; if on blank or non-indenting comment line, use the preceding stmt
1897 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1898 (progn
1899 (py-goto-statement-at-or-above)
1900 (setq found (py-statement-opens-block-p))))
1901 ;; search back for colon line indented less
1902 (setq initial-indent (current-indentation))
1903 (if (zerop initial-indent)
1904 ;; force fast exit
1905 (goto-char (point-min)))
1906 (while (not (or found (bobp)))
1907 (setq found
1908 (and
1909 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1910 (or (py-goto-initial-line) t) ; always true -- side effect
1911 (< (current-indentation) initial-indent)
1912 (py-statement-opens-block-p))))
1913 (if found
1914 (progn
1915 (or nomark (push-mark start))
1916 (back-to-indentation))
1917 (goto-char start)
1918 (error "Enclosing block not found"))))
1919
1920(defun beginning-of-python-def-or-class (&optional class)
1921 "Move point to start of def (or class, with prefix arg).
1922
1923Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924arg, looks for a `class' instead. The docs assume the `def' case;
1925just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001926
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001927If point is in a def statement already, and after the `d', simply
1928moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930Else (point is not in a def statement, or at or before the `d' of a
1931def statement), searches for the closest preceding def statement, and
1932leaves point at its start. If no such statement can be found, leaves
1933point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934
1935Returns t iff a def statement is found by these rules.
1936
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001937Note that doing this command repeatedly will take you closer to the
1938start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001941`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001942 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1944 (start-of-line (progn (beginning-of-line) (point)))
1945 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001946 (if (or (/= start-of-stmt start-of-line)
1947 (not at-or-before-p))
1948 (end-of-line)) ; OK to match on this line
1949 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951
1952(defun end-of-python-def-or-class (&optional class)
1953 "Move point beyond end of def (or class, with prefix arg) body.
1954
1955By default, looks for an appropriate `def'. If you supply a prefix arg,
1956looks for a `class' instead. The docs assume the `def' case; just
1957substitute `class' for `def' for the other case.
1958
1959If point is in a def statement already, this is the def we use.
1960
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961Else if the def found by `\\[beginning-of-python-def-or-class]'
1962contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001963
1964Else we search forward for the closest following def, and use that.
1965
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001966If a def can be found by these rules, point is moved to the start of
1967the line immediately following the def block, and the position of the
1968start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001969
1970Else point is moved to the end of the buffer, and nil is returned.
1971
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001972Note that doing this command repeatedly will take you closer to the
1973end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001974
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001976`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001977 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001978 (let ((start (progn (py-goto-initial-line) (point)))
1979 (which (if class "class" "def"))
1980 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981 ;; move point to start of appropriate def/class
1982 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1983 (setq state 'at-beginning)
1984 ;; else see if beginning-of-python-def-or-class hits container
1985 (if (and (beginning-of-python-def-or-class class)
1986 (progn (py-goto-beyond-block)
1987 (> (point) start)))
1988 (setq state 'at-end)
1989 ;; else search forward
1990 (goto-char start)
1991 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1992 (progn (setq state 'at-beginning)
1993 (beginning-of-line)))))
1994 (cond
1995 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1996 ((eq state 'at-end) t)
1997 ((eq state 'not-found) nil)
1998 (t (error "internal error in end-of-python-def-or-class")))))
1999
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000
2001;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002002(defun py-mark-block (&optional extend just-move)
2003 "Mark following block of lines. With prefix arg, mark structure.
2004Easier to use than explain. It sets the region to an `interesting'
2005block of succeeding lines. If point is on a blank line, it goes down to
2006the next non-blank line. That will be the start of the region. The end
2007of the region depends on the kind of line at the start:
2008
2009 - If a comment, the region will include all succeeding comment lines up
2010 to (but not including) the next non-comment line (if any).
2011
2012 - Else if a prefix arg is given, and the line begins one of these
2013 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014
2015 if elif else try except finally for while def class
2016
Barry Warsaw7ae77681994-12-12 20:38:05 +00002017 the region will be set to the body of the structure, including
2018 following blocks that `belong' to it, but excluding trailing blank
2019 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020 and all (if any) of the following `except' and `finally' blocks
2021 that belong to the `try' structure will be in the region. Ditto
2022 for if/elif/else, for/else and while/else structures, and (a bit
2023 degenerate, since they're always one-block structures) def and
2024 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025
2026 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002027 block (see list above), and the block is not a `one-liner' (i.e.,
2028 the statement ends with a colon, not with code), the region will
2029 include all succeeding lines up to (but not including) the next
2030 code statement (if any) that's indented no more than the starting
2031 line, except that trailing blank and comment lines are excluded.
2032 E.g., if the starting line begins a multi-statement `def'
2033 structure, the region will be set to the full function definition,
2034 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002035
2036 - Else the region will include all succeeding lines up to (but not
2037 including) the next blank line, or code or indenting-comment line
2038 indented strictly less than the starting line. Trailing indenting
2039 comment lines are included in this case, but not trailing blank
2040 lines.
2041
2042A msg identifying the location of the mark is displayed in the echo
2043area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2044
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045If called from a program, optional argument EXTEND plays the role of
2046the prefix arg, and if optional argument JUST-MOVE is not nil, just
2047moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002048 (interactive "P") ; raw prefix arg
2049 (py-goto-initial-line)
2050 ;; skip over blank lines
2051 (while (and
2052 (looking-at "[ \t]*$") ; while blank line
2053 (not (eobp))) ; & somewhere to go
2054 (forward-line 1))
2055 (if (eobp)
2056 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002057 (let ((initial-pos (point))
2058 (initial-indent (current-indentation))
2059 last-pos ; position of last stmt in region
2060 (followers
2061 '((if elif else) (elif elif else) (else)
2062 (try except finally) (except except) (finally)
2063 (for else) (while else)
2064 (def) (class) ) )
2065 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002066
2067 (cond
2068 ;; if comment line, suck up the following comment lines
2069 ((looking-at "[ \t]*#")
2070 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2071 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2072 (setq last-pos (point)))
2073
2074 ;; else if line is a block line and EXTEND given, suck up
2075 ;; the whole structure
2076 ((and extend
2077 (setq first-symbol (py-suck-up-first-keyword) )
2078 (assq first-symbol followers))
2079 (while (and
2080 (or (py-goto-beyond-block) t) ; side effect
2081 (forward-line -1) ; side effect
2082 (setq last-pos (point)) ; side effect
2083 (py-goto-statement-below)
2084 (= (current-indentation) initial-indent)
2085 (setq next-symbol (py-suck-up-first-keyword))
2086 (memq next-symbol (cdr (assq first-symbol followers))))
2087 (setq first-symbol next-symbol)))
2088
2089 ;; else if line *opens* a block, search for next stmt indented <=
2090 ((py-statement-opens-block-p)
2091 (while (and
2092 (setq last-pos (point)) ; always true -- side effect
2093 (py-goto-statement-below)
2094 (> (current-indentation) initial-indent))
2095 nil))
2096
2097 ;; else plain code line; stop at next blank line, or stmt or
2098 ;; indenting comment line indented <
2099 (t
2100 (while (and
2101 (setq last-pos (point)) ; always true -- side effect
2102 (or (py-goto-beyond-final-line) t)
2103 (not (looking-at "[ \t]*$")) ; stop at blank line
2104 (or
2105 (>= (current-indentation) initial-indent)
2106 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2107 nil)))
2108
2109 ;; skip to end of last stmt
2110 (goto-char last-pos)
2111 (py-goto-beyond-final-line)
2112
2113 ;; set mark & display
2114 (if just-move
2115 () ; just return
2116 (push-mark (point) 'no-msg)
2117 (forward-line -1)
2118 (message "Mark set after: %s" (py-suck-up-leading-text))
2119 (goto-char initial-pos))))
2120
Barry Warsaw2518c671997-11-05 00:51:08 +00002121(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002122 "Set region to body of def (or class, with prefix arg) enclosing point.
2123Pushes the current mark, then point, on the mark ring (all language
2124modes do this, but although it's handy it's never documented ...).
2125
2126In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002127hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2128`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002129
2130And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002131Turned out that was more confusing than useful: the `goto start' and
2132`goto end' commands are usually used to search through a file, and
2133people expect them to act a lot like `search backward' and `search
2134forward' string-search commands. But because Python `def' and `class'
2135can nest to arbitrary levels, finding the smallest def containing
2136point cannot be done via a simple backward search: the def containing
2137point may not be the closest preceding def, or even the closest
2138preceding def that's indented less. The fancy algorithm required is
2139appropriate for the usual uses of this `mark' command, but not for the
2140`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002142So the def marked by this command may not be the one either of the
2143`goto' commands find: If point is on a blank or non-indenting comment
2144line, moves back to start of the closest preceding code statement or
2145indenting comment line. If this is a `def' statement, that's the def
2146we use. Else searches for the smallest enclosing `def' block and uses
2147that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002148
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002149When an enclosing def is found: The mark is left immediately beyond
2150the last line of the def block. Point is left at the start of the
2151def, except that: if the def is preceded by a number of comment lines
2152followed by (at most) one optional blank line, point is left at the
2153start of the comments; else if the def is preceded by a blank line,
2154point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002155
2156The intent is to mark the containing def/class and its associated
2157documentation, to make moving and duplicating functions and classes
2158pleasant."
2159 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002160 (let ((start (point))
2161 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002162 (push-mark start)
2163 (if (not (py-go-up-tree-to-keyword which))
2164 (progn (goto-char start)
2165 (error "Enclosing %s not found" which))
2166 ;; else enclosing def/class found
2167 (setq start (point))
2168 (py-goto-beyond-block)
2169 (push-mark (point))
2170 (goto-char start)
2171 (if (zerop (forward-line -1)) ; if there is a preceding line
2172 (progn
2173 (if (looking-at "[ \t]*$") ; it's blank
2174 (setq start (point)) ; so reset start point
2175 (goto-char start)) ; else try again
2176 (if (zerop (forward-line -1))
2177 (if (looking-at "[ \t]*#") ; a comment
2178 ;; look back for non-comment line
2179 ;; tricky: note that the regexp matches a blank
2180 ;; line, cuz \n is in the 2nd character class
2181 (and
2182 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2183 (forward-line 1))
2184 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002185 (goto-char start)))))))
2186 (exchange-point-and-mark)
2187 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002188
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002189;; ripped from cc-mode
2190(defun py-forward-into-nomenclature (&optional arg)
2191 "Move forward to end of a nomenclature section or word.
2192With arg, to it arg times.
2193
2194A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2195 (interactive "p")
2196 (let ((case-fold-search nil))
2197 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002198 (re-search-forward
2199 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2200 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002201 (while (and (< arg 0)
2202 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002203 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002204 (point-min) 0))
2205 (forward-char 1)
2206 (setq arg (1+ arg)))))
2207 (py-keep-region-active))
2208
2209(defun py-backward-into-nomenclature (&optional arg)
2210 "Move backward to beginning of a nomenclature section or word.
2211With optional ARG, move that many times. If ARG is negative, move
2212forward.
2213
2214A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2215 (interactive "p")
2216 (py-forward-into-nomenclature (- arg))
2217 (py-keep-region-active))
2218
2219
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002220
2221;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002222
2223;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002224;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2225;; out of the right places, along with the keys they're on & current
2226;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227(defun py-dump-help-string (str)
2228 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002229 (let ((locals (buffer-local-variables))
2230 funckind funcname func funcdoc
2231 (start 0) mstart end
2232 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2234 (setq mstart (match-beginning 0) end (match-end 0)
2235 funckind (substring str (match-beginning 1) (match-end 1))
2236 funcname (substring str (match-beginning 2) (match-end 2))
2237 func (intern funcname))
2238 (princ (substitute-command-keys (substring str start mstart)))
2239 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002240 ((equal funckind "c") ; command
2241 (setq funcdoc (documentation func)
2242 keys (concat
2243 "Key(s): "
2244 (mapconcat 'key-description
2245 (where-is-internal func py-mode-map)
2246 ", "))))
2247 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002248 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002249 keys (if (assq func locals)
2250 (concat
2251 "Local/Global values: "
2252 (prin1-to-string (symbol-value func))
2253 " / "
2254 (prin1-to-string (default-value func)))
2255 (concat
2256 "Value: "
2257 (prin1-to-string (symbol-value func))))))
2258 (t ; unexpected
2259 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002260 (princ (format "\n-> %s:\t%s\t%s\n\n"
2261 (if (equal funckind "c") "Command" "Variable")
2262 funcname keys))
2263 (princ funcdoc)
2264 (terpri)
2265 (setq start end))
2266 (princ (substitute-command-keys (substring str start))))
2267 (print-help-return-message)))
2268
2269(defun py-describe-mode ()
2270 "Dump long form of Python-mode docs."
2271 (interactive)
2272 (py-dump-help-string "Major mode for editing Python files.
2273Knows about Python indentation, tokens, comments and continuation lines.
2274Paragraphs are separated by blank lines only.
2275
2276Major sections below begin with the string `@'; specific function and
2277variable docs begin with `->'.
2278
2279@EXECUTING PYTHON CODE
2280
2281\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2282\\[py-execute-region]\tsends the current region
2283\\[py-shell]\tstarts a Python interpreter window; this will be used by
2284\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2285%c:py-execute-buffer
2286%c:py-execute-region
2287%c:py-shell
2288
2289@VARIABLES
2290
2291py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002292py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002293
2294py-python-command\tshell command to invoke Python interpreter
2295py-scroll-process-buffer\talways scroll Python process buffer
2296py-temp-directory\tdirectory used for temp files (if needed)
2297
2298py-beep-if-tab-change\tring the bell if tab-width is changed
2299%v:py-indent-offset
2300%v:py-block-comment-prefix
2301%v:py-python-command
2302%v:py-scroll-process-buffer
2303%v:py-temp-directory
2304%v:py-beep-if-tab-change
2305
2306@KINDS OF LINES
2307
2308Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002309preceding line ends with a backslash that's not part of a comment, or
2310the paren/bracket/brace nesting level at the start of the line is
2311non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002312
2313An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002314possibly blanks or tabs), a `comment line' (leftmost non-blank
2315character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002316
2317Comment Lines
2318
2319Although all comment lines are treated alike by Python, Python mode
2320recognizes two kinds that act differently with respect to indentation.
2321
2322An `indenting comment line' is a comment line with a blank, tab or
2323nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002324treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002325indenting comment line will be indented like the comment line. All
2326other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002327following the initial `#') are `non-indenting comment lines', and
2328their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329
2330Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002331whenever possible. Non-indenting comment lines are useful in cases
2332like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333
2334\ta = b # a very wordy single-line comment that ends up being
2335\t #... continued onto another line
2336
2337\tif a == b:
2338##\t\tprint 'panic!' # old code we've `commented out'
2339\t\treturn a
2340
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002341Since the `#...' and `##' comment lines have a non-whitespace
2342character following the initial `#', Python mode ignores them when
2343computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002344
2345Continuation Lines and Statements
2346
2347The Python-mode commands generally work on statements instead of on
2348individual lines, where a `statement' is a comment or blank line, or a
2349code line and all of its following continuation lines (if any)
2350considered as a single logical unit. The commands in this mode
2351generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002352statement containing point, even if point happens to be in the middle
2353of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002354
2355
2356@INDENTATION
2357
2358Primarily for entering new code:
2359\t\\[indent-for-tab-command]\t indent line appropriately
2360\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002361\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002362
2363Primarily for reindenting existing code:
2364\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2365\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2366
2367\t\\[py-indent-region]\t reindent region to match its context
2368\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2369\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2370
2371Unlike most programming languages, Python uses indentation, and only
2372indentation, to specify block structure. Hence the indentation supplied
2373automatically by Python-mode is just an educated guess: only you know
2374the block structure you intend, so only you can supply correct
2375indentation.
2376
2377The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2378the indentation of preceding statements. E.g., assuming
2379py-indent-offset is 4, after you enter
2380\tif a > 0: \\[py-newline-and-indent]
2381the cursor will be moved to the position of the `_' (_ is not a
2382character in the file, it's just used here to indicate the location of
2383the cursor):
2384\tif a > 0:
2385\t _
2386If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2387to
2388\tif a > 0:
2389\t c = d
2390\t _
2391Python-mode cannot know whether that's what you intended, or whether
2392\tif a > 0:
2393\t c = d
2394\t_
2395was your intent. In general, Python-mode either reproduces the
2396indentation of the (closest code or indenting-comment) preceding
2397statement, or adds an extra py-indent-offset blanks if the preceding
2398statement has `:' as its last significant (non-whitespace and non-
2399comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002400\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002401
2402Continuation lines are given extra indentation. If you don't like the
2403suggested indentation, change it to something you do like, and Python-
2404mode will strive to indent later lines of the statement in the same way.
2405
2406If a line is a continuation line by virtue of being in an unclosed
2407paren/bracket/brace structure (`list', for short), the suggested
2408indentation depends on whether the current line contains the first item
2409in the list. If it does, it's indented py-indent-offset columns beyond
2410the indentation of the line containing the open bracket. If you don't
2411like that, change it by hand. The remaining items in the list will mimic
2412whatever indentation you give to the first item.
2413
2414If a line is a continuation line because the line preceding it ends with
2415a backslash, the third and following lines of the statement inherit their
2416indentation from the line preceding them. The indentation of the second
2417line in the statement depends on the form of the first (base) line: if
2418the base line is an assignment statement with anything more interesting
2419than the backslash following the leftmost assigning `=', the second line
2420is indented two columns beyond that `='. Else it's indented to two
2421columns beyond the leftmost solid chunk of non-whitespace characters on
2422the base line.
2423
2424Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2425repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2426structure you intend.
2427%c:indent-for-tab-command
2428%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002429%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002430
2431
2432The next function may be handy when editing code you didn't write:
2433%c:py-guess-indent-offset
2434
2435
2436The remaining `indent' functions apply to a region of Python code. They
2437assume the block structure (equals indentation, in Python) of the region
2438is correct, and alter the indentation in various ways while preserving
2439the block structure:
2440%c:py-indent-region
2441%c:py-shift-region-left
2442%c:py-shift-region-right
2443
2444@MARKING & MANIPULATING REGIONS OF CODE
2445
2446\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002447\\[py-mark-def-or-class]\t mark smallest enclosing def
2448\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002449\\[comment-region]\t comment out region of code
2450\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002451%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002452%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002453%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002454
2455@MOVING POINT
2456
2457\\[py-previous-statement]\t move to statement preceding point
2458\\[py-next-statement]\t move to statement following point
2459\\[py-goto-block-up]\t move up to start of current block
2460\\[beginning-of-python-def-or-class]\t move to start of def
2461\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2462\\[end-of-python-def-or-class]\t move to end of def
2463\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2464
2465The first two move to one statement beyond the statement that contains
2466point. A numeric prefix argument tells them to move that many
2467statements instead. Blank lines, comment lines, and continuation lines
2468do not count as `statements' for these commands. So, e.g., you can go
2469to the first code statement in a file by entering
2470\t\\[beginning-of-buffer]\t to move to the top of the file
2471\t\\[py-next-statement]\t to skip over initial comments and blank lines
2472Or do `\\[py-previous-statement]' with a huge prefix argument.
2473%c:py-previous-statement
2474%c:py-next-statement
2475%c:py-goto-block-up
2476%c:beginning-of-python-def-or-class
2477%c:end-of-python-def-or-class
2478
2479@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2480
2481`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2482
2483`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2484overall class and def structure of a module.
2485
2486`\\[back-to-indentation]' moves point to a line's first non-blank character.
2487
2488`\\[indent-relative]' is handy for creating odd indentation.
2489
2490@OTHER EMACS HINTS
2491
2492If you don't like the default value of a variable, change its value to
2493whatever you do like by putting a `setq' line in your .emacs file.
2494E.g., to set the indentation increment to 4, put this line in your
2495.emacs:
2496\t(setq py-indent-offset 4)
2497To see the value of a variable, do `\\[describe-variable]' and enter the variable
2498name at the prompt.
2499
2500When entering a key sequence like `C-c C-n', it is not necessary to
2501release the CONTROL key after doing the `C-c' part -- it suffices to
2502press the CONTROL key, press and release `c' (while still holding down
2503CONTROL), press and release `n' (while still holding down CONTROL), &
2504then release CONTROL.
2505
2506Entering Python mode calls with no arguments the value of the variable
2507`python-mode-hook', if that value exists and is not nil; for backward
2508compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2509the Elisp manual for details.
2510
2511Obscure: When python-mode is first loaded, it looks for all bindings
2512to newline-and-indent in the global keymap, and shadows them with
2513local bindings to py-newline-and-indent."))
2514
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002515
2516;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002517(defvar py-parse-state-re
2518 (concat
2519 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2520 "\\|"
2521 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002522
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523;; returns the parse state at point (see parse-partial-sexp docs)
2524(defun py-parse-state ()
2525 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002526 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002527 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002528 (while (not done)
2529 ;; back up to the first preceding line (if any; else start of
2530 ;; buffer) that begins with a popular Python keyword, or a
2531 ;; non- whitespace and non-comment character. These are good
2532 ;; places to start parsing to see whether where we started is
2533 ;; at a non-zero nesting level. It may be slow for people who
2534 ;; write huge code blocks or huge lists ... tough beans.
2535 (re-search-backward py-parse-state-re nil 'move)
2536 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002537 ;; In XEmacs, we have a much better way to test for whether
2538 ;; we're in a triple-quoted string or not. Emacs does not
2539 ;; have this built-in function, which is it's loss because
2540 ;; without scanning from the beginning of the buffer, there's
2541 ;; no accurate way to determine this otherwise.
2542 (if (not (fboundp 'buffer-syntactic-context))
2543 ;; Emacs
2544 (save-excursion
2545 (setq pps (parse-partial-sexp (point) here))
2546 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002547 (setq done (or (not (nth 3 pps))
2548 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002549 ;; XEmacs
2550 (setq done (or (not (buffer-syntactic-context))
2551 (bobp)))
2552 (when done
2553 (setq pps (parse-partial-sexp (point) here)))
2554 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002555 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002556
2557;; if point is at a non-zero nesting level, returns the number of the
2558;; character that opens the smallest enclosing unclosed list; else
2559;; returns nil.
2560(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002561 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002562 (if (zerop (car status))
2563 nil ; not in a nest
2564 (car (cdr status))))) ; char# of open bracket
2565
2566;; t iff preceding line ends with backslash that's not in a comment
2567(defun py-backslash-continuation-line-p ()
2568 (save-excursion
2569 (beginning-of-line)
2570 (and
2571 ;; use a cheap test first to avoid the regexp if possible
2572 ;; use 'eq' because char-after may return nil
2573 (eq (char-after (- (point) 2)) ?\\ )
2574 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002575 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002576 (looking-at py-continued-re))))
2577
2578;; t iff current line is a continuation line
2579(defun py-continuation-line-p ()
2580 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002581 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002582 (or (py-backslash-continuation-line-p)
2583 (py-nesting-level))))
2584
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002585;; go to initial line of current statement; usually this is the line
2586;; we're on, but if we're on the 2nd or following lines of a
2587;; continuation block, we need to go up to the first line of the
2588;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002589;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002590;; Tricky: We want to avoid quadratic-time behavior for long continued
2591;; blocks, whether of the backslash or open-bracket varieties, or a
2592;; mix of the two. The following manages to do that in the usual
2593;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002594;;
2595;; Also, if we're sitting inside a triple quoted string, this will
2596;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002597(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002598 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002599 (while (py-continuation-line-p)
2600 (beginning-of-line)
2601 (if (py-backslash-continuation-line-p)
2602 (while (py-backslash-continuation-line-p)
2603 (forward-line -1))
2604 ;; else zip out of nested brackets/braces/parens
2605 (while (setq open-bracket-pos (py-nesting-level))
2606 (goto-char open-bracket-pos)))))
2607 (beginning-of-line))
2608
2609;; go to point right beyond final line of current statement; usually
2610;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002611;; statement we need to skip over the continuation lines. Tricky:
2612;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002613(defun py-goto-beyond-final-line ()
2614 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002615 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002616 (while (and (py-continuation-line-p)
2617 (not (eobp)))
2618 ;; skip over the backslash flavor
2619 (while (and (py-backslash-continuation-line-p)
2620 (not (eobp)))
2621 (forward-line 1))
2622 ;; if in nest, zip to the end of the nest
2623 (setq state (py-parse-state))
2624 (if (and (not (zerop (car state)))
2625 (not (eobp)))
2626 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002627 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002628 (forward-line 1))))))
2629
2630;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002631;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002632(defun py-statement-opens-block-p ()
2633 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002634 (let ((start (point))
2635 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2636 (searching t)
2637 (answer nil)
2638 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002639 (goto-char start)
2640 (while searching
2641 ;; look for a colon with nothing after it except whitespace, and
2642 ;; maybe a comment
2643 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2644 finish t)
2645 (if (eq (point) finish) ; note: no `else' clause; just
2646 ; keep searching if we're not at
2647 ; the end yet
2648 ;; sure looks like it opens a block -- but it might
2649 ;; be in a comment
2650 (progn
2651 (setq searching nil) ; search is done either way
2652 (setq state (parse-partial-sexp start
2653 (match-beginning 0)))
2654 (setq answer (not (nth 4 state)))))
2655 ;; search failed: couldn't find another interesting colon
2656 (setq searching nil)))
2657 answer)))
2658
Barry Warsawf831d811996-07-31 20:42:59 +00002659(defun py-statement-closes-block-p ()
2660 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002661 ;; starts with `return', `raise', `break', `continue', and `pass'.
2662 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002663 (let ((here (point)))
2664 (back-to-indentation)
2665 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002666 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002667 (goto-char here))))
2668
Barry Warsaw7ae77681994-12-12 20:38:05 +00002669;; go to point right beyond final line of block begun by the current
2670;; line. This is the same as where py-goto-beyond-final-line goes
2671;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002672;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002673(defun py-goto-beyond-block ()
2674 (if (py-statement-opens-block-p)
2675 (py-mark-block nil 'just-move)
2676 (py-goto-beyond-final-line)))
2677
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002678;; go to start of first statement (not blank or comment or
2679;; continuation line) at or preceding point. returns t if there is
2680;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002681(defun py-goto-statement-at-or-above ()
2682 (py-goto-initial-line)
2683 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002684 ;; skip back over blank & comment lines
2685 ;; note: will skip a blank or comment line that happens to be
2686 ;; a continuation line too
2687 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2688 (progn (py-goto-initial-line) t)
2689 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002690 t))
2691
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002692;; go to start of first statement (not blank or comment or
2693;; continuation line) following the statement containing point returns
2694;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002695(defun py-goto-statement-below ()
2696 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002697 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002698 (py-goto-beyond-final-line)
2699 (while (and
2700 (looking-at py-blank-or-comment-re)
2701 (not (eobp)))
2702 (forward-line 1))
2703 (if (eobp)
2704 (progn (goto-char start) nil)
2705 t)))
2706
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002707;; go to start of statement, at or preceding point, starting with
2708;; keyword KEY. Skips blank lines and non-indenting comments upward
2709;; first. If that statement starts with KEY, done, else go back to
2710;; first enclosing block starting with KEY. If successful, leaves
2711;; point at the start of the KEY line & returns t. Else leaves point
2712;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002713(defun py-go-up-tree-to-keyword (key)
2714 ;; skip blanks and non-indenting #
2715 (py-goto-initial-line)
2716 (while (and
2717 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2718 (zerop (forward-line -1))) ; go back
2719 nil)
2720 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002721 (let* ((re (concat "[ \t]*" key "\\b"))
2722 (case-fold-search nil) ; let* so looking-at sees this
2723 (found (looking-at re))
2724 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002725 (while (not (or found dead))
2726 (condition-case nil ; in case no enclosing block
2727 (py-goto-block-up 'no-mark)
2728 (error (setq dead t)))
2729 (or dead (setq found (looking-at re))))
2730 (beginning-of-line)
2731 found))
2732
2733;; return string in buffer from start of indentation to end of line;
2734;; prefix "..." if leading whitespace was skipped
2735(defun py-suck-up-leading-text ()
2736 (save-excursion
2737 (back-to-indentation)
2738 (concat
2739 (if (bolp) "" "...")
2740 (buffer-substring (point) (progn (end-of-line) (point))))))
2741
2742;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2743;; as a Lisp symbol; return nil if none
2744(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002745 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002746 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2747 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2748 nil)))
2749
Barry Warsawb3e81d51996-09-04 15:12:42 +00002750(defun py-current-defun ()
2751 ;; tell add-log.el how to find the current function/method/variable
2752 (save-excursion
2753 (if (re-search-backward py-defun-start-re nil t)
2754 (or (match-string 3)
2755 (let ((method (match-string 2)))
2756 (if (and (not (zerop (length (match-string 1))))
2757 (re-search-backward py-class-start-re nil t))
2758 (concat (match-string 1) "." method)
2759 method)))
2760 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002761
2762
Barry Warsawfec75d61995-07-05 23:26:15 +00002763(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002764 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002765
Barry Warsaw850437a1995-03-08 21:50:28 +00002766(defun py-version ()
2767 "Echo the current version of `python-mode' in the minibuffer."
2768 (interactive)
2769 (message "Using `python-mode' version %s" py-version)
2770 (py-keep-region-active))
2771
2772;; only works under Emacs 19
2773;(eval-when-compile
2774; (require 'reporter))
2775
2776(defun py-submit-bug-report (enhancement-p)
2777 "Submit via mail a bug report on `python-mode'.
2778With \\[universal-argument] just submit an enhancement request."
2779 (interactive
2780 (list (not (y-or-n-p
2781 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002782 (let ((reporter-prompt-for-summary-p (if enhancement-p
2783 "(Very) brief summary: "
2784 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002785 (require 'reporter)
2786 (reporter-submit-bug-report
2787 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002788 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002789 ;; varlist
2790 (if enhancement-p nil
2791 '(py-python-command
2792 py-indent-offset
2793 py-block-comment-prefix
2794 py-scroll-process-buffer
2795 py-temp-directory
2796 py-beep-if-tab-change))
2797 nil ;pre-hooks
2798 nil ;post-hooks
2799 "Dear Barry,") ;salutation
2800 (if enhancement-p nil
2801 (set-mark (point))
2802 (insert
2803"Please replace this text with a sufficiently large code sample\n\
2804and an exact recipe so that I can reproduce your problem. Failure\n\
2805to do so may mean a greater delay in fixing your bug.\n\n")
2806 (exchange-point-and-mark)
2807 (py-keep-region-active))))
2808
2809
Barry Warsaw47384781997-11-26 05:27:45 +00002810(defun py-kill-emacs-hook ()
2811 (mapcar #'(lambda (filename)
2812 (py-safe (delete-file filename)))
2813 py-file-queue))
2814
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002815;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002816(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002817
2818
2819
2820(provide 'python-mode)
2821;;; python-mode.el ends here