blob: 45eadfe3deeb04d1645f20f93351725bb5405746 [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 Warsaw0d2805b1998-03-19 21:52:06 +0000312(defface py-tab-face nil
313 "Face that tabs are displayed in.
314To quickly see mixed tabs/spaces, use \\[customize-face] and set the
315background of `py-tab-face' to something obnoxious (like \"Yellow\")."
316 :group 'python)
317
Barry Warsawc0ecb531998-01-20 21:43:34 +0000318;; Not customizable
319(defvar py-master-file nil
320 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000321The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000322variable section, e.g.:
323
324 # Local Variables:
325 # py-master-file: \"master.py\"
326 # End:
327
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000328so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000329named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000330name has a relative path, the `default-directory' for the buffer is
331prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000332(make-variable-buffer-local 'py-master-file)
333
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000334
Barry Warsawc72c11c1997-08-09 06:42:08 +0000335
336;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
337;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
338
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000339(defconst py-emacs-features
340 (let (features)
341 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
342 ;; the same string.
343 (let ((tmp1 (make-temp-name ""))
344 (tmp2 (make-temp-name "")))
345 (if (string-equal tmp1 tmp2)
346 (push 'broken-temp-names features)))
347 ;; return the features
348 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000349 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000350There are many flavors of Emacs out there, with different levels of
351support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000352
Barry Warsawfb07f401997-02-24 03:37:22 +0000353(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000354 (let ((kw1 (mapconcat 'identity
355 '("and" "assert" "break" "class"
356 "continue" "def" "del" "elif"
357 "else" "except" "exec" "for"
358 "from" "global" "if" "import"
359 "in" "is" "lambda" "not"
360 "or" "pass" "print" "raise"
361 "return" "while"
362 )
363 "\\|"))
364 (kw2 (mapconcat 'identity
365 '("else:" "except:" "finally:" "try:")
366 "\\|"))
367 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000368 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000369 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000370 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
371 ;; block introducing keywords with immediately following colons.
372 ;; Yes "except" is in both lists.
373 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000374 ;; classes
375 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
376 1 font-lock-type-face)
377 ;; functions
378 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
379 1 font-lock-function-name-face)
Barry Warsaw0d2805b1998-03-19 21:52:06 +0000380 ;; tabs
381 '("^[\t]+" 0 py-tab-face)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000382 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000383 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000384(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
385
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000386
Barry Warsaw81437461996-08-01 19:48:02 +0000387(defvar imenu-example--python-show-method-args-p nil
388 "*Controls echoing of arguments of functions & methods in the imenu buffer.
389When non-nil, arguments are printed.")
390
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000391(make-variable-buffer-local 'py-indent-offset)
392
Barry Warsawe467bfb1997-11-26 05:40:58 +0000393;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000394(defvar py-file-queue nil
395 "Queue of Python temp files awaiting execution.
396Currently-active file is at the head of the list.")
397
Barry Warsawc72c11c1997-08-09 06:42:08 +0000398
399;; Constants
400
401;; Regexp matching a Python string literal
402(defconst py-stringlit-re
403 (concat
404 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
405 "\\|" ; or
406 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
407
408;; Regexp matching Python lines that are continued via backslash.
409;; This is tricky because a trailing backslash does not mean
410;; continuation if it's in a comment
411(defconst py-continued-re
412 (concat
413 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
414 "\\\\$"))
415
416;; Regexp matching blank or comment lines.
417(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
418
419;; Regexp matching clauses to be outdented one level.
420(defconst py-outdent-re
421 (concat "\\(" (mapconcat 'identity
422 '("else:"
423 "except\\(\\s +.*\\)?:"
424 "finally:"
425 "elif\\s +.*:")
426 "\\|")
427 "\\)"))
428
429
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000430;; Regexp matching keywords which typically close a block
431(defconst py-block-closing-keywords-re
432 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
433
Barry Warsawc72c11c1997-08-09 06:42:08 +0000434;; Regexp matching lines to not outdent after.
435(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000436 (concat
437 "\\("
438 (mapconcat 'identity
439 (list "try:"
440 "except\\(\\s +.*\\)?:"
441 "while\\s +.*:"
442 "for\\s +.*:"
443 "if\\s +.*:"
444 "elif\\s +.*:"
445 (concat py-block-closing-keywords-re "[ \t\n]")
446 )
447 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000448 "\\)"))
449
450;; Regexp matching a function, method or variable assignment. If you
451;; change this, you probably have to change `py-current-defun' as
452;; well. This is only used by `py-current-defun' to find the name for
453;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000454(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000455 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
456
457;; Regexp for finding a class name. If you change this, you probably
458;; have to change `py-current-defun' as well. This is only used by
459;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000460(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
461
462;; Regexp that describes tracebacks
463(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000464 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000465
466
467
468;; Utilities
469
470(defmacro py-safe (&rest body)
471 ;; safely execute BODY, return nil if an error occurred
472 (` (condition-case nil
473 (progn (,@ body))
474 (error nil))))
475
476(defsubst py-keep-region-active ()
477 ;; Do whatever is necessary to keep the region active in XEmacs.
478 ;; Ignore byte-compiler warnings you might see. Also note that
479 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
480 ;; to take explicit action.
481 (and (boundp 'zmacs-region-stays)
482 (setq zmacs-region-stays t)))
483
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000484(defsubst py-point (position)
485 ;; Returns the value of point at certain commonly referenced POSITIONs.
486 ;; POSITION can be one of the following symbols:
487 ;;
488 ;; bol -- beginning of line
489 ;; eol -- end of line
490 ;; bod -- beginning of defun
491 ;; boi -- back to indentation
492 ;;
493 ;; This function does not modify point or mark.
494 (let ((here (point)))
495 (cond
496 ((eq position 'bol) (beginning-of-line))
497 ((eq position 'eol) (end-of-line))
498 ((eq position 'bod) (beginning-of-python-def-or-class))
499 ((eq position 'bob) (beginning-of-buffer))
500 ((eq position 'eob) (end-of-buffer))
501 ((eq position 'boi) (back-to-indentation))
502 (t (error "unknown buffer position requested: %s" position))
503 )
504 (prog1
505 (point)
506 (goto-char here))))
507
508(defsubst py-highlight-line (from to file line)
509 (cond
510 ((fboundp 'make-extent)
511 ;; XEmacs
512 (let ((e (make-extent from to)))
513 (set-extent-property e 'mouse-face 'highlight)
514 (set-extent-property e 'py-exc-info (cons file line))
515 (set-extent-property e 'keymap py-mode-output-map)))
516 (t
517 ;; Emacs -- Please port this!
518 )
519 ))
520
Barry Warsawe908b6b1998-03-19 22:48:02 +0000521(defun py-in-literal (&optional lim)
522 ;; Determine if point is in a Python literal, defined as a comment
523 ;; or string. This is the version used for non-XEmacs, which has a
524 ;; nicer interface.
525 ;;
526 ;; WARNING: Watch out for infinite recursion.
527 (let* ((lim (or lim (c-point 'bod)))
528 (state (parse-partial-sexp lim (point))))
529 (cond
530 ((nth 3 state) 'string)
531 ((nth 4 state) 'comment)
532 (t nil))))
533
534;; XEmacs has a built-in function that should make this much quicker.
535;; In this case, lim is ignored
536(defun py-fast-in-literal (&optional lim)
537 ;; don't have to worry about context == 'block-comment
538 (buffer-syntactic-context))
539
540(if (fboundp 'buffer-syntactic-context)
541 (defalias 'c-in-literal 'c-fast-in-literal))
542
543
Barry Warsawc72c11c1997-08-09 06:42:08 +0000544
545;; Major mode boilerplate
546
Barry Warsaw7ae77681994-12-12 20:38:05 +0000547;; define a mode-specific abbrev table for those who use such things
548(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000549 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000550(define-abbrev-table 'python-mode-abbrev-table nil)
551
Barry Warsaw7ae77681994-12-12 20:38:05 +0000552(defvar python-mode-hook nil
553 "*Hook called by `python-mode'.")
554
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000555;; in previous version of python-mode.el, the hook was incorrectly
556;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557(and (fboundp 'make-obsolete-variable)
558 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
559
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000560(defvar py-mode-map ()
561 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000562(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000563 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000565 ;; electric keys
566 (define-key py-mode-map ":" 'py-electric-colon)
567 ;; indentation level modifiers
568 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
569 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
570 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
571 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
572 ;; subprocess commands
573 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
574 (define-key py-mode-map "\C-c|" 'py-execute-region)
575 (define-key py-mode-map "\C-c!" 'py-shell)
576 ;; Caution! Enter here at your own risk. We are trying to support
577 ;; several behaviors and it gets disgusting. :-( This logic ripped
578 ;; largely from CC Mode.
579 ;;
580 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
581 ;; backwards deletion behavior to DEL, which both Delete and
582 ;; Backspace get translated to. There's no way to separate this
583 ;; behavior in a clean way, so deal with it! Besides, it's been
584 ;; this way since the dawn of time.
585 (if (not (boundp 'delete-key-deletes-forward))
586 (define-key py-mode-map "\177" 'py-electric-backspace)
587 ;; However, XEmacs 20 actually achieved enlightenment. It is
588 ;; possible to sanely define both backward and forward deletion
589 ;; behavior under X separately (TTYs are forever beyond hope, but
590 ;; who cares? XEmacs 20 does the right thing with these too).
591 (define-key py-mode-map [delete] 'py-electric-delete)
592 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000593 ;; Separate M-BS from C-M-h. The former should remain
594 ;; backward-kill-word.
595 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000596 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000597 ;; Miscellaneous
598 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
599 (define-key py-mode-map "\C-c\t" 'py-indent-region)
600 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
601 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
602 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000603 (define-key py-mode-map "\C-c#" 'py-comment-region)
604 (define-key py-mode-map "\C-c?" 'py-describe-mode)
605 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
606 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
607 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000608 (define-key py-mode-map "\C-c-" 'py-up-exception)
609 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000610 ;; information
611 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
612 (define-key py-mode-map "\C-c\C-v" 'py-version)
613 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000614 (define-key py-mode-map "\n" 'py-newline-and-indent)
615 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000616 ;; shadow global bindings for newline-and-indent w/ the py- version.
617 ;; BAW - this is extremely bad form, but I'm not going to change it
618 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000619 (mapcar #'(lambda (key)
620 (define-key py-mode-map key 'py-newline-and-indent))
621 (where-is-internal 'newline-and-indent))
622 )
623
624(defvar py-mode-output-map nil
625 "Keymap used in *Python Output* buffers*")
626(if py-mode-output-map
627 nil
628 (setq py-mode-output-map (make-sparse-keymap))
629 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
630 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
631 ;; TBD: Disable all self-inserting keys. This is bogus, we should
632 ;; really implement this as *Python Output* buffer being read-only
633 (mapcar #' (lambda (key)
634 (define-key py-mode-output-map key
635 #'(lambda () (interactive) (beep))))
636 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000637 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000638
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000639(defvar py-mode-syntax-table nil
640 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000641(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000642 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000643 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000644 (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 ;; Add operator symbols misassigned in the std 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 (modify-syntax-entry ?\* "." py-mode-syntax-table)
655 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
656 (modify-syntax-entry ?\- "." py-mode-syntax-table)
657 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
658 (modify-syntax-entry ?\< "." py-mode-syntax-table)
659 (modify-syntax-entry ?\= "." py-mode-syntax-table)
660 (modify-syntax-entry ?\> "." py-mode-syntax-table)
661 (modify-syntax-entry ?\| "." py-mode-syntax-table)
662 ;; For historical reasons, underscore is word class instead of
663 ;; symbol class. GNU conventions say it should be symbol class, but
664 ;; there's a natural conflict between what major mode authors want
665 ;; and what users expect from `forward-word' and `backward-word'.
666 ;; Guido and I have hashed this out and have decided to keep
667 ;; underscore in word class. If you're tempted to change it, try
668 ;; binding M-f and M-b to py-forward-into-nomenclature and
669 ;; py-backward-into-nomenclature instead.
670 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
671 ;; Both single quote and double quote are string delimiters
672 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
673 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
674 ;; backquote is open and close paren
675 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
676 ;; comment delimiters
677 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
678 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
679 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000680
Barry Warsawb3e81d51996-09-04 15:12:42 +0000681
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000682
Barry Warsaw42f707f1996-07-29 21:05:05 +0000683;; Menu definitions, only relevent if you have the easymenu.el package
684;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000685(defvar py-menu nil
686 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000687This menu will get created automatically if you have the `easymenu'
688package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000689
Barry Warsawc72c11c1997-08-09 06:42:08 +0000690(and (py-safe (require 'easymenu) t)
691 (easy-menu-define
692 py-menu py-mode-map "Python Mode menu"
693 '("Python"
694 ["Comment Out Region" py-comment-region (mark)]
695 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
696 "-"
697 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000698 ["Mark current def" py-mark-def-or-class t]
699 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000700 "-"
701 ["Shift region left" py-shift-region-left (mark)]
702 ["Shift region right" py-shift-region-right (mark)]
703 "-"
704 ["Execute buffer" py-execute-buffer t]
705 ["Execute region" py-execute-region (mark)]
706 ["Start interpreter..." py-shell t]
707 "-"
708 ["Go to start of block" py-goto-block-up t]
709 ["Go to start of class" (beginning-of-python-def-or-class t) t]
710 ["Move to end of class" (end-of-python-def-or-class t) t]
711 ["Move to start of def" beginning-of-python-def-or-class t]
712 ["Move to end of def" end-of-python-def-or-class t]
713 "-"
714 ["Describe mode" py-describe-mode t]
715 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000716
Barry Warsaw81437461996-08-01 19:48:02 +0000717
718
719;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
720(defvar imenu-example--python-class-regexp
721 (concat ; <<classes>>
722 "\\(" ;
723 "^[ \t]*" ; newline and maybe whitespace
724 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
725 ; possibly multiple superclasses
726 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
727 "[ \t]*:" ; and the final :
728 "\\)" ; >>classes<<
729 )
730 "Regexp for Python classes for use with the imenu package."
731 )
732
733(defvar imenu-example--python-method-regexp
734 (concat ; <<methods and functions>>
735 "\\(" ;
736 "^[ \t]*" ; new line and maybe whitespace
737 "\\(def[ \t]+" ; function definitions start with def
738 "\\([a-zA-Z0-9_]+\\)" ; name is here
739 ; function arguments...
740 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
741 "\\)" ; end of def
742 "[ \t]*:" ; and then the :
743 "\\)" ; >>methods and functions<<
744 )
745 "Regexp for Python methods/functions for use with the imenu package."
746 )
747
748(defvar imenu-example--python-method-no-arg-parens '(2 8)
749 "Indicies into groups of the Python regexp for use with imenu.
750
751Using these values will result in smaller imenu lists, as arguments to
752functions are not listed.
753
754See the variable `imenu-example--python-show-method-args-p' for more
755information.")
756
757(defvar imenu-example--python-method-arg-parens '(2 7)
758 "Indicies into groups of the Python regexp for use with imenu.
759Using these values will result in large imenu lists, as arguments to
760functions are listed.
761
762See the variable `imenu-example--python-show-method-args-p' for more
763information.")
764
765;; Note that in this format, this variable can still be used with the
766;; imenu--generic-function. Otherwise, there is no real reason to have
767;; it.
768(defvar imenu-example--generic-python-expression
769 (cons
770 (concat
771 imenu-example--python-class-regexp
772 "\\|" ; or...
773 imenu-example--python-method-regexp
774 )
775 imenu-example--python-method-no-arg-parens)
776 "Generic Python expression which may be used directly with imenu.
777Used by setting the variable `imenu-generic-expression' to this value.
778Also, see the function \\[imenu-example--create-python-index] for a
779better alternative for finding the index.")
780
781;; These next two variables are used when searching for the python
782;; class/definitions. Just saving some time in accessing the
783;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000784(defvar imenu-example--python-generic-regexp nil)
785(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000786
787
Barry Warsaw81437461996-08-01 19:48:02 +0000788(defun imenu-example--create-python-index ()
789 "Python interface function for imenu package.
790Finds all python classes and functions/methods. Calls function
791\\[imenu-example--create-python-index-engine]. See that function for
792the details of how this works."
793 (setq imenu-example--python-generic-regexp
794 (car imenu-example--generic-python-expression))
795 (setq imenu-example--python-generic-parens
796 (if imenu-example--python-show-method-args-p
797 imenu-example--python-method-arg-parens
798 imenu-example--python-method-no-arg-parens))
799 (goto-char (point-min))
800 (imenu-example--create-python-index-engine nil))
801
802(defun imenu-example--create-python-index-engine (&optional start-indent)
803 "Function for finding imenu definitions in Python.
804
805Finds all definitions (classes, methods, or functions) in a Python
806file for the imenu package.
807
808Returns a possibly nested alist of the form
809
810 (INDEX-NAME . INDEX-POSITION)
811
812The second element of the alist may be an alist, producing a nested
813list as in
814
815 (INDEX-NAME . INDEX-ALIST)
816
817This function should not be called directly, as it calls itself
818recursively and requires some setup. Rather this is the engine for
819the function \\[imenu-example--create-python-index].
820
821It works recursively by looking for all definitions at the current
822indention level. When it finds one, it adds it to the alist. If it
823finds a definition at a greater indentation level, it removes the
824previous definition from the alist. In it's place it adds all
825definitions found at the next indentation level. When it finds a
826definition that is less indented then the current level, it retuns the
827alist it has created thus far.
828
829The optional argument START-INDENT indicates the starting indentation
830at which to continue looking for Python classes, methods, or
831functions. If this is not supplied, the function uses the indentation
832of the first definition found."
833 (let ((index-alist '())
834 (sub-method-alist '())
835 looking-p
836 def-name prev-name
837 cur-indent def-pos
838 (class-paren (first imenu-example--python-generic-parens))
839 (def-paren (second imenu-example--python-generic-parens)))
840 (setq looking-p
841 (re-search-forward imenu-example--python-generic-regexp
842 (point-max) t))
843 (while looking-p
844 (save-excursion
845 ;; used to set def-name to this value but generic-extract-name is
846 ;; new to imenu-1.14. this way it still works with imenu-1.11
847 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
848 (let ((cur-paren (if (match-beginning class-paren)
849 class-paren def-paren)))
850 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000851 (buffer-substring-no-properties (match-beginning cur-paren)
852 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000853 (beginning-of-line)
854 (setq cur-indent (current-indentation)))
855
856 ;; HACK: want to go to the next correct definition location. we
857 ;; explicitly list them here. would be better to have them in a
858 ;; list.
859 (setq def-pos
860 (or (match-beginning class-paren)
861 (match-beginning def-paren)))
862
863 ;; if we don't have a starting indent level, take this one
864 (or start-indent
865 (setq start-indent cur-indent))
866
867 ;; if we don't have class name yet, take this one
868 (or prev-name
869 (setq prev-name def-name))
870
871 ;; what level is the next definition on? must be same, deeper
872 ;; or shallower indentation
873 (cond
874 ;; at the same indent level, add it to the list...
875 ((= start-indent cur-indent)
876
877 ;; if we don't have push, use the following...
878 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
879 (push (cons def-name def-pos) index-alist))
880
881 ;; deeper indented expression, recur...
882 ((< start-indent cur-indent)
883
884 ;; the point is currently on the expression we're supposed to
885 ;; start on, so go back to the last expression. The recursive
886 ;; call will find this place again and add it to the correct
887 ;; list
888 (re-search-backward imenu-example--python-generic-regexp
889 (point-min) 'move)
890 (setq sub-method-alist (imenu-example--create-python-index-engine
891 cur-indent))
892
893 (if sub-method-alist
894 ;; we put the last element on the index-alist on the start
895 ;; of the submethod alist so the user can still get to it.
896 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000897 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000898 (cons save-elmt sub-method-alist))
899 index-alist))))
900
901 ;; found less indented expression, we're done.
902 (t
903 (setq looking-p nil)
904 (re-search-backward imenu-example--python-generic-regexp
905 (point-min) t)))
906 (setq prev-name def-name)
907 (and looking-p
908 (setq looking-p
909 (re-search-forward imenu-example--python-generic-regexp
910 (point-max) 'move))))
911 (nreverse index-alist)))
912
Barry Warsaw42f707f1996-07-29 21:05:05 +0000913
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000914;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000915(defun python-mode ()
916 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917To submit a problem report, enter `\\[py-submit-bug-report]' from a
918`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
919documentation. To see what version of `python-mode' you are running,
920enter `\\[py-version]'.
921
922This mode knows about Python indentation, tokens, comments and
923continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000924
925COMMANDS
926\\{py-mode-map}
927VARIABLES
928
Barry Warsaw42f707f1996-07-29 21:05:05 +0000929py-indent-offset\t\tindentation increment
930py-block-comment-prefix\t\tcomment string used by comment-region
931py-python-command\t\tshell command to invoke Python interpreter
932py-scroll-process-buffer\t\talways scroll Python process buffer
933py-temp-directory\t\tdirectory used for temp files (if needed)
934py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000936 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000937 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000938 (make-local-variable 'font-lock-defaults)
939 (make-local-variable 'paragraph-separate)
940 (make-local-variable 'paragraph-start)
941 (make-local-variable 'require-final-newline)
942 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000943 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000944 (make-local-variable 'comment-start-skip)
945 (make-local-variable 'comment-column)
946 (make-local-variable 'indent-region-function)
947 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000948 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000949 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000950 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000951 (setq major-mode 'python-mode
952 mode-name "Python"
953 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000954 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000955 paragraph-separate "^[ \t]*$"
956 paragraph-start "^[ \t]*$"
957 require-final-newline t
958 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000959 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000960 comment-start-skip "# *"
961 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000962 indent-region-function 'py-indent-region
963 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000964 ;; tell add-log.el how to find the current function/method/variable
965 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000966 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000967 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000968 ;; add the menu
969 (if py-menu
970 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000971 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000972 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000973 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000974 ;; Install Imenu, only works for Emacs.
975 (when (py-safe (require 'imenu))
976 (make-variable-buffer-local 'imenu-create-index-function)
977 (setq imenu-create-index-function
978 (function imenu-example--create-python-index))
979 (setq imenu-generic-expression
980 imenu-example--generic-python-expression)
981 (if (fboundp 'imenu-add-to-menubar)
982 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
983 )
984 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000985 (if python-mode-hook
986 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000987 (run-hooks 'py-mode-hook))
988 ;; Now do the automagical guessing
989 (if py-smart-indentation
990 (let ((offset py-indent-offset))
991 ;; Its okay if this fails to guess a good value
992 (if (and (py-safe (py-guess-indent-offset))
993 (<= py-indent-offset 8)
994 (>= py-indent-offset 2))
995 (setq offset py-indent-offset))
996 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000997 ;; Only turn indent-tabs-mode off if tab-width !=
998 ;; py-indent-offset. Never turn it on, because the user must
999 ;; have explicitly turned it off.
1000 (if (/= tab-width py-indent-offset)
1001 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001002 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001003
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004
Barry Warsawb91b7431995-03-14 15:55:20 +00001005;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001006(defun py-outdent-p ()
1007 ;; returns non-nil if the current line should outdent one level
1008 (save-excursion
1009 (and (progn (back-to-indentation)
1010 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001011 (progn (forward-line -1)
1012 (py-goto-initial-line)
1013 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001014 (while (or (looking-at py-blank-or-comment-re)
1015 (bobp))
1016 (backward-to-indentation 1))
1017 (not (looking-at py-no-outdent-re)))
1018 )))
1019
Barry Warsawb91b7431995-03-14 15:55:20 +00001020(defun py-electric-colon (arg)
1021 "Insert a colon.
1022In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001023argument is provided, that many colons are inserted non-electrically.
1024Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001025 (interactive "P")
1026 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001027 ;; are we in a string or comment?
1028 (if (save-excursion
1029 (let ((pps (parse-partial-sexp (save-excursion
1030 (beginning-of-python-def-or-class)
1031 (point))
1032 (point))))
1033 (not (or (nth 3 pps) (nth 4 pps)))))
1034 (save-excursion
1035 (let ((here (point))
1036 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001037 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001038 (if (and (not arg)
1039 (py-outdent-p)
1040 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001041 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001042 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001043 )
1044 (setq outdent py-indent-offset))
1045 ;; Don't indent, only outdent. This assumes that any lines that
1046 ;; are already outdented relative to py-compute-indentation were
1047 ;; put there on purpose. Its highly annoying to have `:' indent
1048 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1049 ;; there a better way to determine this???
1050 (if (< (current-indentation) indent) nil
1051 (goto-char here)
1052 (beginning-of-line)
1053 (delete-horizontal-space)
1054 (indent-to (- indent outdent))
1055 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001056
1057
Barry Warsawa97a3f31997-11-04 18:47:06 +00001058;; Python subprocess utilities and filters
1059(defun py-execute-file (proc filename)
1060 ;; Send a properly formatted execfile('FILENAME') to the underlying
1061 ;; Python interpreter process FILENAME. Make that process's buffer
1062 ;; visible and force display. Also make comint believe the user
1063 ;; typed this string so that kill-output-from-shell does The Right
1064 ;; Thing.
1065 (let ((curbuf (current-buffer))
1066 (procbuf (process-buffer proc))
1067 (comint-scroll-to-bottom-on-output t)
1068 (msg (format "## working on region in file %s...\n" filename))
1069 (cmd (format "execfile('%s')\n" filename)))
1070 (unwind-protect
1071 (progn
1072 (set-buffer procbuf)
1073 (goto-char (point-max))
1074 (move-marker (process-mark proc) (point))
1075 (funcall (process-filter proc) proc msg))
1076 (set-buffer curbuf))
1077 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001078
1079(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 (let ((curbuf (current-buffer))
1081 (pbuf (process-buffer pyproc))
1082 (pmark (process-mark pyproc))
1083 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 ;; make sure we switch to a different buffer at least once. if we
1085 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001086 ;; window, and point is before the end, and lots of output is
1087 ;; coming at a fast pace, then (a) simple cursor-movement commands
1088 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1089 ;; to have a visible effect (the window just doesn't get updated,
1090 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1091 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001093 ;; #b makes no sense to me at all. #a almost makes sense: unless
1094 ;; we actually change buffers, set_buffer_internal in buffer.c
1095 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1096 ;; seems to make the Emacs command loop reluctant to update the
1097 ;; display. Perhaps the default process filter in process.c's
1098 ;; read_process_output has update_mode_lines++ for a similar
1099 ;; reason? beats me ...
1100
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001101 (unwind-protect
1102 ;; make sure current buffer is restored
1103 ;; BAW - we want to check to see if this still applies
1104 (progn
1105 ;; mysterious ugly hack
1106 (if (eq curbuf pbuf)
1107 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001108
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001109 (set-buffer pbuf)
1110 (let* ((start (point))
1111 (goback (< start pmark))
1112 (goend (and (not goback) (= start (point-max))))
1113 (buffer-read-only nil))
1114 (goto-char pmark)
1115 (insert string)
1116 (move-marker pmark (point))
1117 (setq file-finished
1118 (and py-file-queue
1119 (equal ">>> "
1120 (buffer-substring
1121 (prog2 (beginning-of-line) (point)
1122 (goto-char pmark))
1123 (point)))))
1124 (if goback (goto-char start)
1125 ;; else
1126 (if py-scroll-process-buffer
1127 (let* ((pop-up-windows t)
1128 (pwin (display-buffer pbuf)))
1129 (set-window-point pwin (point)))))
1130 (set-buffer curbuf)
1131 (if file-finished
1132 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001133 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001134 (setq py-file-queue (cdr py-file-queue))
1135 (if py-file-queue
1136 (py-execute-file pyproc (car py-file-queue)))))
1137 (and goend
1138 (progn (set-buffer pbuf)
1139 (goto-char (point-max))))
1140 ))
1141 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001142
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001143(defun py-postprocess-output-buffer (buf)
Barry Warsaw9981d221997-12-03 05:25:48 +00001144 (let (line file bol)
1145 (save-excursion
1146 (set-buffer buf)
1147 (beginning-of-buffer)
1148 (while (re-search-forward py-traceback-line-re nil t)
1149 (setq file (match-string 1)
1150 line (string-to-int (match-string 2))
1151 bol (py-point 'bol))
1152 (py-highlight-line bol (py-point 'eol) file line))
1153 (when (and py-jump-on-exception line)
1154 (beep)
1155 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001156 )))
1157
Barry Warsaw9981d221997-12-03 05:25:48 +00001158
Barry Warsawa97a3f31997-11-04 18:47:06 +00001159
1160;;; Subprocess commands
1161
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001162;; only used when (memq 'broken-temp-names py-emacs-features)
1163(defvar py-serial-number 0)
1164(defvar py-exception-buffer nil)
1165(defconst py-output-buffer "*Python Output*")
1166
Barry Warsawa97a3f31997-11-04 18:47:06 +00001167;;;###autoload
1168(defun py-shell ()
1169 "Start an interactive Python interpreter in another window.
1170This is like Shell mode, except that Python is running in the window
1171instead of a shell. See the `Interactive Shell' and `Shell Mode'
1172sections of the Emacs manual for details, especially for the key
1173bindings active in the `*Python*' buffer.
1174
1175See the docs for variable `py-scroll-buffer' for info on scrolling
1176behavior in the process window.
1177
1178Warning: Don't use an interactive Python if you change sys.ps1 or
1179sys.ps2 from their default values, or if you're running code that
1180prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1181distinguish your output from Python's output, and assumes that `>>> '
1182at the start of a line is a prompt from Python. Similarly, the Emacs
1183Shell mode code assumes that both `>>> ' and `... ' at the start of a
1184line are Python prompts. Bad things can happen if you fool either
1185mode.
1186
1187Warning: If you do any editing *in* the process buffer *while* the
1188buffer is accepting output from Python, do NOT attempt to `undo' the
1189changes. Some of the output (nowhere near the parts you changed!) may
1190be lost if you do. This appears to be an Emacs bug, an unfortunate
1191interaction between undo and process filters; the same problem exists in
1192non-Python process buffers using the default (Emacs-supplied) process
1193filter."
1194 ;; BAW - should undo be disabled in the python process buffer, if
1195 ;; this bug still exists?
1196 (interactive)
1197 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001198 (switch-to-buffer-other-window
Barry Warsaw8f972b71998-02-05 20:45:49 +00001199 (apply 'make-comint "Python" py-python-command nil py-python-command-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001200 (make-local-variable 'comint-prompt-regexp)
1201 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1202 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1203 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001204 ;; set up keybindings for this subshell
1205 (local-set-key [tab] 'self-insert-command)
1206 (local-set-key "\C-c-" 'py-up-exception)
1207 (local-set-key "\C-c=" 'py-down-exception)
1208 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001209
Barry Warsawa97a3f31997-11-04 18:47:06 +00001210(defun py-clear-queue ()
1211 "Clear the queue of temporary files waiting to execute."
1212 (interactive)
1213 (let ((n (length py-file-queue)))
1214 (mapcar 'delete-file py-file-queue)
1215 (setq py-file-queue nil)
1216 (message "%d pending files de-queued." n)))
1217
1218(defun py-execute-region (start end &optional async)
1219 "Execute the the region in a Python interpreter.
1220The region is first copied into a temporary file (in the directory
1221`py-temp-directory'). If there is no Python interpreter shell
1222running, this file is executed synchronously using
1223`shell-command-on-region'. If the program is long running, use an
1224optional \\[universal-argument] to run the command asynchronously in
1225its own buffer.
1226
1227If the Python interpreter shell is running, the region is execfile()'d
1228in that shell. If you try to execute regions too quickly,
1229`python-mode' will queue them up and execute them one at a time when
1230it sees a `>>> ' prompt from Python. Each time this happens, the
1231process buffer is popped into a window (if it's not already in some
1232window) so you can see it, and a comment of the form
1233
1234 \t## working on region in file <name>...
1235
1236is inserted at the end. See also the command `py-clear-queue'."
1237 (interactive "r\nP")
1238 (or (< start end)
1239 (error "Region is empty"))
1240 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001241 (temp (if (memq 'broken-temp-names py-emacs-features)
1242 (prog1
1243 (format "python-%d" py-serial-number)
1244 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001245 (make-temp-name "python-")))
1246 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001247 (write-region start end file nil 'nomsg)
1248 (cond
1249 ;; always run the code in it's own asynchronous subprocess
1250 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001251 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001252 (start-process "Python" buf py-python-command "-u" file)
1253 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001254 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001255 ))
1256 ;; if the Python interpreter shell is running, queue it up for
1257 ;; execution there.
1258 (proc
1259 ;; use the existing python shell
1260 (if (not py-file-queue)
1261 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001262 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001263 (push file py-file-queue)
1264 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001265 (t
1266 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001267 (shell-command-on-region start end py-python-command py-output-buffer)
1268 (setq py-exception-buffer (current-buffer))
1269 (py-postprocess-output-buffer py-output-buffer)
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001270 (pop-to-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001271 ))))
1272
1273;; Code execution command
1274(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001275 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001276If the file local variable `py-master-file' is non-nil, execute the
1277named file instead of the buffer's file.
1278
Barry Warsaw7ae77681994-12-12 20:38:05 +00001279If there is a *Python* process buffer it is used. If a clipping
1280restriction is in effect, only the accessible portion of the buffer is
1281sent. A trailing newline will be supplied if needed.
1282
1283See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001284 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001285 (if py-master-file
1286 (let* ((filename (expand-file-name py-master-file))
1287 (buffer (or (get-file-buffer filename)
1288 (find-file-noselect filename))))
1289 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001290 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001291
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001292
1293
1294(defun py-jump-to-exception (file line)
1295 (let ((buffer (cond ((string-equal file "<stdin>")
1296 py-exception-buffer)
1297 ((and (consp py-exception-buffer)
1298 (string-equal file (car py-exception-buffer)))
1299 (cdr py-exception-buffer))
1300 ((py-safe (find-file-noselect file)))
1301 ;; could not figure out what file the exception
1302 ;; is pointing to, so prompt for it
1303 (t (find-file (read-file-name "Exception file: "
1304 nil
1305 file t))))))
1306 (pop-to-buffer buffer)
1307 (goto-line line)
1308 (message "Jumping to exception in file %s on line %d" file line)))
1309
1310(defun py-mouseto-exception (event)
1311 (interactive "e")
1312 (cond
1313 ((fboundp 'event-point)
1314 ;; XEmacs
1315 (let* ((point (event-point event))
1316 (buffer (event-buffer event))
1317 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1318 (info (and e (extent-property e 'py-exc-info))))
1319 (message "Event point: %d, info: %s" point info)
1320 (and info
1321 (py-jump-to-exception (car info) (cdr info)))
1322 ))
1323 ;; Emacs -- Please port this!
1324 ))
1325
1326(defun py-goto-exception ()
1327 "Go to the line indicated by the traceback."
1328 (interactive)
1329 (let (file line)
1330 (save-excursion
1331 (beginning-of-line)
1332 (if (looking-at py-traceback-line-re)
1333 (setq file (match-string 1)
1334 line (string-to-int (match-string 2)))))
1335 (if (not file)
1336 (error "Not on a traceback line."))
1337 (py-jump-to-exception file line)))
1338
1339(defun py-find-next-exception (start buffer searchdir errwhere)
1340 ;; Go to start position in buffer, search in the specified
1341 ;; direction, and jump to the exception found. If at the end of the
1342 ;; exception, print error message
1343 (let (file line)
1344 (save-excursion
1345 (set-buffer buffer)
1346 (goto-char (py-point start))
1347 (if (funcall searchdir py-traceback-line-re nil t)
1348 (setq file (match-string 1)
1349 line (string-to-int (match-string 2)))))
1350 (if (and file line)
1351 (py-jump-to-exception file line)
1352 (error "%s of traceback" errwhere))))
1353
1354(defun py-down-exception (&optional bottom)
1355 "Go to the next line down in the traceback.
1356With optional \\[universal-argument], jump to the bottom (innermost)
1357exception in the exception stack."
1358 (interactive "P")
1359 (let* ((proc (get-process "Python"))
1360 (buffer (if proc "*Python*" py-output-buffer)))
1361 (if bottom
1362 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1363 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1364
1365(defun py-up-exception (&optional top)
1366 "Go to the previous line up in the traceback.
1367With optional \\[universal-argument], jump to the top (outermost)
1368exception in the exception stack."
1369 (interactive "P")
1370 (let* ((proc (get-process "Python"))
1371 (buffer (if proc "*Python*" py-output-buffer)))
1372 (if top
1373 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001374 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001375
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001376
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001377;; Electric deletion
1378(defun py-electric-backspace (arg)
1379 "Deletes preceding character or levels of indentation.
1380Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001381with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001382
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001383If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001385Otherwise, if point is at the leftmost non-whitespace character of a
1386line that is neither a continuation line nor a non-indenting comment
1387line, or if point is at the end of a blank line, this command reduces
1388the indentation to match that of the line that opened the current
1389block of code. The line that opened the block is displayed in the
1390echo area to help you keep track of where you are. With numeric arg,
1391outdents that many blocks (but not past column zero).
1392
1393Otherwise the preceding character is deleted, converting a tab to
1394spaces if needed so that only a single column position is deleted.
1395Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001396 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001397 (if (or (/= (current-indentation) (current-column))
1398 (bolp)
1399 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001400 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001401 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001402 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001403 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001404 ;; force non-blank so py-goto-block-up doesn't ignore it
1405 (insert-char ?* 1)
1406 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001407 (let ((base-indent 0) ; indentation of base line
1408 (base-text "") ; and text of base line
1409 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001410 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001411 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001412 (condition-case nil ; in case no enclosing block
1413 (progn
1414 (py-goto-block-up 'no-mark)
1415 (setq base-indent (current-indentation)
1416 base-text (py-suck-up-leading-text)
1417 base-found-p t))
1418 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001419 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001420 (delete-char 1) ; toss the dummy character
1421 (delete-horizontal-space)
1422 (indent-to base-indent)
1423 (if base-found-p
1424 (message "Closes block: %s" base-text)))))
1425
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001426
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001427(defun py-electric-delete (arg)
1428 "Deletes preceding or following character or levels of whitespace.
1429
1430The behavior of this function depends on the variable
1431`delete-key-deletes-forward'. If this variable is nil (or does not
1432exist, as in older Emacsen), then this function behaves identical to
1433\\[c-electric-backspace].
1434
1435If `delete-key-deletes-forward' is non-nil and is supported in your
1436Emacs, then deletion occurs in the forward direction, by calling the
1437function in `py-delete-function'."
1438 (interactive "*p")
1439 (if (and (boundp 'delete-key-deletes-forward)
1440 delete-key-deletes-forward)
1441 (funcall py-delete-function arg)
1442 ;; else
1443 (py-electric-backspace arg)))
1444
1445;; required for pending-del and delsel modes
1446(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1447(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1448(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1449(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1450
1451
1452
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001453(defun py-indent-line (&optional arg)
1454 "Fix the indentation of the current line according to Python rules.
1455With \\[universal-argument], ignore outdenting rules for block
1456closing statements (e.g. return, raise, break, continue, pass)
1457
1458This function is normally bound to `indent-line-function' so
1459\\[indent-for-tab-command] will call it."
1460 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001461 (let* ((ci (current-indentation))
1462 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001463 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001464 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001465 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001466 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001467 (if (/= ci need)
1468 (save-excursion
1469 (beginning-of-line)
1470 (delete-horizontal-space)
1471 (indent-to need)))
1472 (if move-to-indentation-p (back-to-indentation))))
1473
1474(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001475 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001476This is just `strives to' because correct indentation can't be computed
1477from scratch for Python code. In general, deletes the whitespace before
1478point, inserts a newline, and takes an educated guess as to how you want
1479the new line indented."
1480 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001481 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001482 (if (< ci (current-column)) ; if point beyond indentation
1483 (newline-and-indent)
1484 ;; else try to act like newline-and-indent "normally" acts
1485 (beginning-of-line)
1486 (insert-char ?\n 1)
1487 (move-to-column ci))))
1488
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001489(defun py-compute-indentation (honor-block-close-p)
1490 ;; implements all the rules for indentation computation. when
1491 ;; honor-block-close-p is non-nil, statements such as return, raise,
1492 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001493 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001494 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001495 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001496 (pps (parse-partial-sexp bod (point)))
1497 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001498 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001499 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001500 ((or (and (nth 3 pps) (nth 3 boipps))
1501 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001502 (save-excursion
1503 (if (not py-align-multiline-strings-p) 0
1504 ;; skip back over blank & non-indenting comment lines
1505 ;; note: will skip a blank or non-indenting comment line
1506 ;; that happens to be a continuation line too
1507 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1508 (back-to-indentation)
1509 (current-column))))
1510 ;; are we on a continuation line?
1511 ((py-continuation-line-p)
1512 (let ((startpos (point))
1513 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001514 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001515 (if open-bracket-pos
1516 (progn
1517 ;; align with first item in list; else a normal
1518 ;; indent beyond the line with the open bracket
1519 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1520 ;; is the first list item on the same line?
1521 (skip-chars-forward " \t")
1522 (if (null (memq (following-char) '(?\n ?# ?\\)))
1523 ; yes, so line up with it
1524 (current-column)
1525 ;; first list item on another line, or doesn't exist yet
1526 (forward-line 1)
1527 (while (and (< (point) startpos)
1528 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1529 (forward-line 1))
1530 (if (< (point) startpos)
1531 ;; again mimic the first list item
1532 (current-indentation)
1533 ;; else they're about to enter the first item
1534 (goto-char open-bracket-pos)
1535 (+ (current-indentation) py-indent-offset))))
1536
1537 ;; else on backslash continuation line
1538 (forward-line -1)
1539 (if (py-continuation-line-p) ; on at least 3rd line in block
1540 (current-indentation) ; so just continue the pattern
1541 ;; else started on 2nd line in block, so indent more.
1542 ;; if base line is an assignment with a start on a RHS,
1543 ;; indent to 2 beyond the leftmost "="; else skip first
1544 ;; chunk of non-whitespace characters on base line, + 1 more
1545 ;; column
1546 (end-of-line)
1547 (setq endpos (point) searching t)
1548 (back-to-indentation)
1549 (setq startpos (point))
1550 ;; look at all "=" from left to right, stopping at first
1551 ;; one not nested in a list or string
1552 (while searching
1553 (skip-chars-forward "^=" endpos)
1554 (if (= (point) endpos)
1555 (setq searching nil)
1556 (forward-char 1)
1557 (setq state (parse-partial-sexp startpos (point)))
1558 (if (and (zerop (car state)) ; not in a bracket
1559 (null (nth 3 state))) ; & not in a string
1560 (progn
1561 (setq searching nil) ; done searching in any case
1562 (setq found
1563 (not (or
1564 (eq (following-char) ?=)
1565 (memq (char-after (- (point) 2))
1566 '(?< ?> ?!)))))))))
1567 (if (or (not found) ; not an assignment
1568 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1569 (progn
1570 (goto-char startpos)
1571 (skip-chars-forward "^ \t\n")))
1572 (1+ (current-column))))))
1573
1574 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001575 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001576
Barry Warsawa7891711996-08-01 15:53:09 +00001577 ;; Dfn: "Indenting comment line". A line containing only a
1578 ;; comment, but which is treated like a statement for
1579 ;; indentation calculation purposes. Such lines are only
1580 ;; treated specially by the mode; they are not treated
1581 ;; specially by the Python interpreter.
1582
1583 ;; The rules for indenting comment lines are a line where:
1584 ;; - the first non-whitespace character is `#', and
1585 ;; - the character following the `#' is whitespace, and
1586 ;; - the line is outdented with respect to (i.e. to the left
1587 ;; of) the indentation of the preceding non-blank line.
1588
1589 ;; The first non-blank line following an indenting comment
1590 ;; line is given the same amount of indentation as the
1591 ;; indenting comment line.
1592
1593 ;; All other comment-only lines are ignored for indentation
1594 ;; purposes.
1595
1596 ;; Are we looking at a comment-only line which is *not* an
1597 ;; indenting comment line? If so, we assume that its been
1598 ;; placed at the desired indentation, so leave it alone.
1599 ;; Indenting comment lines are aligned as statements down
1600 ;; below.
1601 ((and (looking-at "[ \t]*#[^ \t\n]")
1602 ;; NOTE: this test will not be performed in older Emacsen
1603 (fboundp 'forward-comment)
1604 (<= (current-indentation)
1605 (save-excursion
1606 (forward-comment (- (point-max)))
1607 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001608 (current-indentation))
1609
1610 ;; else indentation based on that of the statement that
1611 ;; precedes us; use the first line of that statement to
1612 ;; establish the base, in case the user forced a non-std
1613 ;; indentation for the continuation lines (if any)
1614 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001615 ;; skip back over blank & non-indenting comment lines note:
1616 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001617 ;; happens to be a continuation line too. use fast Emacs 19
1618 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001619 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001620 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001621 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001622 (let (done)
1623 (while (not done)
1624 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1625 nil 'move)
1626 (setq done (or (eq py-honor-comment-indentation t)
1627 (bobp)
1628 (/= (following-char) ?#)
1629 (not (zerop (current-column)))))
1630 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001631 ;; if we landed inside a string, go to the beginning of that
1632 ;; string. this handles triple quoted, multi-line spanning
1633 ;; strings.
Barry Warsawf64b4051998-02-12 16:52:14 +00001634 (let* ((pps3 (nth 3 (parse-partial-sexp bod (point))))
1635 (delim (and pps3 (int-to-char pps3)))
1636 (skip (and delim (make-string 1 delim))))
1637 (when skip
1638 (save-excursion
1639 (py-safe (search-backward skip))
1640 (if (and (eq (char-before) delim)
1641 (eq (char-before (1- (point))) delim))
1642 (setq skip (make-string 3 delim))))
1643 ;; we're looking at a triple-quoted string
1644 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001645 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001646 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001647 (+ (current-indentation)
1648 (if (py-statement-opens-block-p)
1649 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001650 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001651 (- py-indent-offset)
1652 0)))
1653 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654
1655(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001656 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001658`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001659Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001660`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001661their own buffer-local copy), both those currently existing and those
1662created later in the Emacs session.
1663
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001665There's no excuse for such foolishness, but sometimes you have to deal
1666with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667`py-indent-offset' to what it thinks it was when they created the
1668mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001669
1670Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671looking for a line that opens a block of code. `py-indent-offset' is
1672set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001673statement following it. If the search doesn't succeed going forward,
1674it's tried again going backward."
1675 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001676 (let (new-value
1677 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001678 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001679 (found nil)
1680 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001681 (py-goto-initial-line)
1682 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001683 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1684 (not (py-in-literal restart)))
1685 (setq restart (point))
1686 (py-goto-initial-line)
1687 (if (py-statement-opens-block-p)
1688 (setq found t)
1689 (goto-char restart))))
1690 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001691 (goto-char start)
1692 (py-goto-initial-line)
1693 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001694 (setq found (and
1695 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1696 (or (py-goto-initial-line) t) ; always true -- side effect
1697 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001698 (setq colon-indent (current-indentation)
1699 found (and found (zerop (py-next-statement 1)))
1700 new-value (- (current-indentation) colon-indent))
1701 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001702 (if (not found)
1703 (error "Sorry, couldn't guess a value for py-indent-offset")
1704 (funcall (if global 'kill-local-variable 'make-local-variable)
1705 'py-indent-offset)
1706 (setq py-indent-offset new-value)
1707 (message "%s value of py-indent-offset set to %d"
1708 (if global "Global" "Local")
1709 py-indent-offset))
1710 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001711
1712(defun py-shift-region (start end count)
1713 (save-excursion
1714 (goto-char end) (beginning-of-line) (setq end (point))
1715 (goto-char start) (beginning-of-line) (setq start (point))
1716 (indent-rigidly start end count)))
1717
1718(defun py-shift-region-left (start end &optional count)
1719 "Shift region of Python code to the left.
1720The lines from the line containing the start of the current region up
1721to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001722shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723
1724If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001725many columns. With no active region, outdent only the current line.
1726You cannot outdent the region if any line is already at column zero."
1727 (interactive
1728 (let ((p (point))
1729 (m (mark))
1730 (arg current-prefix-arg))
1731 (if m
1732 (list (min p m) (max p m) arg)
1733 (list p (save-excursion (forward-line 1) (point)) arg))))
1734 ;; if any line is at column zero, don't shift the region
1735 (save-excursion
1736 (goto-char start)
1737 (while (< (point) end)
1738 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001739 (if (and (zerop (current-column))
1740 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001741 (error "Region is at left edge."))
1742 (forward-line 1)))
1743 (py-shift-region start end (- (prefix-numeric-value
1744 (or count py-indent-offset))))
1745 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746
1747(defun py-shift-region-right (start end &optional count)
1748 "Shift region of Python code to the right.
1749The lines from the line containing the start of the current region up
1750to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752
1753If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001754many columns. With no active region, indent only the current line."
1755 (interactive
1756 (let ((p (point))
1757 (m (mark))
1758 (arg current-prefix-arg))
1759 (if m
1760 (list (min p m) (max p m) arg)
1761 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001763 (or count py-indent-offset)))
1764 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001765
1766(defun py-indent-region (start end &optional indent-offset)
1767 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001768
Barry Warsaw7ae77681994-12-12 20:38:05 +00001769The lines from the line containing the start of the current region up
1770to (but not including) the line containing the end of the region are
1771reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001772character in the first column, the first line is left alone and the
1773rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001774region is reindented with respect to the (closest code or indenting
1775comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776
1777This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778control structures are introduced or removed, or to reformat code
1779using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001780
1781If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001782the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001783used.
1784
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001785Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001786is called! This function does not compute proper indentation from
1787scratch (that's impossible in Python), it merely adjusts the existing
1788indentation to be correct in context.
1789
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790Warning: This function really has no idea what to do with
1791non-indenting comment lines, and shifts them as if they were indenting
1792comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001793
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794Special cases: whitespace is deleted from blank lines; continuation
1795lines are shifted by the same amount their initial line was shifted,
1796in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001798 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001799 (save-excursion
1800 (goto-char end) (beginning-of-line) (setq end (point-marker))
1801 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001802 (let ((py-indent-offset (prefix-numeric-value
1803 (or indent-offset py-indent-offset)))
1804 (indents '(-1)) ; stack of active indent levels
1805 (target-column 0) ; column to which to indent
1806 (base-shifted-by 0) ; amount last base line was shifted
1807 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001808 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001809 0))
1810 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811 (while (< (point) end)
1812 (setq ci (current-indentation))
1813 ;; figure out appropriate target column
1814 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 ((or (eq (following-char) ?#) ; comment in column 1
1816 (looking-at "[ \t]*$")) ; entirely blank
1817 (setq target-column 0))
1818 ((py-continuation-line-p) ; shift relative to base line
1819 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820 (t ; new base line
1821 (if (> ci (car indents)) ; going deeper; push it
1822 (setq indents (cons ci indents))
1823 ;; else we should have seen this indent before
1824 (setq indents (memq ci indents)) ; pop deeper indents
1825 (if (null indents)
1826 (error "Bad indentation in region, at line %d"
1827 (save-restriction
1828 (widen)
1829 (1+ (count-lines 1 (point)))))))
1830 (setq target-column (+ indent-base
1831 (* py-indent-offset
1832 (- (length indents) 2))))
1833 (setq base-shifted-by (- target-column ci))))
1834 ;; shift as needed
1835 (if (/= ci target-column)
1836 (progn
1837 (delete-horizontal-space)
1838 (indent-to target-column)))
1839 (forward-line 1))))
1840 (set-marker end nil))
1841
Barry Warsawa7891711996-08-01 15:53:09 +00001842(defun py-comment-region (beg end &optional arg)
1843 "Like `comment-region' but uses double hash (`#') comment starter."
1844 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001845 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001846 (comment-region beg end arg)))
1847
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001848
1849;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850(defun py-previous-statement (count)
1851 "Go to the start of previous Python statement.
1852If the statement at point is the i'th Python statement, goes to the
1853start of statement i-COUNT. If there is no such statement, goes to the
1854first statement. Returns count of statements left to move.
1855`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001856 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001857 (if (< count 0) (py-next-statement (- count))
1858 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001859 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001861 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 (> count 0)
1863 (zerop (forward-line -1))
1864 (py-goto-statement-at-or-above))
1865 (setq count (1- count)))
1866 (if (> count 0) (goto-char start)))
1867 count))
1868
1869(defun py-next-statement (count)
1870 "Go to the start of next Python statement.
1871If the statement at point is the i'th Python statement, goes to the
1872start of statement i+COUNT. If there is no such statement, goes to the
1873last statement. Returns count of statements left to move. `Statements'
1874do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876 (if (< count 0) (py-previous-statement (- count))
1877 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001879 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001880 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (> count 0)
1882 (py-goto-statement-below))
1883 (setq count (1- count)))
1884 (if (> count 0) (goto-char start)))
1885 count))
1886
1887(defun py-goto-block-up (&optional nomark)
1888 "Move up to start of current block.
1889Go to the statement that starts the smallest enclosing block; roughly
1890speaking, this will be the closest preceding statement that ends with a
1891colon and is indented less than the statement you started on. If
1892successful, also sets the mark to the starting point.
1893
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001894`\\[py-mark-block]' can be used afterward to mark the whole code
1895block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896
1897If called from a program, the mark will not be set if optional argument
1898NOMARK is not nil."
1899 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900 (let ((start (point))
1901 (found nil)
1902 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001903 (py-goto-initial-line)
1904 ;; if on blank or non-indenting comment line, use the preceding stmt
1905 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1906 (progn
1907 (py-goto-statement-at-or-above)
1908 (setq found (py-statement-opens-block-p))))
1909 ;; search back for colon line indented less
1910 (setq initial-indent (current-indentation))
1911 (if (zerop initial-indent)
1912 ;; force fast exit
1913 (goto-char (point-min)))
1914 (while (not (or found (bobp)))
1915 (setq found
1916 (and
1917 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1918 (or (py-goto-initial-line) t) ; always true -- side effect
1919 (< (current-indentation) initial-indent)
1920 (py-statement-opens-block-p))))
1921 (if found
1922 (progn
1923 (or nomark (push-mark start))
1924 (back-to-indentation))
1925 (goto-char start)
1926 (error "Enclosing block not found"))))
1927
1928(defun beginning-of-python-def-or-class (&optional class)
1929 "Move point to start of def (or class, with prefix arg).
1930
1931Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001932arg, looks for a `class' instead. The docs assume the `def' case;
1933just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001935If point is in a def statement already, and after the `d', simply
1936moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938Else (point is not in a def statement, or at or before the `d' of a
1939def statement), searches for the closest preceding def statement, and
1940leaves point at its start. If no such statement can be found, leaves
1941point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001942
1943Returns t iff a def statement is found by these rules.
1944
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945Note that doing this command repeatedly will take you closer to the
1946start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001947
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001948If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001949`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001950 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001951 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1952 (start-of-line (progn (beginning-of-line) (point)))
1953 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001954 (if (or (/= start-of-stmt start-of-line)
1955 (not at-or-before-p))
1956 (end-of-line)) ; OK to match on this line
1957 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001958 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001959
1960(defun end-of-python-def-or-class (&optional class)
1961 "Move point beyond end of def (or class, with prefix arg) body.
1962
1963By default, looks for an appropriate `def'. If you supply a prefix arg,
1964looks for a `class' instead. The docs assume the `def' case; just
1965substitute `class' for `def' for the other case.
1966
1967If point is in a def statement already, this is the def we use.
1968
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001969Else if the def found by `\\[beginning-of-python-def-or-class]'
1970contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971
1972Else we search forward for the closest following def, and use that.
1973
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974If a def can be found by these rules, point is moved to the start of
1975the line immediately following the def block, and the position of the
1976start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001977
1978Else point is moved to the end of the buffer, and nil is returned.
1979
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980Note that doing this command repeatedly will take you closer to the
1981end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001982
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001983If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001984`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001985 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001986 (let ((start (progn (py-goto-initial-line) (point)))
1987 (which (if class "class" "def"))
1988 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001989 ;; move point to start of appropriate def/class
1990 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1991 (setq state 'at-beginning)
1992 ;; else see if beginning-of-python-def-or-class hits container
1993 (if (and (beginning-of-python-def-or-class class)
1994 (progn (py-goto-beyond-block)
1995 (> (point) start)))
1996 (setq state 'at-end)
1997 ;; else search forward
1998 (goto-char start)
1999 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2000 (progn (setq state 'at-beginning)
2001 (beginning-of-line)))))
2002 (cond
2003 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2004 ((eq state 'at-end) t)
2005 ((eq state 'not-found) nil)
2006 (t (error "internal error in end-of-python-def-or-class")))))
2007
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002008
2009;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002010(defun py-mark-block (&optional extend just-move)
2011 "Mark following block of lines. With prefix arg, mark structure.
2012Easier to use than explain. It sets the region to an `interesting'
2013block of succeeding lines. If point is on a blank line, it goes down to
2014the next non-blank line. That will be the start of the region. The end
2015of the region depends on the kind of line at the start:
2016
2017 - If a comment, the region will include all succeeding comment lines up
2018 to (but not including) the next non-comment line (if any).
2019
2020 - Else if a prefix arg is given, and the line begins one of these
2021 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002022
2023 if elif else try except finally for while def class
2024
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025 the region will be set to the body of the structure, including
2026 following blocks that `belong' to it, but excluding trailing blank
2027 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028 and all (if any) of the following `except' and `finally' blocks
2029 that belong to the `try' structure will be in the region. Ditto
2030 for if/elif/else, for/else and while/else structures, and (a bit
2031 degenerate, since they're always one-block structures) def and
2032 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002033
2034 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002035 block (see list above), and the block is not a `one-liner' (i.e.,
2036 the statement ends with a colon, not with code), the region will
2037 include all succeeding lines up to (but not including) the next
2038 code statement (if any) that's indented no more than the starting
2039 line, except that trailing blank and comment lines are excluded.
2040 E.g., if the starting line begins a multi-statement `def'
2041 structure, the region will be set to the full function definition,
2042 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002043
2044 - Else the region will include all succeeding lines up to (but not
2045 including) the next blank line, or code or indenting-comment line
2046 indented strictly less than the starting line. Trailing indenting
2047 comment lines are included in this case, but not trailing blank
2048 lines.
2049
2050A msg identifying the location of the mark is displayed in the echo
2051area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2052
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002053If called from a program, optional argument EXTEND plays the role of
2054the prefix arg, and if optional argument JUST-MOVE is not nil, just
2055moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002056 (interactive "P") ; raw prefix arg
2057 (py-goto-initial-line)
2058 ;; skip over blank lines
2059 (while (and
2060 (looking-at "[ \t]*$") ; while blank line
2061 (not (eobp))) ; & somewhere to go
2062 (forward-line 1))
2063 (if (eobp)
2064 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002065 (let ((initial-pos (point))
2066 (initial-indent (current-indentation))
2067 last-pos ; position of last stmt in region
2068 (followers
2069 '((if elif else) (elif elif else) (else)
2070 (try except finally) (except except) (finally)
2071 (for else) (while else)
2072 (def) (class) ) )
2073 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002074
2075 (cond
2076 ;; if comment line, suck up the following comment lines
2077 ((looking-at "[ \t]*#")
2078 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2079 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2080 (setq last-pos (point)))
2081
2082 ;; else if line is a block line and EXTEND given, suck up
2083 ;; the whole structure
2084 ((and extend
2085 (setq first-symbol (py-suck-up-first-keyword) )
2086 (assq first-symbol followers))
2087 (while (and
2088 (or (py-goto-beyond-block) t) ; side effect
2089 (forward-line -1) ; side effect
2090 (setq last-pos (point)) ; side effect
2091 (py-goto-statement-below)
2092 (= (current-indentation) initial-indent)
2093 (setq next-symbol (py-suck-up-first-keyword))
2094 (memq next-symbol (cdr (assq first-symbol followers))))
2095 (setq first-symbol next-symbol)))
2096
2097 ;; else if line *opens* a block, search for next stmt indented <=
2098 ((py-statement-opens-block-p)
2099 (while (and
2100 (setq last-pos (point)) ; always true -- side effect
2101 (py-goto-statement-below)
2102 (> (current-indentation) initial-indent))
2103 nil))
2104
2105 ;; else plain code line; stop at next blank line, or stmt or
2106 ;; indenting comment line indented <
2107 (t
2108 (while (and
2109 (setq last-pos (point)) ; always true -- side effect
2110 (or (py-goto-beyond-final-line) t)
2111 (not (looking-at "[ \t]*$")) ; stop at blank line
2112 (or
2113 (>= (current-indentation) initial-indent)
2114 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2115 nil)))
2116
2117 ;; skip to end of last stmt
2118 (goto-char last-pos)
2119 (py-goto-beyond-final-line)
2120
2121 ;; set mark & display
2122 (if just-move
2123 () ; just return
2124 (push-mark (point) 'no-msg)
2125 (forward-line -1)
2126 (message "Mark set after: %s" (py-suck-up-leading-text))
2127 (goto-char initial-pos))))
2128
Barry Warsaw2518c671997-11-05 00:51:08 +00002129(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002130 "Set region to body of def (or class, with prefix arg) enclosing point.
2131Pushes the current mark, then point, on the mark ring (all language
2132modes do this, but although it's handy it's never documented ...).
2133
2134In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002135hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2136`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002137
2138And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002139Turned out that was more confusing than useful: the `goto start' and
2140`goto end' commands are usually used to search through a file, and
2141people expect them to act a lot like `search backward' and `search
2142forward' string-search commands. But because Python `def' and `class'
2143can nest to arbitrary levels, finding the smallest def containing
2144point cannot be done via a simple backward search: the def containing
2145point may not be the closest preceding def, or even the closest
2146preceding def that's indented less. The fancy algorithm required is
2147appropriate for the usual uses of this `mark' command, but not for the
2148`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002149
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002150So the def marked by this command may not be the one either of the
2151`goto' commands find: If point is on a blank or non-indenting comment
2152line, moves back to start of the closest preceding code statement or
2153indenting comment line. If this is a `def' statement, that's the def
2154we use. Else searches for the smallest enclosing `def' block and uses
2155that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002157When an enclosing def is found: The mark is left immediately beyond
2158the last line of the def block. Point is left at the start of the
2159def, except that: if the def is preceded by a number of comment lines
2160followed by (at most) one optional blank line, point is left at the
2161start of the comments; else if the def is preceded by a blank line,
2162point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002163
2164The intent is to mark the containing def/class and its associated
2165documentation, to make moving and duplicating functions and classes
2166pleasant."
2167 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002168 (let ((start (point))
2169 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170 (push-mark start)
2171 (if (not (py-go-up-tree-to-keyword which))
2172 (progn (goto-char start)
2173 (error "Enclosing %s not found" which))
2174 ;; else enclosing def/class found
2175 (setq start (point))
2176 (py-goto-beyond-block)
2177 (push-mark (point))
2178 (goto-char start)
2179 (if (zerop (forward-line -1)) ; if there is a preceding line
2180 (progn
2181 (if (looking-at "[ \t]*$") ; it's blank
2182 (setq start (point)) ; so reset start point
2183 (goto-char start)) ; else try again
2184 (if (zerop (forward-line -1))
2185 (if (looking-at "[ \t]*#") ; a comment
2186 ;; look back for non-comment line
2187 ;; tricky: note that the regexp matches a blank
2188 ;; line, cuz \n is in the 2nd character class
2189 (and
2190 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2191 (forward-line 1))
2192 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002193 (goto-char start)))))))
2194 (exchange-point-and-mark)
2195 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002196
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002197;; ripped from cc-mode
2198(defun py-forward-into-nomenclature (&optional arg)
2199 "Move forward to end of a nomenclature section or word.
2200With arg, to it arg times.
2201
2202A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2203 (interactive "p")
2204 (let ((case-fold-search nil))
2205 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002206 (re-search-forward
2207 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2208 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002209 (while (and (< arg 0)
2210 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002211 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002212 (point-min) 0))
2213 (forward-char 1)
2214 (setq arg (1+ arg)))))
2215 (py-keep-region-active))
2216
2217(defun py-backward-into-nomenclature (&optional arg)
2218 "Move backward to beginning of a nomenclature section or word.
2219With optional ARG, move that many times. If ARG is negative, move
2220forward.
2221
2222A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2223 (interactive "p")
2224 (py-forward-into-nomenclature (- arg))
2225 (py-keep-region-active))
2226
2227
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002228
2229;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002230
2231;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002232;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2233;; out of the right places, along with the keys they're on & current
2234;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002235(defun py-dump-help-string (str)
2236 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002237 (let ((locals (buffer-local-variables))
2238 funckind funcname func funcdoc
2239 (start 0) mstart end
2240 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002241 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2242 (setq mstart (match-beginning 0) end (match-end 0)
2243 funckind (substring str (match-beginning 1) (match-end 1))
2244 funcname (substring str (match-beginning 2) (match-end 2))
2245 func (intern funcname))
2246 (princ (substitute-command-keys (substring str start mstart)))
2247 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002248 ((equal funckind "c") ; command
2249 (setq funcdoc (documentation func)
2250 keys (concat
2251 "Key(s): "
2252 (mapconcat 'key-description
2253 (where-is-internal func py-mode-map)
2254 ", "))))
2255 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002256 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002257 keys (if (assq func locals)
2258 (concat
2259 "Local/Global values: "
2260 (prin1-to-string (symbol-value func))
2261 " / "
2262 (prin1-to-string (default-value func)))
2263 (concat
2264 "Value: "
2265 (prin1-to-string (symbol-value func))))))
2266 (t ; unexpected
2267 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002268 (princ (format "\n-> %s:\t%s\t%s\n\n"
2269 (if (equal funckind "c") "Command" "Variable")
2270 funcname keys))
2271 (princ funcdoc)
2272 (terpri)
2273 (setq start end))
2274 (princ (substitute-command-keys (substring str start))))
2275 (print-help-return-message)))
2276
2277(defun py-describe-mode ()
2278 "Dump long form of Python-mode docs."
2279 (interactive)
2280 (py-dump-help-string "Major mode for editing Python files.
2281Knows about Python indentation, tokens, comments and continuation lines.
2282Paragraphs are separated by blank lines only.
2283
2284Major sections below begin with the string `@'; specific function and
2285variable docs begin with `->'.
2286
2287@EXECUTING PYTHON CODE
2288
2289\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2290\\[py-execute-region]\tsends the current region
2291\\[py-shell]\tstarts a Python interpreter window; this will be used by
2292\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2293%c:py-execute-buffer
2294%c:py-execute-region
2295%c:py-shell
2296
2297@VARIABLES
2298
2299py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002300py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002301
2302py-python-command\tshell command to invoke Python interpreter
2303py-scroll-process-buffer\talways scroll Python process buffer
2304py-temp-directory\tdirectory used for temp files (if needed)
2305
2306py-beep-if-tab-change\tring the bell if tab-width is changed
2307%v:py-indent-offset
2308%v:py-block-comment-prefix
2309%v:py-python-command
2310%v:py-scroll-process-buffer
2311%v:py-temp-directory
2312%v:py-beep-if-tab-change
2313
2314@KINDS OF LINES
2315
2316Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002317preceding line ends with a backslash that's not part of a comment, or
2318the paren/bracket/brace nesting level at the start of the line is
2319non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002320
2321An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002322possibly blanks or tabs), a `comment line' (leftmost non-blank
2323character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002324
2325Comment Lines
2326
2327Although all comment lines are treated alike by Python, Python mode
2328recognizes two kinds that act differently with respect to indentation.
2329
2330An `indenting comment line' is a comment line with a blank, tab or
2331nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002332treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333indenting comment line will be indented like the comment line. All
2334other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002335following the initial `#') are `non-indenting comment lines', and
2336their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002337
2338Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002339whenever possible. Non-indenting comment lines are useful in cases
2340like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341
2342\ta = b # a very wordy single-line comment that ends up being
2343\t #... continued onto another line
2344
2345\tif a == b:
2346##\t\tprint 'panic!' # old code we've `commented out'
2347\t\treturn a
2348
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002349Since the `#...' and `##' comment lines have a non-whitespace
2350character following the initial `#', Python mode ignores them when
2351computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002352
2353Continuation Lines and Statements
2354
2355The Python-mode commands generally work on statements instead of on
2356individual lines, where a `statement' is a comment or blank line, or a
2357code line and all of its following continuation lines (if any)
2358considered as a single logical unit. The commands in this mode
2359generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002360statement containing point, even if point happens to be in the middle
2361of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002362
2363
2364@INDENTATION
2365
2366Primarily for entering new code:
2367\t\\[indent-for-tab-command]\t indent line appropriately
2368\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002369\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002370
2371Primarily for reindenting existing code:
2372\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2373\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2374
2375\t\\[py-indent-region]\t reindent region to match its context
2376\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2377\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2378
2379Unlike most programming languages, Python uses indentation, and only
2380indentation, to specify block structure. Hence the indentation supplied
2381automatically by Python-mode is just an educated guess: only you know
2382the block structure you intend, so only you can supply correct
2383indentation.
2384
2385The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2386the indentation of preceding statements. E.g., assuming
2387py-indent-offset is 4, after you enter
2388\tif a > 0: \\[py-newline-and-indent]
2389the cursor will be moved to the position of the `_' (_ is not a
2390character in the file, it's just used here to indicate the location of
2391the cursor):
2392\tif a > 0:
2393\t _
2394If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2395to
2396\tif a > 0:
2397\t c = d
2398\t _
2399Python-mode cannot know whether that's what you intended, or whether
2400\tif a > 0:
2401\t c = d
2402\t_
2403was your intent. In general, Python-mode either reproduces the
2404indentation of the (closest code or indenting-comment) preceding
2405statement, or adds an extra py-indent-offset blanks if the preceding
2406statement has `:' as its last significant (non-whitespace and non-
2407comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002408\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002409
2410Continuation lines are given extra indentation. If you don't like the
2411suggested indentation, change it to something you do like, and Python-
2412mode will strive to indent later lines of the statement in the same way.
2413
2414If a line is a continuation line by virtue of being in an unclosed
2415paren/bracket/brace structure (`list', for short), the suggested
2416indentation depends on whether the current line contains the first item
2417in the list. If it does, it's indented py-indent-offset columns beyond
2418the indentation of the line containing the open bracket. If you don't
2419like that, change it by hand. The remaining items in the list will mimic
2420whatever indentation you give to the first item.
2421
2422If a line is a continuation line because the line preceding it ends with
2423a backslash, the third and following lines of the statement inherit their
2424indentation from the line preceding them. The indentation of the second
2425line in the statement depends on the form of the first (base) line: if
2426the base line is an assignment statement with anything more interesting
2427than the backslash following the leftmost assigning `=', the second line
2428is indented two columns beyond that `='. Else it's indented to two
2429columns beyond the leftmost solid chunk of non-whitespace characters on
2430the base line.
2431
2432Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2433repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2434structure you intend.
2435%c:indent-for-tab-command
2436%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002437%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002438
2439
2440The next function may be handy when editing code you didn't write:
2441%c:py-guess-indent-offset
2442
2443
2444The remaining `indent' functions apply to a region of Python code. They
2445assume the block structure (equals indentation, in Python) of the region
2446is correct, and alter the indentation in various ways while preserving
2447the block structure:
2448%c:py-indent-region
2449%c:py-shift-region-left
2450%c:py-shift-region-right
2451
2452@MARKING & MANIPULATING REGIONS OF CODE
2453
2454\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002455\\[py-mark-def-or-class]\t mark smallest enclosing def
2456\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002457\\[comment-region]\t comment out region of code
2458\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002459%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002460%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002461%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002462
2463@MOVING POINT
2464
2465\\[py-previous-statement]\t move to statement preceding point
2466\\[py-next-statement]\t move to statement following point
2467\\[py-goto-block-up]\t move up to start of current block
2468\\[beginning-of-python-def-or-class]\t move to start of def
2469\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2470\\[end-of-python-def-or-class]\t move to end of def
2471\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2472
2473The first two move to one statement beyond the statement that contains
2474point. A numeric prefix argument tells them to move that many
2475statements instead. Blank lines, comment lines, and continuation lines
2476do not count as `statements' for these commands. So, e.g., you can go
2477to the first code statement in a file by entering
2478\t\\[beginning-of-buffer]\t to move to the top of the file
2479\t\\[py-next-statement]\t to skip over initial comments and blank lines
2480Or do `\\[py-previous-statement]' with a huge prefix argument.
2481%c:py-previous-statement
2482%c:py-next-statement
2483%c:py-goto-block-up
2484%c:beginning-of-python-def-or-class
2485%c:end-of-python-def-or-class
2486
2487@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2488
2489`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2490
2491`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2492overall class and def structure of a module.
2493
2494`\\[back-to-indentation]' moves point to a line's first non-blank character.
2495
2496`\\[indent-relative]' is handy for creating odd indentation.
2497
2498@OTHER EMACS HINTS
2499
2500If you don't like the default value of a variable, change its value to
2501whatever you do like by putting a `setq' line in your .emacs file.
2502E.g., to set the indentation increment to 4, put this line in your
2503.emacs:
2504\t(setq py-indent-offset 4)
2505To see the value of a variable, do `\\[describe-variable]' and enter the variable
2506name at the prompt.
2507
2508When entering a key sequence like `C-c C-n', it is not necessary to
2509release the CONTROL key after doing the `C-c' part -- it suffices to
2510press the CONTROL key, press and release `c' (while still holding down
2511CONTROL), press and release `n' (while still holding down CONTROL), &
2512then release CONTROL.
2513
2514Entering Python mode calls with no arguments the value of the variable
2515`python-mode-hook', if that value exists and is not nil; for backward
2516compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2517the Elisp manual for details.
2518
2519Obscure: When python-mode is first loaded, it looks for all bindings
2520to newline-and-indent in the global keymap, and shadows them with
2521local bindings to py-newline-and-indent."))
2522
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002523
2524;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002525(defvar py-parse-state-re
2526 (concat
2527 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2528 "\\|"
2529 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002530
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531;; returns the parse state at point (see parse-partial-sexp docs)
2532(defun py-parse-state ()
2533 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002534 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002535 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002536 (while (not done)
2537 ;; back up to the first preceding line (if any; else start of
2538 ;; buffer) that begins with a popular Python keyword, or a
2539 ;; non- whitespace and non-comment character. These are good
2540 ;; places to start parsing to see whether where we started is
2541 ;; at a non-zero nesting level. It may be slow for people who
2542 ;; write huge code blocks or huge lists ... tough beans.
2543 (re-search-backward py-parse-state-re nil 'move)
2544 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002545 ;; In XEmacs, we have a much better way to test for whether
2546 ;; we're in a triple-quoted string or not. Emacs does not
2547 ;; have this built-in function, which is it's loss because
2548 ;; without scanning from the beginning of the buffer, there's
2549 ;; no accurate way to determine this otherwise.
2550 (if (not (fboundp 'buffer-syntactic-context))
2551 ;; Emacs
2552 (save-excursion
2553 (setq pps (parse-partial-sexp (point) here))
2554 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002555 (setq done (or (not (nth 3 pps))
2556 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002557 ;; XEmacs
2558 (setq done (or (not (buffer-syntactic-context))
2559 (bobp)))
2560 (when done
2561 (setq pps (parse-partial-sexp (point) here)))
2562 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002563 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002564
2565;; if point is at a non-zero nesting level, returns the number of the
2566;; character that opens the smallest enclosing unclosed list; else
2567;; returns nil.
2568(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002569 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002570 (if (zerop (car status))
2571 nil ; not in a nest
2572 (car (cdr status))))) ; char# of open bracket
2573
2574;; t iff preceding line ends with backslash that's not in a comment
2575(defun py-backslash-continuation-line-p ()
2576 (save-excursion
2577 (beginning-of-line)
2578 (and
2579 ;; use a cheap test first to avoid the regexp if possible
2580 ;; use 'eq' because char-after may return nil
2581 (eq (char-after (- (point) 2)) ?\\ )
2582 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002583 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002584 (looking-at py-continued-re))))
2585
2586;; t iff current line is a continuation line
2587(defun py-continuation-line-p ()
2588 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002589 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002590 (or (py-backslash-continuation-line-p)
2591 (py-nesting-level))))
2592
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002593;; go to initial line of current statement; usually this is the line
2594;; we're on, but if we're on the 2nd or following lines of a
2595;; continuation block, we need to go up to the first line of the
2596;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002597;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002598;; Tricky: We want to avoid quadratic-time behavior for long continued
2599;; blocks, whether of the backslash or open-bracket varieties, or a
2600;; mix of the two. The following manages to do that in the usual
2601;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002602;;
2603;; Also, if we're sitting inside a triple quoted string, this will
2604;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002605(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002606 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002607 (while (py-continuation-line-p)
2608 (beginning-of-line)
2609 (if (py-backslash-continuation-line-p)
2610 (while (py-backslash-continuation-line-p)
2611 (forward-line -1))
2612 ;; else zip out of nested brackets/braces/parens
2613 (while (setq open-bracket-pos (py-nesting-level))
2614 (goto-char open-bracket-pos)))))
2615 (beginning-of-line))
2616
2617;; go to point right beyond final line of current statement; usually
2618;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002619;; statement we need to skip over the continuation lines. Tricky:
2620;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002621(defun py-goto-beyond-final-line ()
2622 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002623 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002624 (while (and (py-continuation-line-p)
2625 (not (eobp)))
2626 ;; skip over the backslash flavor
2627 (while (and (py-backslash-continuation-line-p)
2628 (not (eobp)))
2629 (forward-line 1))
2630 ;; if in nest, zip to the end of the nest
2631 (setq state (py-parse-state))
2632 (if (and (not (zerop (car state)))
2633 (not (eobp)))
2634 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002635 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002636 (forward-line 1))))))
2637
2638;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002639;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002640(defun py-statement-opens-block-p ()
2641 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002642 (let ((start (point))
2643 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2644 (searching t)
2645 (answer nil)
2646 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002647 (goto-char start)
2648 (while searching
2649 ;; look for a colon with nothing after it except whitespace, and
2650 ;; maybe a comment
2651 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2652 finish t)
2653 (if (eq (point) finish) ; note: no `else' clause; just
2654 ; keep searching if we're not at
2655 ; the end yet
2656 ;; sure looks like it opens a block -- but it might
2657 ;; be in a comment
2658 (progn
2659 (setq searching nil) ; search is done either way
2660 (setq state (parse-partial-sexp start
2661 (match-beginning 0)))
2662 (setq answer (not (nth 4 state)))))
2663 ;; search failed: couldn't find another interesting colon
2664 (setq searching nil)))
2665 answer)))
2666
Barry Warsawf831d811996-07-31 20:42:59 +00002667(defun py-statement-closes-block-p ()
2668 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002669 ;; starts with `return', `raise', `break', `continue', and `pass'.
2670 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002671 (let ((here (point)))
2672 (back-to-indentation)
2673 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002674 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002675 (goto-char here))))
2676
Barry Warsaw7ae77681994-12-12 20:38:05 +00002677;; go to point right beyond final line of block begun by the current
2678;; line. This is the same as where py-goto-beyond-final-line goes
2679;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002680;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002681(defun py-goto-beyond-block ()
2682 (if (py-statement-opens-block-p)
2683 (py-mark-block nil 'just-move)
2684 (py-goto-beyond-final-line)))
2685
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002686;; go to start of first statement (not blank or comment or
2687;; continuation line) at or preceding point. returns t if there is
2688;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002689(defun py-goto-statement-at-or-above ()
2690 (py-goto-initial-line)
2691 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002692 ;; skip back over blank & comment lines
2693 ;; note: will skip a blank or comment line that happens to be
2694 ;; a continuation line too
2695 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2696 (progn (py-goto-initial-line) t)
2697 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002698 t))
2699
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002700;; go to start of first statement (not blank or comment or
2701;; continuation line) following the statement containing point returns
2702;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002703(defun py-goto-statement-below ()
2704 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002705 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002706 (py-goto-beyond-final-line)
2707 (while (and
2708 (looking-at py-blank-or-comment-re)
2709 (not (eobp)))
2710 (forward-line 1))
2711 (if (eobp)
2712 (progn (goto-char start) nil)
2713 t)))
2714
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002715;; go to start of statement, at or preceding point, starting with
2716;; keyword KEY. Skips blank lines and non-indenting comments upward
2717;; first. If that statement starts with KEY, done, else go back to
2718;; first enclosing block starting with KEY. If successful, leaves
2719;; point at the start of the KEY line & returns t. Else leaves point
2720;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002721(defun py-go-up-tree-to-keyword (key)
2722 ;; skip blanks and non-indenting #
2723 (py-goto-initial-line)
2724 (while (and
2725 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2726 (zerop (forward-line -1))) ; go back
2727 nil)
2728 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002729 (let* ((re (concat "[ \t]*" key "\\b"))
2730 (case-fold-search nil) ; let* so looking-at sees this
2731 (found (looking-at re))
2732 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002733 (while (not (or found dead))
2734 (condition-case nil ; in case no enclosing block
2735 (py-goto-block-up 'no-mark)
2736 (error (setq dead t)))
2737 (or dead (setq found (looking-at re))))
2738 (beginning-of-line)
2739 found))
2740
2741;; return string in buffer from start of indentation to end of line;
2742;; prefix "..." if leading whitespace was skipped
2743(defun py-suck-up-leading-text ()
2744 (save-excursion
2745 (back-to-indentation)
2746 (concat
2747 (if (bolp) "" "...")
2748 (buffer-substring (point) (progn (end-of-line) (point))))))
2749
2750;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2751;; as a Lisp symbol; return nil if none
2752(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002753 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002754 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2755 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2756 nil)))
2757
Barry Warsawb3e81d51996-09-04 15:12:42 +00002758(defun py-current-defun ()
2759 ;; tell add-log.el how to find the current function/method/variable
2760 (save-excursion
2761 (if (re-search-backward py-defun-start-re nil t)
2762 (or (match-string 3)
2763 (let ((method (match-string 2)))
2764 (if (and (not (zerop (length (match-string 1))))
2765 (re-search-backward py-class-start-re nil t))
2766 (concat (match-string 1) "." method)
2767 method)))
2768 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002769
2770
Barry Warsawfec75d61995-07-05 23:26:15 +00002771(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002772 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002773
Barry Warsaw850437a1995-03-08 21:50:28 +00002774(defun py-version ()
2775 "Echo the current version of `python-mode' in the minibuffer."
2776 (interactive)
2777 (message "Using `python-mode' version %s" py-version)
2778 (py-keep-region-active))
2779
2780;; only works under Emacs 19
2781;(eval-when-compile
2782; (require 'reporter))
2783
2784(defun py-submit-bug-report (enhancement-p)
2785 "Submit via mail a bug report on `python-mode'.
2786With \\[universal-argument] just submit an enhancement request."
2787 (interactive
2788 (list (not (y-or-n-p
2789 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002790 (let ((reporter-prompt-for-summary-p (if enhancement-p
2791 "(Very) brief summary: "
2792 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002793 (require 'reporter)
2794 (reporter-submit-bug-report
2795 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002796 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002797 ;; varlist
2798 (if enhancement-p nil
2799 '(py-python-command
2800 py-indent-offset
2801 py-block-comment-prefix
2802 py-scroll-process-buffer
2803 py-temp-directory
2804 py-beep-if-tab-change))
2805 nil ;pre-hooks
2806 nil ;post-hooks
2807 "Dear Barry,") ;salutation
2808 (if enhancement-p nil
2809 (set-mark (point))
2810 (insert
2811"Please replace this text with a sufficiently large code sample\n\
2812and an exact recipe so that I can reproduce your problem. Failure\n\
2813to do so may mean a greater delay in fixing your bug.\n\n")
2814 (exchange-point-and-mark)
2815 (py-keep-region-active))))
2816
2817
Barry Warsaw47384781997-11-26 05:27:45 +00002818(defun py-kill-emacs-hook ()
2819 (mapcar #'(lambda (filename)
2820 (py-safe (delete-file filename)))
2821 py-file-queue))
2822
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002823;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002824(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002825
2826
2827
2828(provide 'python-mode)
2829;;; python-mode.el ends here