blob: a18300020050d0abefda5fe93db558bfc273209a [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 Warsaw5204b4a1998-04-02 19:27:18 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
67;; Please see <http://www.python.org/ftp/emacs/pmdetails.html> for the
68;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsaw8f972b71998-02-05 20:45:49 +0000145(defcustom py-python-command-args '("-i")
146 "*List of string arguments to be used when starting a Python shell."
147 :type '(repeat string)
148 :group 'python)
149
Barry Warsawc72c11c1997-08-09 06:42:08 +0000150(defcustom py-indent-offset 4
151 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000152Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000153when you're editing someone else's Python code."
154 :type 'integer
155 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000156
Barry Warsaw742a5111998-03-13 17:29:15 +0000157(defcustom py-smart-indentation t
158 "*Should `python-mode' try to automagically set some indentation variables?
159When this variable is non-nil, two things happen when a buffer is set
160to `python-mode':
161
162 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000163 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000164 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000165 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000166
Barry Warsaw639eea61998-03-16 18:12:13 +0000167 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
168 equal `tab-width' (`indent-tabs-mode' is never turned on by
169 Python mode). This means that for newly written code, tabs are
170 only inserted in indentation if one tab is one indentation
171 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000172
Barry Warsaw8046bef1998-03-13 20:04:52 +0000173Note that both these settings occur *after* `python-mode-hook' is run,
174so if you want to defeat the automagic configuration, you must also
175set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000176 :type 'boolean
177 :group 'python)
178
Barry Warsawc72c11c1997-08-09 06:42:08 +0000179(defcustom py-align-multiline-strings-p t
180 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000181When this flag is non-nil, continuation lines are lined up under the
182preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000183lines are aligned to column zero."
184 :type '(choice (const :tag "Align under preceding line" t)
185 (const :tag "Align to column zero" nil))
186 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000187
Barry Warsawc72c11c1997-08-09 06:42:08 +0000188(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000189 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000190This should follow the convention for non-indenting comment lines so
191that the indentation commands won't get confused (i.e., the string
192should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193`...' is arbitrary)."
194 :type 'string
195 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000196
Barry Warsawc72c11c1997-08-09 06:42:08 +0000197(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000198 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000199
Barry Warsaw6d627751996-03-06 18:41:38 +0000200When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000202
203When t, lines that begin with a single `#' are a hint to subsequent
204line indentation. If the previous line is such a comment line (as
205opposed to one that starts with `py-block-comment-prefix'), then it's
206indentation is used as a hint for this line's indentation. Lines that
207begin with `py-block-comment-prefix' are ignored for indentation
208purposes.
209
210When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211indentation hints, unless the comment character is in column zero."
212 :type '(choice
213 (const :tag "Skip all comment lines (fast)" nil)
214 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000215 (const :tag "Single # `sets' indentation except at column zero"
216 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000217 )
218 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000219
Barry Warsaw8ee4a601998-02-06 16:01:52 +0000220(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000221 "*Scroll Python process buffer as output arrives.
222If nil, the Python process buffer acts, with respect to scrolling, like
223Shell-mode buffers normally act. This is surprisingly complicated and
224so won't be explained here; in fact, you can't get the whole story
225without studying the Emacs C code.
226
227If non-nil, the behavior is different in two respects (which are
228slightly inaccurate in the interest of brevity):
229
230 - If the buffer is in a window, and you left point at its end, the
231 window will scroll as new output arrives, and point will move to the
232 buffer's end, even if the window is not the selected window (that
233 being the one the cursor is in). The usual behavior for shell-mode
234 windows is not to scroll, and to leave point where it was, if the
235 buffer is in a window other than the selected window.
236
237 - If the buffer is not visible in any window, and you left point at
238 its end, the buffer will be popped into a window as soon as more
239 output arrives. This is handy if you have a long-running
240 computation and don't want to tie up screen area waiting for the
241 output. The usual behavior for a shell-mode buffer is to stay
242 invisible until you explicitly visit it.
243
244Note the `and if you left point at its end' clauses in both of the
245above: you can `turn off' the special behaviors while output is in
246progress, by visiting the Python buffer and moving point to anywhere
247besides the end. Then the buffer won't scroll, point will remain where
248you leave it, and if you hide the buffer it will stay hidden until you
249visit it again. You can enable and disable the special behaviors as
250often as you like, while output is in progress, by (respectively) moving
251point to, or away from, the end of the buffer.
252
253Warning: If you expect a large amount of output, you'll probably be
254happier setting this option to nil.
255
256Obscure: `End of buffer' above should really say `at or beyond the
257process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000258told <grin>."
259 :type 'boolean
260 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261
Barry Warsaw516b6201997-08-09 06:43:20 +0000262(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000263 (let ((ok '(lambda (x)
264 (and x
265 (setq x (expand-file-name x)) ; always true
266 (file-directory-p x)
267 (file-writable-p x)
268 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269 (or (funcall ok (getenv "TMPDIR"))
270 (funcall ok "/usr/tmp")
271 (funcall ok "/tmp")
272 (funcall ok ".")
273 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000274 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000275 "*Directory used for temp files created by a *Python* process.
276By default, the first directory from this list that exists and that you
277can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000278/usr/tmp, /tmp, or the current directory."
279 :type 'string
280 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000281
Barry Warsaw516b6201997-08-09 06:43:20 +0000282(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 "*Ring the bell if tab-width is changed.
284If a comment of the form
285
286 \t# vi:set tabsize=<number>:
287
288is found before the first code line when the file is entered, and the
289current value of (the general Emacs variable) `tab-width' does not
290equal <number>, `tab-width' is set to <number>, a message saying so is
291displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000292the Emacs bell is also rung as a warning."
293 :type 'boolean
294 :group 'python)
295
Barry Warsaw9981d221997-12-03 05:25:48 +0000296(defcustom py-jump-on-exception t
297 "*Jump to innermost exception frame in *Python Output* buffer.
298When this variable is non-nil and ane exception occurs when running
299Python code synchronously in a subprocess, jump immediately to the
300source code of the innermost frame.")
301
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000302(defcustom py-backspace-function 'backward-delete-char-untabify
303 "*Function called by `py-electric-backspace' when deleting backwards."
304 :type 'function
305 :group 'python)
306
307(defcustom py-delete-function 'delete-char
308 "*Function called by `py-electric-delete' when deleting forwards."
309 :type 'function
310 :group 'python)
311
Barry Warsawc0ecb531998-01-20 21:43:34 +0000312;; Not customizable
313(defvar py-master-file nil
314 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000315The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000316variable section, e.g.:
317
318 # Local Variables:
319 # py-master-file: \"master.py\"
320 # End:
321
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000322so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000323named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000324name has a relative path, the `default-directory' for the buffer is
325prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000326(make-variable-buffer-local 'py-master-file)
327
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000328
Barry Warsawc72c11c1997-08-09 06:42:08 +0000329
330;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
331;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
332
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000333(defconst py-emacs-features
334 (let (features)
335 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
336 ;; the same string.
337 (let ((tmp1 (make-temp-name ""))
338 (tmp2 (make-temp-name "")))
339 (if (string-equal tmp1 tmp2)
340 (push 'broken-temp-names features)))
341 ;; return the features
342 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000343 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000344There are many flavors of Emacs out there, with different levels of
345support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000346
Barry Warsawfb07f401997-02-24 03:37:22 +0000347(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000348 (let ((kw1 (mapconcat 'identity
349 '("and" "assert" "break" "class"
350 "continue" "def" "del" "elif"
351 "else" "except" "exec" "for"
352 "from" "global" "if" "import"
353 "in" "is" "lambda" "not"
354 "or" "pass" "print" "raise"
355 "return" "while"
356 )
357 "\\|"))
358 (kw2 (mapconcat 'identity
359 '("else:" "except:" "finally:" "try:")
360 "\\|"))
361 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000362 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000363 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000364 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
365 ;; block introducing keywords with immediately following colons.
366 ;; Yes "except" is in both lists.
367 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000368 ;; classes
369 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
370 1 font-lock-type-face)
371 ;; functions
372 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
373 1 font-lock-function-name-face)
374 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000375 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000376(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
377
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000378
Barry Warsaw81437461996-08-01 19:48:02 +0000379(defvar imenu-example--python-show-method-args-p nil
380 "*Controls echoing of arguments of functions & methods in the imenu buffer.
381When non-nil, arguments are printed.")
382
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000383(make-variable-buffer-local 'py-indent-offset)
384
Barry Warsawe467bfb1997-11-26 05:40:58 +0000385;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386(defvar py-file-queue nil
387 "Queue of Python temp files awaiting execution.
388Currently-active file is at the head of the list.")
389
Barry Warsawc72c11c1997-08-09 06:42:08 +0000390
391;; Constants
392
393;; Regexp matching a Python string literal
394(defconst py-stringlit-re
395 (concat
396 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
397 "\\|" ; or
398 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
399
400;; Regexp matching Python lines that are continued via backslash.
401;; This is tricky because a trailing backslash does not mean
402;; continuation if it's in a comment
403(defconst py-continued-re
404 (concat
405 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
406 "\\\\$"))
407
408;; Regexp matching blank or comment lines.
409(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
410
411;; Regexp matching clauses to be outdented one level.
412(defconst py-outdent-re
413 (concat "\\(" (mapconcat 'identity
414 '("else:"
415 "except\\(\\s +.*\\)?:"
416 "finally:"
417 "elif\\s +.*:")
418 "\\|")
419 "\\)"))
420
421
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000422;; Regexp matching keywords which typically close a block
423(defconst py-block-closing-keywords-re
424 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
425
Barry Warsawc72c11c1997-08-09 06:42:08 +0000426;; Regexp matching lines to not outdent after.
427(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000428 (concat
429 "\\("
430 (mapconcat 'identity
431 (list "try:"
432 "except\\(\\s +.*\\)?:"
433 "while\\s +.*:"
434 "for\\s +.*:"
435 "if\\s +.*:"
436 "elif\\s +.*:"
437 (concat py-block-closing-keywords-re "[ \t\n]")
438 )
439 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000440 "\\)"))
441
442;; Regexp matching a function, method or variable assignment. If you
443;; change this, you probably have to change `py-current-defun' as
444;; well. This is only used by `py-current-defun' to find the name for
445;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000446(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000447 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
448
449;; Regexp for finding a class name. If you change this, you probably
450;; have to change `py-current-defun' as well. This is only used by
451;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000452(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
453
454;; Regexp that describes tracebacks
455(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000456 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000457
458
459
460;; Utilities
461
462(defmacro py-safe (&rest body)
463 ;; safely execute BODY, return nil if an error occurred
464 (` (condition-case nil
465 (progn (,@ body))
466 (error nil))))
467
468(defsubst py-keep-region-active ()
469 ;; Do whatever is necessary to keep the region active in XEmacs.
470 ;; Ignore byte-compiler warnings you might see. Also note that
471 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
472 ;; to take explicit action.
473 (and (boundp 'zmacs-region-stays)
474 (setq zmacs-region-stays t)))
475
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000476(defsubst py-point (position)
477 ;; Returns the value of point at certain commonly referenced POSITIONs.
478 ;; POSITION can be one of the following symbols:
479 ;;
480 ;; bol -- beginning of line
481 ;; eol -- end of line
482 ;; bod -- beginning of defun
483 ;; boi -- back to indentation
484 ;;
485 ;; This function does not modify point or mark.
486 (let ((here (point)))
487 (cond
488 ((eq position 'bol) (beginning-of-line))
489 ((eq position 'eol) (end-of-line))
490 ((eq position 'bod) (beginning-of-python-def-or-class))
491 ((eq position 'bob) (beginning-of-buffer))
492 ((eq position 'eob) (end-of-buffer))
493 ((eq position 'boi) (back-to-indentation))
494 (t (error "unknown buffer position requested: %s" position))
495 )
496 (prog1
497 (point)
498 (goto-char here))))
499
500(defsubst py-highlight-line (from to file line)
501 (cond
502 ((fboundp 'make-extent)
503 ;; XEmacs
504 (let ((e (make-extent from to)))
505 (set-extent-property e 'mouse-face 'highlight)
506 (set-extent-property e 'py-exc-info (cons file line))
507 (set-extent-property e 'keymap py-mode-output-map)))
508 (t
509 ;; Emacs -- Please port this!
510 )
511 ))
512
Barry Warsawe908b6b1998-03-19 22:48:02 +0000513(defun py-in-literal (&optional lim)
514 ;; Determine if point is in a Python literal, defined as a comment
515 ;; or string. This is the version used for non-XEmacs, which has a
516 ;; nicer interface.
517 ;;
518 ;; WARNING: Watch out for infinite recursion.
519 (let* ((lim (or lim (c-point 'bod)))
520 (state (parse-partial-sexp lim (point))))
521 (cond
522 ((nth 3 state) 'string)
523 ((nth 4 state) 'comment)
524 (t nil))))
525
526;; XEmacs has a built-in function that should make this much quicker.
527;; In this case, lim is ignored
528(defun py-fast-in-literal (&optional lim)
529 ;; don't have to worry about context == 'block-comment
530 (buffer-syntactic-context))
531
532(if (fboundp 'buffer-syntactic-context)
533 (defalias 'c-in-literal 'c-fast-in-literal))
534
535
Barry Warsawc72c11c1997-08-09 06:42:08 +0000536
537;; Major mode boilerplate
538
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539;; define a mode-specific abbrev table for those who use such things
540(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000541 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542(define-abbrev-table 'python-mode-abbrev-table nil)
543
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544(defvar python-mode-hook nil
545 "*Hook called by `python-mode'.")
546
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000547;; in previous version of python-mode.el, the hook was incorrectly
548;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549(and (fboundp 'make-obsolete-variable)
550 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
551
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000552(defvar py-mode-map ()
553 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000555 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000557 ;; electric keys
558 (define-key py-mode-map ":" 'py-electric-colon)
559 ;; indentation level modifiers
560 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
561 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
562 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
563 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
564 ;; subprocess commands
565 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
566 (define-key py-mode-map "\C-c|" 'py-execute-region)
567 (define-key py-mode-map "\C-c!" 'py-shell)
568 ;; Caution! Enter here at your own risk. We are trying to support
569 ;; several behaviors and it gets disgusting. :-( This logic ripped
570 ;; largely from CC Mode.
571 ;;
572 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
573 ;; backwards deletion behavior to DEL, which both Delete and
574 ;; Backspace get translated to. There's no way to separate this
575 ;; behavior in a clean way, so deal with it! Besides, it's been
576 ;; this way since the dawn of time.
577 (if (not (boundp 'delete-key-deletes-forward))
578 (define-key py-mode-map "\177" 'py-electric-backspace)
579 ;; However, XEmacs 20 actually achieved enlightenment. It is
580 ;; possible to sanely define both backward and forward deletion
581 ;; behavior under X separately (TTYs are forever beyond hope, but
582 ;; who cares? XEmacs 20 does the right thing with these too).
583 (define-key py-mode-map [delete] 'py-electric-delete)
584 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000585 ;; Separate M-BS from C-M-h. The former should remain
586 ;; backward-kill-word.
587 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000588 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000589 ;; Miscellaneous
590 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
591 (define-key py-mode-map "\C-c\t" 'py-indent-region)
592 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
593 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
594 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000595 (define-key py-mode-map "\C-c#" 'py-comment-region)
596 (define-key py-mode-map "\C-c?" 'py-describe-mode)
597 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
598 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
599 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000600 (define-key py-mode-map "\C-c-" 'py-up-exception)
601 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000602 ;; information
603 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
604 (define-key py-mode-map "\C-c\C-v" 'py-version)
605 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000606 (define-key py-mode-map "\n" 'py-newline-and-indent)
607 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000608 ;; shadow global bindings for newline-and-indent w/ the py- version.
609 ;; BAW - this is extremely bad form, but I'm not going to change it
610 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000611 (mapcar #'(lambda (key)
612 (define-key py-mode-map key 'py-newline-and-indent))
613 (where-is-internal 'newline-and-indent))
614 )
615
616(defvar py-mode-output-map nil
617 "Keymap used in *Python Output* buffers*")
618(if py-mode-output-map
619 nil
620 (setq py-mode-output-map (make-sparse-keymap))
621 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
622 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
623 ;; TBD: Disable all self-inserting keys. This is bogus, we should
624 ;; really implement this as *Python Output* buffer being read-only
625 (mapcar #' (lambda (key)
626 (define-key py-mode-output-map key
627 #'(lambda () (interactive) (beep))))
628 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000629 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000631(defvar py-mode-syntax-table nil
632 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000633(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000634 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000635 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000636 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
637 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
638 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
639 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
640 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
641 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
642 ;; Add operator symbols misassigned in the std table
643 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
644 (modify-syntax-entry ?\% "." py-mode-syntax-table)
645 (modify-syntax-entry ?\& "." py-mode-syntax-table)
646 (modify-syntax-entry ?\* "." py-mode-syntax-table)
647 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
648 (modify-syntax-entry ?\- "." py-mode-syntax-table)
649 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
650 (modify-syntax-entry ?\< "." py-mode-syntax-table)
651 (modify-syntax-entry ?\= "." py-mode-syntax-table)
652 (modify-syntax-entry ?\> "." py-mode-syntax-table)
653 (modify-syntax-entry ?\| "." py-mode-syntax-table)
654 ;; For historical reasons, underscore is word class instead of
655 ;; symbol class. GNU conventions say it should be symbol class, but
656 ;; there's a natural conflict between what major mode authors want
657 ;; and what users expect from `forward-word' and `backward-word'.
658 ;; Guido and I have hashed this out and have decided to keep
659 ;; underscore in word class. If you're tempted to change it, try
660 ;; binding M-f and M-b to py-forward-into-nomenclature and
661 ;; py-backward-into-nomenclature instead.
662 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
663 ;; Both single quote and double quote are string delimiters
664 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
665 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
666 ;; backquote is open and close paren
667 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
668 ;; comment delimiters
669 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
670 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
671 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000672
Barry Warsawb3e81d51996-09-04 15:12:42 +0000673
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000674
Barry Warsaw42f707f1996-07-29 21:05:05 +0000675;; Menu definitions, only relevent if you have the easymenu.el package
676;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000677(defvar py-menu nil
678 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000679This menu will get created automatically if you have the `easymenu'
680package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000681
Barry Warsawc72c11c1997-08-09 06:42:08 +0000682(and (py-safe (require 'easymenu) t)
683 (easy-menu-define
684 py-menu py-mode-map "Python Mode menu"
685 '("Python"
686 ["Comment Out Region" py-comment-region (mark)]
687 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
688 "-"
689 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000690 ["Mark current def" py-mark-def-or-class t]
691 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000692 "-"
693 ["Shift region left" py-shift-region-left (mark)]
694 ["Shift region right" py-shift-region-right (mark)]
695 "-"
696 ["Execute buffer" py-execute-buffer t]
697 ["Execute region" py-execute-region (mark)]
698 ["Start interpreter..." py-shell t]
699 "-"
700 ["Go to start of block" py-goto-block-up t]
701 ["Go to start of class" (beginning-of-python-def-or-class t) t]
702 ["Move to end of class" (end-of-python-def-or-class t) t]
703 ["Move to start of def" beginning-of-python-def-or-class t]
704 ["Move to end of def" end-of-python-def-or-class t]
705 "-"
706 ["Describe mode" py-describe-mode t]
707 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000708
Barry Warsaw81437461996-08-01 19:48:02 +0000709
710
711;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
712(defvar imenu-example--python-class-regexp
713 (concat ; <<classes>>
714 "\\(" ;
715 "^[ \t]*" ; newline and maybe whitespace
716 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
717 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000718 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000719 "[ \t]*:" ; and the final :
720 "\\)" ; >>classes<<
721 )
722 "Regexp for Python classes for use with the imenu package."
723 )
724
725(defvar imenu-example--python-method-regexp
726 (concat ; <<methods and functions>>
727 "\\(" ;
728 "^[ \t]*" ; new line and maybe whitespace
729 "\\(def[ \t]+" ; function definitions start with def
730 "\\([a-zA-Z0-9_]+\\)" ; name is here
731 ; function arguments...
732 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
733 "\\)" ; end of def
734 "[ \t]*:" ; and then the :
735 "\\)" ; >>methods and functions<<
736 )
737 "Regexp for Python methods/functions for use with the imenu package."
738 )
739
740(defvar imenu-example--python-method-no-arg-parens '(2 8)
741 "Indicies into groups of the Python regexp for use with imenu.
742
743Using these values will result in smaller imenu lists, as arguments to
744functions are not listed.
745
746See the variable `imenu-example--python-show-method-args-p' for more
747information.")
748
749(defvar imenu-example--python-method-arg-parens '(2 7)
750 "Indicies into groups of the Python regexp for use with imenu.
751Using these values will result in large imenu lists, as arguments to
752functions are listed.
753
754See the variable `imenu-example--python-show-method-args-p' for more
755information.")
756
757;; Note that in this format, this variable can still be used with the
758;; imenu--generic-function. Otherwise, there is no real reason to have
759;; it.
760(defvar imenu-example--generic-python-expression
761 (cons
762 (concat
763 imenu-example--python-class-regexp
764 "\\|" ; or...
765 imenu-example--python-method-regexp
766 )
767 imenu-example--python-method-no-arg-parens)
768 "Generic Python expression which may be used directly with imenu.
769Used by setting the variable `imenu-generic-expression' to this value.
770Also, see the function \\[imenu-example--create-python-index] for a
771better alternative for finding the index.")
772
773;; These next two variables are used when searching for the python
774;; class/definitions. Just saving some time in accessing the
775;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000776(defvar imenu-example--python-generic-regexp nil)
777(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000778
779
Barry Warsaw81437461996-08-01 19:48:02 +0000780(defun imenu-example--create-python-index ()
781 "Python interface function for imenu package.
782Finds all python classes and functions/methods. Calls function
783\\[imenu-example--create-python-index-engine]. See that function for
784the details of how this works."
785 (setq imenu-example--python-generic-regexp
786 (car imenu-example--generic-python-expression))
787 (setq imenu-example--python-generic-parens
788 (if imenu-example--python-show-method-args-p
789 imenu-example--python-method-arg-parens
790 imenu-example--python-method-no-arg-parens))
791 (goto-char (point-min))
792 (imenu-example--create-python-index-engine nil))
793
794(defun imenu-example--create-python-index-engine (&optional start-indent)
795 "Function for finding imenu definitions in Python.
796
797Finds all definitions (classes, methods, or functions) in a Python
798file for the imenu package.
799
800Returns a possibly nested alist of the form
801
802 (INDEX-NAME . INDEX-POSITION)
803
804The second element of the alist may be an alist, producing a nested
805list as in
806
807 (INDEX-NAME . INDEX-ALIST)
808
809This function should not be called directly, as it calls itself
810recursively and requires some setup. Rather this is the engine for
811the function \\[imenu-example--create-python-index].
812
813It works recursively by looking for all definitions at the current
814indention level. When it finds one, it adds it to the alist. If it
815finds a definition at a greater indentation level, it removes the
816previous definition from the alist. In it's place it adds all
817definitions found at the next indentation level. When it finds a
818definition that is less indented then the current level, it retuns the
819alist it has created thus far.
820
821The optional argument START-INDENT indicates the starting indentation
822at which to continue looking for Python classes, methods, or
823functions. If this is not supplied, the function uses the indentation
824of the first definition found."
825 (let ((index-alist '())
826 (sub-method-alist '())
827 looking-p
828 def-name prev-name
829 cur-indent def-pos
830 (class-paren (first imenu-example--python-generic-parens))
831 (def-paren (second imenu-example--python-generic-parens)))
832 (setq looking-p
833 (re-search-forward imenu-example--python-generic-regexp
834 (point-max) t))
835 (while looking-p
836 (save-excursion
837 ;; used to set def-name to this value but generic-extract-name is
838 ;; new to imenu-1.14. this way it still works with imenu-1.11
839 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
840 (let ((cur-paren (if (match-beginning class-paren)
841 class-paren def-paren)))
842 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000843 (buffer-substring-no-properties (match-beginning cur-paren)
844 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000845 (beginning-of-line)
846 (setq cur-indent (current-indentation)))
847
848 ;; HACK: want to go to the next correct definition location. we
849 ;; explicitly list them here. would be better to have them in a
850 ;; list.
851 (setq def-pos
852 (or (match-beginning class-paren)
853 (match-beginning def-paren)))
854
855 ;; if we don't have a starting indent level, take this one
856 (or start-indent
857 (setq start-indent cur-indent))
858
859 ;; if we don't have class name yet, take this one
860 (or prev-name
861 (setq prev-name def-name))
862
863 ;; what level is the next definition on? must be same, deeper
864 ;; or shallower indentation
865 (cond
866 ;; at the same indent level, add it to the list...
867 ((= start-indent cur-indent)
868
869 ;; if we don't have push, use the following...
870 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
871 (push (cons def-name def-pos) index-alist))
872
873 ;; deeper indented expression, recur...
874 ((< start-indent cur-indent)
875
876 ;; the point is currently on the expression we're supposed to
877 ;; start on, so go back to the last expression. The recursive
878 ;; call will find this place again and add it to the correct
879 ;; list
880 (re-search-backward imenu-example--python-generic-regexp
881 (point-min) 'move)
882 (setq sub-method-alist (imenu-example--create-python-index-engine
883 cur-indent))
884
885 (if sub-method-alist
886 ;; we put the last element on the index-alist on the start
887 ;; of the submethod alist so the user can still get to it.
888 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000889 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000890 (cons save-elmt sub-method-alist))
891 index-alist))))
892
893 ;; found less indented expression, we're done.
894 (t
895 (setq looking-p nil)
896 (re-search-backward imenu-example--python-generic-regexp
897 (point-min) t)))
898 (setq prev-name def-name)
899 (and looking-p
900 (setq looking-p
901 (re-search-forward imenu-example--python-generic-regexp
902 (point-max) 'move))))
903 (nreverse index-alist)))
904
Barry Warsaw42f707f1996-07-29 21:05:05 +0000905
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000906;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907(defun python-mode ()
908 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000909To submit a problem report, enter `\\[py-submit-bug-report]' from a
910`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
911documentation. To see what version of `python-mode' you are running,
912enter `\\[py-version]'.
913
914This mode knows about Python indentation, tokens, comments and
915continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916
917COMMANDS
918\\{py-mode-map}
919VARIABLES
920
Barry Warsaw42f707f1996-07-29 21:05:05 +0000921py-indent-offset\t\tindentation increment
922py-block-comment-prefix\t\tcomment string used by comment-region
923py-python-command\t\tshell command to invoke Python interpreter
924py-scroll-process-buffer\t\talways scroll Python process buffer
925py-temp-directory\t\tdirectory used for temp files (if needed)
926py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000927 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000928 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000929 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000930 (make-local-variable 'font-lock-defaults)
931 (make-local-variable 'paragraph-separate)
932 (make-local-variable 'paragraph-start)
933 (make-local-variable 'require-final-newline)
934 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000935 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000936 (make-local-variable 'comment-start-skip)
937 (make-local-variable 'comment-column)
938 (make-local-variable 'indent-region-function)
939 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000940 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000941 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000942 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000943 (setq major-mode 'python-mode
944 mode-name "Python"
945 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000946 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000947 paragraph-separate "^[ \t]*$"
948 paragraph-start "^[ \t]*$"
949 require-final-newline t
950 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000951 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 comment-start-skip "# *"
953 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000954 indent-region-function 'py-indent-region
955 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000956 ;; tell add-log.el how to find the current function/method/variable
957 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000958 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000959 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000960 ;; add the menu
961 (if py-menu
962 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000963 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000964 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000965 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000966 ;; Install Imenu, only works for Emacs.
967 (when (py-safe (require 'imenu))
968 (make-variable-buffer-local 'imenu-create-index-function)
969 (setq imenu-create-index-function
970 (function imenu-example--create-python-index))
971 (setq imenu-generic-expression
972 imenu-example--generic-python-expression)
973 (if (fboundp 'imenu-add-to-menubar)
974 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
975 )
976 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977 (if python-mode-hook
978 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000979 (run-hooks 'py-mode-hook))
980 ;; Now do the automagical guessing
981 (if py-smart-indentation
982 (let ((offset py-indent-offset))
983 ;; Its okay if this fails to guess a good value
984 (if (and (py-safe (py-guess-indent-offset))
985 (<= py-indent-offset 8)
986 (>= py-indent-offset 2))
987 (setq offset py-indent-offset))
988 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000989 ;; Only turn indent-tabs-mode off if tab-width !=
990 ;; py-indent-offset. Never turn it on, because the user must
991 ;; have explicitly turned it off.
992 (if (/= tab-width py-indent-offset)
993 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000994 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000996
Barry Warsawb91b7431995-03-14 15:55:20 +0000997;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000998(defun py-outdent-p ()
999 ;; returns non-nil if the current line should outdent one level
1000 (save-excursion
1001 (and (progn (back-to-indentation)
1002 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001003 (progn (forward-line -1)
1004 (py-goto-initial-line)
1005 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001006 (while (or (looking-at py-blank-or-comment-re)
1007 (bobp))
1008 (backward-to-indentation 1))
1009 (not (looking-at py-no-outdent-re)))
1010 )))
1011
Barry Warsawb91b7431995-03-14 15:55:20 +00001012(defun py-electric-colon (arg)
1013 "Insert a colon.
1014In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001015argument is provided, that many colons are inserted non-electrically.
1016Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001017 (interactive "P")
1018 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001019 ;; are we in a string or comment?
1020 (if (save-excursion
1021 (let ((pps (parse-partial-sexp (save-excursion
1022 (beginning-of-python-def-or-class)
1023 (point))
1024 (point))))
1025 (not (or (nth 3 pps) (nth 4 pps)))))
1026 (save-excursion
1027 (let ((here (point))
1028 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001029 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001030 (if (and (not arg)
1031 (py-outdent-p)
1032 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001033 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001034 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001035 )
1036 (setq outdent py-indent-offset))
1037 ;; Don't indent, only outdent. This assumes that any lines that
1038 ;; are already outdented relative to py-compute-indentation were
1039 ;; put there on purpose. Its highly annoying to have `:' indent
1040 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1041 ;; there a better way to determine this???
1042 (if (< (current-indentation) indent) nil
1043 (goto-char here)
1044 (beginning-of-line)
1045 (delete-horizontal-space)
1046 (indent-to (- indent outdent))
1047 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001048
1049
Barry Warsawa97a3f31997-11-04 18:47:06 +00001050;; Python subprocess utilities and filters
1051(defun py-execute-file (proc filename)
1052 ;; Send a properly formatted execfile('FILENAME') to the underlying
1053 ;; Python interpreter process FILENAME. Make that process's buffer
1054 ;; visible and force display. Also make comint believe the user
1055 ;; typed this string so that kill-output-from-shell does The Right
1056 ;; Thing.
1057 (let ((curbuf (current-buffer))
1058 (procbuf (process-buffer proc))
1059 (comint-scroll-to-bottom-on-output t)
1060 (msg (format "## working on region in file %s...\n" filename))
1061 (cmd (format "execfile('%s')\n" filename)))
1062 (unwind-protect
1063 (progn
1064 (set-buffer procbuf)
1065 (goto-char (point-max))
1066 (move-marker (process-mark proc) (point))
1067 (funcall (process-filter proc) proc msg))
1068 (set-buffer curbuf))
1069 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070
1071(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (let ((curbuf (current-buffer))
1073 (pbuf (process-buffer pyproc))
1074 (pmark (process-mark pyproc))
1075 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 ;; make sure we switch to a different buffer at least once. if we
1077 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 ;; window, and point is before the end, and lots of output is
1079 ;; coming at a fast pace, then (a) simple cursor-movement commands
1080 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1081 ;; to have a visible effect (the window just doesn't get updated,
1082 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1083 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 ;; #b makes no sense to me at all. #a almost makes sense: unless
1086 ;; we actually change buffers, set_buffer_internal in buffer.c
1087 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1088 ;; seems to make the Emacs command loop reluctant to update the
1089 ;; display. Perhaps the default process filter in process.c's
1090 ;; read_process_output has update_mode_lines++ for a similar
1091 ;; reason? beats me ...
1092
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001093 (unwind-protect
1094 ;; make sure current buffer is restored
1095 ;; BAW - we want to check to see if this still applies
1096 (progn
1097 ;; mysterious ugly hack
1098 (if (eq curbuf pbuf)
1099 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001101 (set-buffer pbuf)
1102 (let* ((start (point))
1103 (goback (< start pmark))
1104 (goend (and (not goback) (= start (point-max))))
1105 (buffer-read-only nil))
1106 (goto-char pmark)
1107 (insert string)
1108 (move-marker pmark (point))
1109 (setq file-finished
1110 (and py-file-queue
1111 (equal ">>> "
1112 (buffer-substring
1113 (prog2 (beginning-of-line) (point)
1114 (goto-char pmark))
1115 (point)))))
1116 (if goback (goto-char start)
1117 ;; else
1118 (if py-scroll-process-buffer
1119 (let* ((pop-up-windows t)
1120 (pwin (display-buffer pbuf)))
1121 (set-window-point pwin (point)))))
1122 (set-buffer curbuf)
1123 (if file-finished
1124 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001125 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001126 (setq py-file-queue (cdr py-file-queue))
1127 (if py-file-queue
1128 (py-execute-file pyproc (car py-file-queue)))))
1129 (and goend
1130 (progn (set-buffer pbuf)
1131 (goto-char (point-max))))
1132 ))
1133 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001135(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001136 ;; Highlight exceptions found in BUF. If an exception occurred
1137 ;; return t, otherwise return nil. BUF must exist.
1138 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001139 (save-excursion
1140 (set-buffer buf)
1141 (beginning-of-buffer)
1142 (while (re-search-forward py-traceback-line-re nil t)
1143 (setq file (match-string 1)
1144 line (string-to-int (match-string 2))
1145 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001146 (py-highlight-line bol (py-point 'eol) file line)))
1147 (when (and py-jump-on-exception line)
1148 (beep)
1149 (py-jump-to-exception file line)
1150 (setq err-p t))
1151 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001152
Barry Warsaw9981d221997-12-03 05:25:48 +00001153
Barry Warsawa97a3f31997-11-04 18:47:06 +00001154
1155;;; Subprocess commands
1156
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001157;; only used when (memq 'broken-temp-names py-emacs-features)
1158(defvar py-serial-number 0)
1159(defvar py-exception-buffer nil)
1160(defconst py-output-buffer "*Python Output*")
1161
Barry Warsawa97a3f31997-11-04 18:47:06 +00001162;;;###autoload
1163(defun py-shell ()
1164 "Start an interactive Python interpreter in another window.
1165This is like Shell mode, except that Python is running in the window
1166instead of a shell. See the `Interactive Shell' and `Shell Mode'
1167sections of the Emacs manual for details, especially for the key
1168bindings active in the `*Python*' buffer.
1169
1170See the docs for variable `py-scroll-buffer' for info on scrolling
1171behavior in the process window.
1172
1173Warning: Don't use an interactive Python if you change sys.ps1 or
1174sys.ps2 from their default values, or if you're running code that
1175prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1176distinguish your output from Python's output, and assumes that `>>> '
1177at the start of a line is a prompt from Python. Similarly, the Emacs
1178Shell mode code assumes that both `>>> ' and `... ' at the start of a
1179line are Python prompts. Bad things can happen if you fool either
1180mode.
1181
1182Warning: If you do any editing *in* the process buffer *while* the
1183buffer is accepting output from Python, do NOT attempt to `undo' the
1184changes. Some of the output (nowhere near the parts you changed!) may
1185be lost if you do. This appears to be an Emacs bug, an unfortunate
1186interaction between undo and process filters; the same problem exists in
1187non-Python process buffers using the default (Emacs-supplied) process
1188filter."
1189 ;; BAW - should undo be disabled in the python process buffer, if
1190 ;; this bug still exists?
1191 (interactive)
1192 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001193 (switch-to-buffer-other-window
Barry Warsaw8f972b71998-02-05 20:45:49 +00001194 (apply 'make-comint "Python" py-python-command nil py-python-command-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001195 (make-local-variable 'comint-prompt-regexp)
1196 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1197 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1198 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001199 ;; set up keybindings for this subshell
1200 (local-set-key [tab] 'self-insert-command)
1201 (local-set-key "\C-c-" 'py-up-exception)
1202 (local-set-key "\C-c=" 'py-down-exception)
1203 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001204
Barry Warsawa97a3f31997-11-04 18:47:06 +00001205(defun py-clear-queue ()
1206 "Clear the queue of temporary files waiting to execute."
1207 (interactive)
1208 (let ((n (length py-file-queue)))
1209 (mapcar 'delete-file py-file-queue)
1210 (setq py-file-queue nil)
1211 (message "%d pending files de-queued." n)))
1212
1213(defun py-execute-region (start end &optional async)
1214 "Execute the the region in a Python interpreter.
1215The region is first copied into a temporary file (in the directory
1216`py-temp-directory'). If there is no Python interpreter shell
1217running, this file is executed synchronously using
1218`shell-command-on-region'. If the program is long running, use an
1219optional \\[universal-argument] to run the command asynchronously in
1220its own buffer.
1221
1222If the Python interpreter shell is running, the region is execfile()'d
1223in that shell. If you try to execute regions too quickly,
1224`python-mode' will queue them up and execute them one at a time when
1225it sees a `>>> ' prompt from Python. Each time this happens, the
1226process buffer is popped into a window (if it's not already in some
1227window) so you can see it, and a comment of the form
1228
1229 \t## working on region in file <name>...
1230
1231is inserted at the end. See also the command `py-clear-queue'."
1232 (interactive "r\nP")
1233 (or (< start end)
1234 (error "Region is empty"))
1235 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001236 (temp (if (memq 'broken-temp-names py-emacs-features)
1237 (prog1
1238 (format "python-%d" py-serial-number)
1239 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001240 (make-temp-name "python-")))
1241 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001242 (write-region start end file nil 'nomsg)
1243 (cond
1244 ;; always run the code in it's own asynchronous subprocess
1245 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001246 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001247 (start-process "Python" buf py-python-command "-u" file)
1248 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001249 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001250 ))
1251 ;; if the Python interpreter shell is running, queue it up for
1252 ;; execution there.
1253 (proc
1254 ;; use the existing python shell
1255 (if (not py-file-queue)
1256 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001257 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001258 (push file py-file-queue)
1259 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001260 (t
1261 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001262 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001263 ;; shell-command-on-region kills the output buffer if it never
1264 ;; existed and there's no output from the command
1265 (if (not (get-buffer py-output-buffer))
1266 (message "No output.")
1267 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001268 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1269 (pop-to-buffer py-output-buffer)
1270 (if err-p
1271 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001272 ))
1273 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001274
1275;; Code execution command
1276(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001278If the file local variable `py-master-file' is non-nil, execute the
1279named file instead of the buffer's file.
1280
Barry Warsaw7ae77681994-12-12 20:38:05 +00001281If there is a *Python* process buffer it is used. If a clipping
1282restriction is in effect, only the accessible portion of the buffer is
1283sent. A trailing newline will be supplied if needed.
1284
1285See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001286 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001287 (if py-master-file
1288 (let* ((filename (expand-file-name py-master-file))
1289 (buffer (or (get-file-buffer filename)
1290 (find-file-noselect filename))))
1291 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001292 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001293
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001294
1295
1296(defun py-jump-to-exception (file line)
1297 (let ((buffer (cond ((string-equal file "<stdin>")
1298 py-exception-buffer)
1299 ((and (consp py-exception-buffer)
1300 (string-equal file (car py-exception-buffer)))
1301 (cdr py-exception-buffer))
1302 ((py-safe (find-file-noselect file)))
1303 ;; could not figure out what file the exception
1304 ;; is pointing to, so prompt for it
1305 (t (find-file (read-file-name "Exception file: "
1306 nil
1307 file t))))))
1308 (pop-to-buffer buffer)
1309 (goto-line line)
1310 (message "Jumping to exception in file %s on line %d" file line)))
1311
1312(defun py-mouseto-exception (event)
1313 (interactive "e")
1314 (cond
1315 ((fboundp 'event-point)
1316 ;; XEmacs
1317 (let* ((point (event-point event))
1318 (buffer (event-buffer event))
1319 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1320 (info (and e (extent-property e 'py-exc-info))))
1321 (message "Event point: %d, info: %s" point info)
1322 (and info
1323 (py-jump-to-exception (car info) (cdr info)))
1324 ))
1325 ;; Emacs -- Please port this!
1326 ))
1327
1328(defun py-goto-exception ()
1329 "Go to the line indicated by the traceback."
1330 (interactive)
1331 (let (file line)
1332 (save-excursion
1333 (beginning-of-line)
1334 (if (looking-at py-traceback-line-re)
1335 (setq file (match-string 1)
1336 line (string-to-int (match-string 2)))))
1337 (if (not file)
1338 (error "Not on a traceback line."))
1339 (py-jump-to-exception file line)))
1340
1341(defun py-find-next-exception (start buffer searchdir errwhere)
1342 ;; Go to start position in buffer, search in the specified
1343 ;; direction, and jump to the exception found. If at the end of the
1344 ;; exception, print error message
1345 (let (file line)
1346 (save-excursion
1347 (set-buffer buffer)
1348 (goto-char (py-point start))
1349 (if (funcall searchdir py-traceback-line-re nil t)
1350 (setq file (match-string 1)
1351 line (string-to-int (match-string 2)))))
1352 (if (and file line)
1353 (py-jump-to-exception file line)
1354 (error "%s of traceback" errwhere))))
1355
1356(defun py-down-exception (&optional bottom)
1357 "Go to the next line down in the traceback.
1358With optional \\[universal-argument], jump to the bottom (innermost)
1359exception in the exception stack."
1360 (interactive "P")
1361 (let* ((proc (get-process "Python"))
1362 (buffer (if proc "*Python*" py-output-buffer)))
1363 (if bottom
1364 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1365 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1366
1367(defun py-up-exception (&optional top)
1368 "Go to the previous line up in the traceback.
1369With optional \\[universal-argument], jump to the top (outermost)
1370exception in the exception stack."
1371 (interactive "P")
1372 (let* ((proc (get-process "Python"))
1373 (buffer (if proc "*Python*" py-output-buffer)))
1374 (if top
1375 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001376 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001377
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001378
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001379;; Electric deletion
1380(defun py-electric-backspace (arg)
1381 "Deletes preceding character or levels of indentation.
1382Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001383with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001385If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001386
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001387Otherwise, if point is at the leftmost non-whitespace character of a
1388line that is neither a continuation line nor a non-indenting comment
1389line, or if point is at the end of a blank line, this command reduces
1390the indentation to match that of the line that opened the current
1391block of code. The line that opened the block is displayed in the
1392echo area to help you keep track of where you are. With numeric arg,
1393outdents that many blocks (but not past column zero).
1394
1395Otherwise the preceding character is deleted, converting a tab to
1396spaces if needed so that only a single column position is deleted.
1397Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001398 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001399 (if (or (/= (current-indentation) (current-column))
1400 (bolp)
1401 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001402 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001403 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001404 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001405 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406 ;; force non-blank so py-goto-block-up doesn't ignore it
1407 (insert-char ?* 1)
1408 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409 (let ((base-indent 0) ; indentation of base line
1410 (base-text "") ; and text of base line
1411 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001412 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001413 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001414 (condition-case nil ; in case no enclosing block
1415 (progn
1416 (py-goto-block-up 'no-mark)
1417 (setq base-indent (current-indentation)
1418 base-text (py-suck-up-leading-text)
1419 base-found-p t))
1420 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001421 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422 (delete-char 1) ; toss the dummy character
1423 (delete-horizontal-space)
1424 (indent-to base-indent)
1425 (if base-found-p
1426 (message "Closes block: %s" base-text)))))
1427
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001428
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001429(defun py-electric-delete (arg)
1430 "Deletes preceding or following character or levels of whitespace.
1431
1432The behavior of this function depends on the variable
1433`delete-key-deletes-forward'. If this variable is nil (or does not
1434exist, as in older Emacsen), then this function behaves identical to
1435\\[c-electric-backspace].
1436
1437If `delete-key-deletes-forward' is non-nil and is supported in your
1438Emacs, then deletion occurs in the forward direction, by calling the
1439function in `py-delete-function'."
1440 (interactive "*p")
1441 (if (and (boundp 'delete-key-deletes-forward)
1442 delete-key-deletes-forward)
1443 (funcall py-delete-function arg)
1444 ;; else
1445 (py-electric-backspace arg)))
1446
1447;; required for pending-del and delsel modes
1448(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1449(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1450(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1451(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1452
1453
1454
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001455(defun py-indent-line (&optional arg)
1456 "Fix the indentation of the current line according to Python rules.
1457With \\[universal-argument], ignore outdenting rules for block
1458closing statements (e.g. return, raise, break, continue, pass)
1459
1460This function is normally bound to `indent-line-function' so
1461\\[indent-for-tab-command] will call it."
1462 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001463 (let* ((ci (current-indentation))
1464 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001465 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001466 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001467 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001468 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001469 (if (/= ci need)
1470 (save-excursion
1471 (beginning-of-line)
1472 (delete-horizontal-space)
1473 (indent-to need)))
1474 (if move-to-indentation-p (back-to-indentation))))
1475
1476(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001477 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001478This is just `strives to' because correct indentation can't be computed
1479from scratch for Python code. In general, deletes the whitespace before
1480point, inserts a newline, and takes an educated guess as to how you want
1481the new line indented."
1482 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001483 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001484 (if (< ci (current-column)) ; if point beyond indentation
1485 (newline-and-indent)
1486 ;; else try to act like newline-and-indent "normally" acts
1487 (beginning-of-line)
1488 (insert-char ?\n 1)
1489 (move-to-column ci))))
1490
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001491(defun py-compute-indentation (honor-block-close-p)
1492 ;; implements all the rules for indentation computation. when
1493 ;; honor-block-close-p is non-nil, statements such as return, raise,
1494 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001495 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001496 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001497 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001498 (pps (parse-partial-sexp bod (point)))
1499 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001500 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001501 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001502 ((or (and (nth 3 pps) (nth 3 boipps))
1503 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001504 (save-excursion
1505 (if (not py-align-multiline-strings-p) 0
1506 ;; skip back over blank & non-indenting comment lines
1507 ;; note: will skip a blank or non-indenting comment line
1508 ;; that happens to be a continuation line too
1509 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1510 (back-to-indentation)
1511 (current-column))))
1512 ;; are we on a continuation line?
1513 ((py-continuation-line-p)
1514 (let ((startpos (point))
1515 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001516 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001517 (if open-bracket-pos
1518 (progn
1519 ;; align with first item in list; else a normal
1520 ;; indent beyond the line with the open bracket
1521 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1522 ;; is the first list item on the same line?
1523 (skip-chars-forward " \t")
1524 (if (null (memq (following-char) '(?\n ?# ?\\)))
1525 ; yes, so line up with it
1526 (current-column)
1527 ;; first list item on another line, or doesn't exist yet
1528 (forward-line 1)
1529 (while (and (< (point) startpos)
1530 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1531 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001532 (if (and (< (point) startpos)
1533 (/= startpos
1534 (save-excursion
1535 (goto-char (1+ open-bracket-pos))
1536 (skip-chars-forward " \t\n")
1537 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001538 ;; again mimic the first list item
1539 (current-indentation)
1540 ;; else they're about to enter the first item
1541 (goto-char open-bracket-pos)
1542 (+ (current-indentation) py-indent-offset))))
1543
1544 ;; else on backslash continuation line
1545 (forward-line -1)
1546 (if (py-continuation-line-p) ; on at least 3rd line in block
1547 (current-indentation) ; so just continue the pattern
1548 ;; else started on 2nd line in block, so indent more.
1549 ;; if base line is an assignment with a start on a RHS,
1550 ;; indent to 2 beyond the leftmost "="; else skip first
1551 ;; chunk of non-whitespace characters on base line, + 1 more
1552 ;; column
1553 (end-of-line)
1554 (setq endpos (point) searching t)
1555 (back-to-indentation)
1556 (setq startpos (point))
1557 ;; look at all "=" from left to right, stopping at first
1558 ;; one not nested in a list or string
1559 (while searching
1560 (skip-chars-forward "^=" endpos)
1561 (if (= (point) endpos)
1562 (setq searching nil)
1563 (forward-char 1)
1564 (setq state (parse-partial-sexp startpos (point)))
1565 (if (and (zerop (car state)) ; not in a bracket
1566 (null (nth 3 state))) ; & not in a string
1567 (progn
1568 (setq searching nil) ; done searching in any case
1569 (setq found
1570 (not (or
1571 (eq (following-char) ?=)
1572 (memq (char-after (- (point) 2))
1573 '(?< ?> ?!)))))))))
1574 (if (or (not found) ; not an assignment
1575 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1576 (progn
1577 (goto-char startpos)
1578 (skip-chars-forward "^ \t\n")))
1579 (1+ (current-column))))))
1580
1581 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001582 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001583
Barry Warsawa7891711996-08-01 15:53:09 +00001584 ;; Dfn: "Indenting comment line". A line containing only a
1585 ;; comment, but which is treated like a statement for
1586 ;; indentation calculation purposes. Such lines are only
1587 ;; treated specially by the mode; they are not treated
1588 ;; specially by the Python interpreter.
1589
1590 ;; The rules for indenting comment lines are a line where:
1591 ;; - the first non-whitespace character is `#', and
1592 ;; - the character following the `#' is whitespace, and
1593 ;; - the line is outdented with respect to (i.e. to the left
1594 ;; of) the indentation of the preceding non-blank line.
1595
1596 ;; The first non-blank line following an indenting comment
1597 ;; line is given the same amount of indentation as the
1598 ;; indenting comment line.
1599
1600 ;; All other comment-only lines are ignored for indentation
1601 ;; purposes.
1602
1603 ;; Are we looking at a comment-only line which is *not* an
1604 ;; indenting comment line? If so, we assume that its been
1605 ;; placed at the desired indentation, so leave it alone.
1606 ;; Indenting comment lines are aligned as statements down
1607 ;; below.
1608 ((and (looking-at "[ \t]*#[^ \t\n]")
1609 ;; NOTE: this test will not be performed in older Emacsen
1610 (fboundp 'forward-comment)
1611 (<= (current-indentation)
1612 (save-excursion
1613 (forward-comment (- (point-max)))
1614 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001615 (current-indentation))
1616
1617 ;; else indentation based on that of the statement that
1618 ;; precedes us; use the first line of that statement to
1619 ;; establish the base, in case the user forced a non-std
1620 ;; indentation for the continuation lines (if any)
1621 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001622 ;; skip back over blank & non-indenting comment lines note:
1623 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001624 ;; happens to be a continuation line too. use fast Emacs 19
1625 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001626 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001627 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001628 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001629 (let (done)
1630 (while (not done)
1631 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1632 nil 'move)
1633 (setq done (or (eq py-honor-comment-indentation t)
1634 (bobp)
1635 (/= (following-char) ?#)
1636 (not (zerop (current-column)))))
1637 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001638 ;; if we landed inside a string, go to the beginning of that
1639 ;; string. this handles triple quoted, multi-line spanning
1640 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001641 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001642 (skip (and delim (make-string 1 delim))))
1643 (when skip
1644 (save-excursion
1645 (py-safe (search-backward skip))
1646 (if (and (eq (char-before) delim)
1647 (eq (char-before (1- (point))) delim))
1648 (setq skip (make-string 3 delim))))
1649 ;; we're looking at a triple-quoted string
1650 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001651 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001652 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001653 (+ (current-indentation)
1654 (if (py-statement-opens-block-p)
1655 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001656 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001657 (- py-indent-offset)
1658 0)))
1659 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660
1661(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001665Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667their own buffer-local copy), both those currently existing and those
1668created later in the Emacs session.
1669
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001670Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001671There's no excuse for such foolishness, but sometimes you have to deal
1672with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673`py-indent-offset' to what it thinks it was when they created the
1674mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675
1676Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001677looking for a line that opens a block of code. `py-indent-offset' is
1678set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679statement following it. If the search doesn't succeed going forward,
1680it's tried again going backward."
1681 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001682 (let (new-value
1683 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001684 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001685 (found nil)
1686 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001687 (py-goto-initial-line)
1688 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001689 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1690 (not (py-in-literal restart)))
1691 (setq restart (point))
1692 (py-goto-initial-line)
1693 (if (py-statement-opens-block-p)
1694 (setq found t)
1695 (goto-char restart))))
1696 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697 (goto-char start)
1698 (py-goto-initial-line)
1699 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001700 (setq found (and
1701 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1702 (or (py-goto-initial-line) t) ; always true -- side effect
1703 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001704 (setq colon-indent (current-indentation)
1705 found (and found (zerop (py-next-statement 1)))
1706 new-value (- (current-indentation) colon-indent))
1707 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001708 (if (not found)
1709 (error "Sorry, couldn't guess a value for py-indent-offset")
1710 (funcall (if global 'kill-local-variable 'make-local-variable)
1711 'py-indent-offset)
1712 (setq py-indent-offset new-value)
1713 (message "%s value of py-indent-offset set to %d"
1714 (if global "Global" "Local")
1715 py-indent-offset))
1716 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001717
1718(defun py-shift-region (start end count)
1719 (save-excursion
1720 (goto-char end) (beginning-of-line) (setq end (point))
1721 (goto-char start) (beginning-of-line) (setq start (point))
1722 (indent-rigidly start end count)))
1723
1724(defun py-shift-region-left (start end &optional count)
1725 "Shift region of Python code to the left.
1726The lines from the line containing the start of the current region up
1727to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001728shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729
1730If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001731many columns. With no active region, outdent only the current line.
1732You cannot outdent the region if any line is already at column zero."
1733 (interactive
1734 (let ((p (point))
1735 (m (mark))
1736 (arg current-prefix-arg))
1737 (if m
1738 (list (min p m) (max p m) arg)
1739 (list p (save-excursion (forward-line 1) (point)) arg))))
1740 ;; if any line is at column zero, don't shift the region
1741 (save-excursion
1742 (goto-char start)
1743 (while (< (point) end)
1744 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001745 (if (and (zerop (current-column))
1746 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001747 (error "Region is at left edge."))
1748 (forward-line 1)))
1749 (py-shift-region start end (- (prefix-numeric-value
1750 (or count py-indent-offset))))
1751 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752
1753(defun py-shift-region-right (start end &optional count)
1754 "Shift region of Python code to the right.
1755The lines from the line containing the start of the current region up
1756to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001758
1759If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001760many columns. With no active region, indent only the current line."
1761 (interactive
1762 (let ((p (point))
1763 (m (mark))
1764 (arg current-prefix-arg))
1765 (if m
1766 (list (min p m) (max p m) arg)
1767 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001769 (or count py-indent-offset)))
1770 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771
1772(defun py-indent-region (start end &optional indent-offset)
1773 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001774
Barry Warsaw7ae77681994-12-12 20:38:05 +00001775The lines from the line containing the start of the current region up
1776to (but not including) the line containing the end of the region are
1777reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778character in the first column, the first line is left alone and the
1779rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001780region is reindented with respect to the (closest code or indenting
1781comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001782
1783This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784control structures are introduced or removed, or to reformat code
1785using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001786
1787If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001789used.
1790
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001791Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792is called! This function does not compute proper indentation from
1793scratch (that's impossible in Python), it merely adjusts the existing
1794indentation to be correct in context.
1795
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001796Warning: This function really has no idea what to do with
1797non-indenting comment lines, and shifts them as if they were indenting
1798comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001799
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800Special cases: whitespace is deleted from blank lines; continuation
1801lines are shifted by the same amount their initial line was shifted,
1802in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001803initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001804 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805 (save-excursion
1806 (goto-char end) (beginning-of-line) (setq end (point-marker))
1807 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001808 (let ((py-indent-offset (prefix-numeric-value
1809 (or indent-offset py-indent-offset)))
1810 (indents '(-1)) ; stack of active indent levels
1811 (target-column 0) ; column to which to indent
1812 (base-shifted-by 0) ; amount last base line was shifted
1813 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001814 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 0))
1816 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001817 (while (< (point) end)
1818 (setq ci (current-indentation))
1819 ;; figure out appropriate target column
1820 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821 ((or (eq (following-char) ?#) ; comment in column 1
1822 (looking-at "[ \t]*$")) ; entirely blank
1823 (setq target-column 0))
1824 ((py-continuation-line-p) ; shift relative to base line
1825 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826 (t ; new base line
1827 (if (> ci (car indents)) ; going deeper; push it
1828 (setq indents (cons ci indents))
1829 ;; else we should have seen this indent before
1830 (setq indents (memq ci indents)) ; pop deeper indents
1831 (if (null indents)
1832 (error "Bad indentation in region, at line %d"
1833 (save-restriction
1834 (widen)
1835 (1+ (count-lines 1 (point)))))))
1836 (setq target-column (+ indent-base
1837 (* py-indent-offset
1838 (- (length indents) 2))))
1839 (setq base-shifted-by (- target-column ci))))
1840 ;; shift as needed
1841 (if (/= ci target-column)
1842 (progn
1843 (delete-horizontal-space)
1844 (indent-to target-column)))
1845 (forward-line 1))))
1846 (set-marker end nil))
1847
Barry Warsawa7891711996-08-01 15:53:09 +00001848(defun py-comment-region (beg end &optional arg)
1849 "Like `comment-region' but uses double hash (`#') comment starter."
1850 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001851 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001852 (comment-region beg end arg)))
1853
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854
1855;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001856(defun py-previous-statement (count)
1857 "Go to the start of previous Python statement.
1858If the statement at point is the i'th Python statement, goes to the
1859start of statement i-COUNT. If there is no such statement, goes to the
1860first statement. Returns count of statements left to move.
1861`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 (if (< count 0) (py-next-statement (- count))
1864 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001867 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868 (> count 0)
1869 (zerop (forward-line -1))
1870 (py-goto-statement-at-or-above))
1871 (setq count (1- count)))
1872 (if (> count 0) (goto-char start)))
1873 count))
1874
1875(defun py-next-statement (count)
1876 "Go to the start of next Python statement.
1877If the statement at point is the i'th Python statement, goes to the
1878start of statement i+COUNT. If there is no such statement, goes to the
1879last statement. Returns count of statements left to move. `Statements'
1880do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001881 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001882 (if (< count 0) (py-previous-statement (- count))
1883 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001884 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001886 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001887 (> count 0)
1888 (py-goto-statement-below))
1889 (setq count (1- count)))
1890 (if (> count 0) (goto-char start)))
1891 count))
1892
1893(defun py-goto-block-up (&optional nomark)
1894 "Move up to start of current block.
1895Go to the statement that starts the smallest enclosing block; roughly
1896speaking, this will be the closest preceding statement that ends with a
1897colon and is indented less than the statement you started on. If
1898successful, also sets the mark to the starting point.
1899
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900`\\[py-mark-block]' can be used afterward to mark the whole code
1901block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001902
1903If called from a program, the mark will not be set if optional argument
1904NOMARK is not nil."
1905 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001906 (let ((start (point))
1907 (found nil)
1908 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001909 (py-goto-initial-line)
1910 ;; if on blank or non-indenting comment line, use the preceding stmt
1911 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1912 (progn
1913 (py-goto-statement-at-or-above)
1914 (setq found (py-statement-opens-block-p))))
1915 ;; search back for colon line indented less
1916 (setq initial-indent (current-indentation))
1917 (if (zerop initial-indent)
1918 ;; force fast exit
1919 (goto-char (point-min)))
1920 (while (not (or found (bobp)))
1921 (setq found
1922 (and
1923 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1924 (or (py-goto-initial-line) t) ; always true -- side effect
1925 (< (current-indentation) initial-indent)
1926 (py-statement-opens-block-p))))
1927 (if found
1928 (progn
1929 (or nomark (push-mark start))
1930 (back-to-indentation))
1931 (goto-char start)
1932 (error "Enclosing block not found"))))
1933
1934(defun beginning-of-python-def-or-class (&optional class)
1935 "Move point to start of def (or class, with prefix arg).
1936
1937Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938arg, looks for a `class' instead. The docs assume the `def' case;
1939just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001941If point is in a def statement already, and after the `d', simply
1942moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001943
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001944Else (point is not in a def statement, or at or before the `d' of a
1945def statement), searches for the closest preceding def statement, and
1946leaves point at its start. If no such statement can be found, leaves
1947point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948
1949Returns t iff a def statement is found by these rules.
1950
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001951Note that doing this command repeatedly will take you closer to the
1952start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001953
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001954If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001955`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001956 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001957 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1958 (start-of-line (progn (beginning-of-line) (point)))
1959 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001960 (if (or (/= start-of-stmt start-of-line)
1961 (not at-or-before-p))
1962 (end-of-line)) ; OK to match on this line
1963 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001964 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001965
1966(defun end-of-python-def-or-class (&optional class)
1967 "Move point beyond end of def (or class, with prefix arg) body.
1968
1969By default, looks for an appropriate `def'. If you supply a prefix arg,
1970looks for a `class' instead. The docs assume the `def' case; just
1971substitute `class' for `def' for the other case.
1972
1973If point is in a def statement already, this is the def we use.
1974
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975Else if the def found by `\\[beginning-of-python-def-or-class]'
1976contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001977
1978Else we search forward for the closest following def, and use that.
1979
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980If a def can be found by these rules, point is moved to the start of
1981the line immediately following the def block, and the position of the
1982start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001983
1984Else point is moved to the end of the buffer, and nil is returned.
1985
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001986Note that doing this command repeatedly will take you closer to the
1987end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001988
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001989If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001990`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001992 (let ((start (progn (py-goto-initial-line) (point)))
1993 (which (if class "class" "def"))
1994 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001995 ;; move point to start of appropriate def/class
1996 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1997 (setq state 'at-beginning)
1998 ;; else see if beginning-of-python-def-or-class hits container
1999 (if (and (beginning-of-python-def-or-class class)
2000 (progn (py-goto-beyond-block)
2001 (> (point) start)))
2002 (setq state 'at-end)
2003 ;; else search forward
2004 (goto-char start)
2005 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2006 (progn (setq state 'at-beginning)
2007 (beginning-of-line)))))
2008 (cond
2009 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2010 ((eq state 'at-end) t)
2011 ((eq state 'not-found) nil)
2012 (t (error "internal error in end-of-python-def-or-class")))))
2013
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014
2015;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002016(defun py-mark-block (&optional extend just-move)
2017 "Mark following block of lines. With prefix arg, mark structure.
2018Easier to use than explain. It sets the region to an `interesting'
2019block of succeeding lines. If point is on a blank line, it goes down to
2020the next non-blank line. That will be the start of the region. The end
2021of the region depends on the kind of line at the start:
2022
2023 - If a comment, the region will include all succeeding comment lines up
2024 to (but not including) the next non-comment line (if any).
2025
2026 - Else if a prefix arg is given, and the line begins one of these
2027 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028
2029 if elif else try except finally for while def class
2030
Barry Warsaw7ae77681994-12-12 20:38:05 +00002031 the region will be set to the body of the structure, including
2032 following blocks that `belong' to it, but excluding trailing blank
2033 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002034 and all (if any) of the following `except' and `finally' blocks
2035 that belong to the `try' structure will be in the region. Ditto
2036 for if/elif/else, for/else and while/else structures, and (a bit
2037 degenerate, since they're always one-block structures) def and
2038 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002039
2040 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002041 block (see list above), and the block is not a `one-liner' (i.e.,
2042 the statement ends with a colon, not with code), the region will
2043 include all succeeding lines up to (but not including) the next
2044 code statement (if any) that's indented no more than the starting
2045 line, except that trailing blank and comment lines are excluded.
2046 E.g., if the starting line begins a multi-statement `def'
2047 structure, the region will be set to the full function definition,
2048 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002049
2050 - Else the region will include all succeeding lines up to (but not
2051 including) the next blank line, or code or indenting-comment line
2052 indented strictly less than the starting line. Trailing indenting
2053 comment lines are included in this case, but not trailing blank
2054 lines.
2055
2056A msg identifying the location of the mark is displayed in the echo
2057area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2058
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002059If called from a program, optional argument EXTEND plays the role of
2060the prefix arg, and if optional argument JUST-MOVE is not nil, just
2061moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002062 (interactive "P") ; raw prefix arg
2063 (py-goto-initial-line)
2064 ;; skip over blank lines
2065 (while (and
2066 (looking-at "[ \t]*$") ; while blank line
2067 (not (eobp))) ; & somewhere to go
2068 (forward-line 1))
2069 (if (eobp)
2070 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002071 (let ((initial-pos (point))
2072 (initial-indent (current-indentation))
2073 last-pos ; position of last stmt in region
2074 (followers
2075 '((if elif else) (elif elif else) (else)
2076 (try except finally) (except except) (finally)
2077 (for else) (while else)
2078 (def) (class) ) )
2079 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002080
2081 (cond
2082 ;; if comment line, suck up the following comment lines
2083 ((looking-at "[ \t]*#")
2084 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2085 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2086 (setq last-pos (point)))
2087
2088 ;; else if line is a block line and EXTEND given, suck up
2089 ;; the whole structure
2090 ((and extend
2091 (setq first-symbol (py-suck-up-first-keyword) )
2092 (assq first-symbol followers))
2093 (while (and
2094 (or (py-goto-beyond-block) t) ; side effect
2095 (forward-line -1) ; side effect
2096 (setq last-pos (point)) ; side effect
2097 (py-goto-statement-below)
2098 (= (current-indentation) initial-indent)
2099 (setq next-symbol (py-suck-up-first-keyword))
2100 (memq next-symbol (cdr (assq first-symbol followers))))
2101 (setq first-symbol next-symbol)))
2102
2103 ;; else if line *opens* a block, search for next stmt indented <=
2104 ((py-statement-opens-block-p)
2105 (while (and
2106 (setq last-pos (point)) ; always true -- side effect
2107 (py-goto-statement-below)
2108 (> (current-indentation) initial-indent))
2109 nil))
2110
2111 ;; else plain code line; stop at next blank line, or stmt or
2112 ;; indenting comment line indented <
2113 (t
2114 (while (and
2115 (setq last-pos (point)) ; always true -- side effect
2116 (or (py-goto-beyond-final-line) t)
2117 (not (looking-at "[ \t]*$")) ; stop at blank line
2118 (or
2119 (>= (current-indentation) initial-indent)
2120 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2121 nil)))
2122
2123 ;; skip to end of last stmt
2124 (goto-char last-pos)
2125 (py-goto-beyond-final-line)
2126
2127 ;; set mark & display
2128 (if just-move
2129 () ; just return
2130 (push-mark (point) 'no-msg)
2131 (forward-line -1)
2132 (message "Mark set after: %s" (py-suck-up-leading-text))
2133 (goto-char initial-pos))))
2134
Barry Warsaw2518c671997-11-05 00:51:08 +00002135(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002136 "Set region to body of def (or class, with prefix arg) enclosing point.
2137Pushes the current mark, then point, on the mark ring (all language
2138modes do this, but although it's handy it's never documented ...).
2139
2140In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002141hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2142`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002143
2144And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002145Turned out that was more confusing than useful: the `goto start' and
2146`goto end' commands are usually used to search through a file, and
2147people expect them to act a lot like `search backward' and `search
2148forward' string-search commands. But because Python `def' and `class'
2149can nest to arbitrary levels, finding the smallest def containing
2150point cannot be done via a simple backward search: the def containing
2151point may not be the closest preceding def, or even the closest
2152preceding def that's indented less. The fancy algorithm required is
2153appropriate for the usual uses of this `mark' command, but not for the
2154`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002155
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002156So the def marked by this command may not be the one either of the
2157`goto' commands find: If point is on a blank or non-indenting comment
2158line, moves back to start of the closest preceding code statement or
2159indenting comment line. If this is a `def' statement, that's the def
2160we use. Else searches for the smallest enclosing `def' block and uses
2161that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002162
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002163When an enclosing def is found: The mark is left immediately beyond
2164the last line of the def block. Point is left at the start of the
2165def, except that: if the def is preceded by a number of comment lines
2166followed by (at most) one optional blank line, point is left at the
2167start of the comments; else if the def is preceded by a blank line,
2168point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002169
2170The intent is to mark the containing def/class and its associated
2171documentation, to make moving and duplicating functions and classes
2172pleasant."
2173 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002174 (let ((start (point))
2175 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002176 (push-mark start)
2177 (if (not (py-go-up-tree-to-keyword which))
2178 (progn (goto-char start)
2179 (error "Enclosing %s not found" which))
2180 ;; else enclosing def/class found
2181 (setq start (point))
2182 (py-goto-beyond-block)
2183 (push-mark (point))
2184 (goto-char start)
2185 (if (zerop (forward-line -1)) ; if there is a preceding line
2186 (progn
2187 (if (looking-at "[ \t]*$") ; it's blank
2188 (setq start (point)) ; so reset start point
2189 (goto-char start)) ; else try again
2190 (if (zerop (forward-line -1))
2191 (if (looking-at "[ \t]*#") ; a comment
2192 ;; look back for non-comment line
2193 ;; tricky: note that the regexp matches a blank
2194 ;; line, cuz \n is in the 2nd character class
2195 (and
2196 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2197 (forward-line 1))
2198 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002199 (goto-char start)))))))
2200 (exchange-point-and-mark)
2201 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002202
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002203;; ripped from cc-mode
2204(defun py-forward-into-nomenclature (&optional arg)
2205 "Move forward to end of a nomenclature section or word.
2206With arg, to it arg times.
2207
2208A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2209 (interactive "p")
2210 (let ((case-fold-search nil))
2211 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002212 (re-search-forward
2213 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2214 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002215 (while (and (< arg 0)
2216 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002217 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002218 (point-min) 0))
2219 (forward-char 1)
2220 (setq arg (1+ arg)))))
2221 (py-keep-region-active))
2222
2223(defun py-backward-into-nomenclature (&optional arg)
2224 "Move backward to beginning of a nomenclature section or word.
2225With optional ARG, move that many times. If ARG is negative, move
2226forward.
2227
2228A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2229 (interactive "p")
2230 (py-forward-into-nomenclature (- arg))
2231 (py-keep-region-active))
2232
2233
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002234
2235;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002236
2237;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002238;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2239;; out of the right places, along with the keys they're on & current
2240;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002241(defun py-dump-help-string (str)
2242 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002243 (let ((locals (buffer-local-variables))
2244 funckind funcname func funcdoc
2245 (start 0) mstart end
2246 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002247 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2248 (setq mstart (match-beginning 0) end (match-end 0)
2249 funckind (substring str (match-beginning 1) (match-end 1))
2250 funcname (substring str (match-beginning 2) (match-end 2))
2251 func (intern funcname))
2252 (princ (substitute-command-keys (substring str start mstart)))
2253 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002254 ((equal funckind "c") ; command
2255 (setq funcdoc (documentation func)
2256 keys (concat
2257 "Key(s): "
2258 (mapconcat 'key-description
2259 (where-is-internal func py-mode-map)
2260 ", "))))
2261 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002262 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002263 keys (if (assq func locals)
2264 (concat
2265 "Local/Global values: "
2266 (prin1-to-string (symbol-value func))
2267 " / "
2268 (prin1-to-string (default-value func)))
2269 (concat
2270 "Value: "
2271 (prin1-to-string (symbol-value func))))))
2272 (t ; unexpected
2273 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002274 (princ (format "\n-> %s:\t%s\t%s\n\n"
2275 (if (equal funckind "c") "Command" "Variable")
2276 funcname keys))
2277 (princ funcdoc)
2278 (terpri)
2279 (setq start end))
2280 (princ (substitute-command-keys (substring str start))))
2281 (print-help-return-message)))
2282
2283(defun py-describe-mode ()
2284 "Dump long form of Python-mode docs."
2285 (interactive)
2286 (py-dump-help-string "Major mode for editing Python files.
2287Knows about Python indentation, tokens, comments and continuation lines.
2288Paragraphs are separated by blank lines only.
2289
2290Major sections below begin with the string `@'; specific function and
2291variable docs begin with `->'.
2292
2293@EXECUTING PYTHON CODE
2294
2295\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2296\\[py-execute-region]\tsends the current region
2297\\[py-shell]\tstarts a Python interpreter window; this will be used by
2298\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2299%c:py-execute-buffer
2300%c:py-execute-region
2301%c:py-shell
2302
2303@VARIABLES
2304
2305py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002306py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002307
2308py-python-command\tshell command to invoke Python interpreter
2309py-scroll-process-buffer\talways scroll Python process buffer
2310py-temp-directory\tdirectory used for temp files (if needed)
2311
2312py-beep-if-tab-change\tring the bell if tab-width is changed
2313%v:py-indent-offset
2314%v:py-block-comment-prefix
2315%v:py-python-command
2316%v:py-scroll-process-buffer
2317%v:py-temp-directory
2318%v:py-beep-if-tab-change
2319
2320@KINDS OF LINES
2321
2322Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002323preceding line ends with a backslash that's not part of a comment, or
2324the paren/bracket/brace nesting level at the start of the line is
2325non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002326
2327An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002328possibly blanks or tabs), a `comment line' (leftmost non-blank
2329character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002330
2331Comment Lines
2332
2333Although all comment lines are treated alike by Python, Python mode
2334recognizes two kinds that act differently with respect to indentation.
2335
2336An `indenting comment line' is a comment line with a blank, tab or
2337nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002338treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002339indenting comment line will be indented like the comment line. All
2340other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002341following the initial `#') are `non-indenting comment lines', and
2342their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002343
2344Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002345whenever possible. Non-indenting comment lines are useful in cases
2346like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002347
2348\ta = b # a very wordy single-line comment that ends up being
2349\t #... continued onto another line
2350
2351\tif a == b:
2352##\t\tprint 'panic!' # old code we've `commented out'
2353\t\treturn a
2354
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002355Since the `#...' and `##' comment lines have a non-whitespace
2356character following the initial `#', Python mode ignores them when
2357computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002358
2359Continuation Lines and Statements
2360
2361The Python-mode commands generally work on statements instead of on
2362individual lines, where a `statement' is a comment or blank line, or a
2363code line and all of its following continuation lines (if any)
2364considered as a single logical unit. The commands in this mode
2365generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002366statement containing point, even if point happens to be in the middle
2367of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002368
2369
2370@INDENTATION
2371
2372Primarily for entering new code:
2373\t\\[indent-for-tab-command]\t indent line appropriately
2374\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002375\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002376
2377Primarily for reindenting existing code:
2378\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2379\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2380
2381\t\\[py-indent-region]\t reindent region to match its context
2382\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2383\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2384
2385Unlike most programming languages, Python uses indentation, and only
2386indentation, to specify block structure. Hence the indentation supplied
2387automatically by Python-mode is just an educated guess: only you know
2388the block structure you intend, so only you can supply correct
2389indentation.
2390
2391The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2392the indentation of preceding statements. E.g., assuming
2393py-indent-offset is 4, after you enter
2394\tif a > 0: \\[py-newline-and-indent]
2395the cursor will be moved to the position of the `_' (_ is not a
2396character in the file, it's just used here to indicate the location of
2397the cursor):
2398\tif a > 0:
2399\t _
2400If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2401to
2402\tif a > 0:
2403\t c = d
2404\t _
2405Python-mode cannot know whether that's what you intended, or whether
2406\tif a > 0:
2407\t c = d
2408\t_
2409was your intent. In general, Python-mode either reproduces the
2410indentation of the (closest code or indenting-comment) preceding
2411statement, or adds an extra py-indent-offset blanks if the preceding
2412statement has `:' as its last significant (non-whitespace and non-
2413comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002414\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002415
2416Continuation lines are given extra indentation. If you don't like the
2417suggested indentation, change it to something you do like, and Python-
2418mode will strive to indent later lines of the statement in the same way.
2419
2420If a line is a continuation line by virtue of being in an unclosed
2421paren/bracket/brace structure (`list', for short), the suggested
2422indentation depends on whether the current line contains the first item
2423in the list. If it does, it's indented py-indent-offset columns beyond
2424the indentation of the line containing the open bracket. If you don't
2425like that, change it by hand. The remaining items in the list will mimic
2426whatever indentation you give to the first item.
2427
2428If a line is a continuation line because the line preceding it ends with
2429a backslash, the third and following lines of the statement inherit their
2430indentation from the line preceding them. The indentation of the second
2431line in the statement depends on the form of the first (base) line: if
2432the base line is an assignment statement with anything more interesting
2433than the backslash following the leftmost assigning `=', the second line
2434is indented two columns beyond that `='. Else it's indented to two
2435columns beyond the leftmost solid chunk of non-whitespace characters on
2436the base line.
2437
2438Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2439repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2440structure you intend.
2441%c:indent-for-tab-command
2442%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002443%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002444
2445
2446The next function may be handy when editing code you didn't write:
2447%c:py-guess-indent-offset
2448
2449
2450The remaining `indent' functions apply to a region of Python code. They
2451assume the block structure (equals indentation, in Python) of the region
2452is correct, and alter the indentation in various ways while preserving
2453the block structure:
2454%c:py-indent-region
2455%c:py-shift-region-left
2456%c:py-shift-region-right
2457
2458@MARKING & MANIPULATING REGIONS OF CODE
2459
2460\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002461\\[py-mark-def-or-class]\t mark smallest enclosing def
2462\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002463\\[comment-region]\t comment out region of code
2464\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002465%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002466%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002467%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002468
2469@MOVING POINT
2470
2471\\[py-previous-statement]\t move to statement preceding point
2472\\[py-next-statement]\t move to statement following point
2473\\[py-goto-block-up]\t move up to start of current block
2474\\[beginning-of-python-def-or-class]\t move to start of def
2475\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2476\\[end-of-python-def-or-class]\t move to end of def
2477\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2478
2479The first two move to one statement beyond the statement that contains
2480point. A numeric prefix argument tells them to move that many
2481statements instead. Blank lines, comment lines, and continuation lines
2482do not count as `statements' for these commands. So, e.g., you can go
2483to the first code statement in a file by entering
2484\t\\[beginning-of-buffer]\t to move to the top of the file
2485\t\\[py-next-statement]\t to skip over initial comments and blank lines
2486Or do `\\[py-previous-statement]' with a huge prefix argument.
2487%c:py-previous-statement
2488%c:py-next-statement
2489%c:py-goto-block-up
2490%c:beginning-of-python-def-or-class
2491%c:end-of-python-def-or-class
2492
2493@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2494
2495`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2496
2497`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2498overall class and def structure of a module.
2499
2500`\\[back-to-indentation]' moves point to a line's first non-blank character.
2501
2502`\\[indent-relative]' is handy for creating odd indentation.
2503
2504@OTHER EMACS HINTS
2505
2506If you don't like the default value of a variable, change its value to
2507whatever you do like by putting a `setq' line in your .emacs file.
2508E.g., to set the indentation increment to 4, put this line in your
2509.emacs:
2510\t(setq py-indent-offset 4)
2511To see the value of a variable, do `\\[describe-variable]' and enter the variable
2512name at the prompt.
2513
2514When entering a key sequence like `C-c C-n', it is not necessary to
2515release the CONTROL key after doing the `C-c' part -- it suffices to
2516press the CONTROL key, press and release `c' (while still holding down
2517CONTROL), press and release `n' (while still holding down CONTROL), &
2518then release CONTROL.
2519
2520Entering Python mode calls with no arguments the value of the variable
2521`python-mode-hook', if that value exists and is not nil; for backward
2522compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2523the Elisp manual for details.
2524
2525Obscure: When python-mode is first loaded, it looks for all bindings
2526to newline-and-indent in the global keymap, and shadows them with
2527local bindings to py-newline-and-indent."))
2528
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002529
2530;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531(defvar py-parse-state-re
2532 (concat
2533 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2534 "\\|"
2535 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002536
Barry Warsaw7ae77681994-12-12 20:38:05 +00002537;; returns the parse state at point (see parse-partial-sexp docs)
2538(defun py-parse-state ()
2539 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002540 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002541 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002542 (while (not done)
2543 ;; back up to the first preceding line (if any; else start of
2544 ;; buffer) that begins with a popular Python keyword, or a
2545 ;; non- whitespace and non-comment character. These are good
2546 ;; places to start parsing to see whether where we started is
2547 ;; at a non-zero nesting level. It may be slow for people who
2548 ;; write huge code blocks or huge lists ... tough beans.
2549 (re-search-backward py-parse-state-re nil 'move)
2550 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002551 ;; In XEmacs, we have a much better way to test for whether
2552 ;; we're in a triple-quoted string or not. Emacs does not
2553 ;; have this built-in function, which is it's loss because
2554 ;; without scanning from the beginning of the buffer, there's
2555 ;; no accurate way to determine this otherwise.
2556 (if (not (fboundp 'buffer-syntactic-context))
2557 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002558 (progn
2559 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002560 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002561 (setq done (or (not (nth 3 pps))
2562 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002563 ;; XEmacs
2564 (setq done (or (not (buffer-syntactic-context))
2565 (bobp)))
2566 (when done
2567 (setq pps (parse-partial-sexp (point) here)))
2568 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002569 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002570
2571;; if point is at a non-zero nesting level, returns the number of the
2572;; character that opens the smallest enclosing unclosed list; else
2573;; returns nil.
2574(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002575 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002576 (if (zerop (car status))
2577 nil ; not in a nest
2578 (car (cdr status))))) ; char# of open bracket
2579
2580;; t iff preceding line ends with backslash that's not in a comment
2581(defun py-backslash-continuation-line-p ()
2582 (save-excursion
2583 (beginning-of-line)
2584 (and
2585 ;; use a cheap test first to avoid the regexp if possible
2586 ;; use 'eq' because char-after may return nil
2587 (eq (char-after (- (point) 2)) ?\\ )
2588 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002589 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002590 (looking-at py-continued-re))))
2591
2592;; t iff current line is a continuation line
2593(defun py-continuation-line-p ()
2594 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002595 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002596 (or (py-backslash-continuation-line-p)
2597 (py-nesting-level))))
2598
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002599;; go to initial line of current statement; usually this is the line
2600;; we're on, but if we're on the 2nd or following lines of a
2601;; continuation block, we need to go up to the first line of the
2602;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002603;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002604;; Tricky: We want to avoid quadratic-time behavior for long continued
2605;; blocks, whether of the backslash or open-bracket varieties, or a
2606;; mix of the two. The following manages to do that in the usual
2607;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002608;;
2609;; Also, if we're sitting inside a triple quoted string, this will
2610;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002611(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002612 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002613 (while (py-continuation-line-p)
2614 (beginning-of-line)
2615 (if (py-backslash-continuation-line-p)
2616 (while (py-backslash-continuation-line-p)
2617 (forward-line -1))
2618 ;; else zip out of nested brackets/braces/parens
2619 (while (setq open-bracket-pos (py-nesting-level))
2620 (goto-char open-bracket-pos)))))
2621 (beginning-of-line))
2622
2623;; go to point right beyond final line of current statement; usually
2624;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002625;; statement we need to skip over the continuation lines. Tricky:
2626;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002627(defun py-goto-beyond-final-line ()
2628 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002629 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002630 (while (and (py-continuation-line-p)
2631 (not (eobp)))
2632 ;; skip over the backslash flavor
2633 (while (and (py-backslash-continuation-line-p)
2634 (not (eobp)))
2635 (forward-line 1))
2636 ;; if in nest, zip to the end of the nest
2637 (setq state (py-parse-state))
2638 (if (and (not (zerop (car state)))
2639 (not (eobp)))
2640 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002641 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002642 (forward-line 1))))))
2643
2644;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002645;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002646(defun py-statement-opens-block-p ()
2647 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002648 (let ((start (point))
2649 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2650 (searching t)
2651 (answer nil)
2652 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002653 (goto-char start)
2654 (while searching
2655 ;; look for a colon with nothing after it except whitespace, and
2656 ;; maybe a comment
2657 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2658 finish t)
2659 (if (eq (point) finish) ; note: no `else' clause; just
2660 ; keep searching if we're not at
2661 ; the end yet
2662 ;; sure looks like it opens a block -- but it might
2663 ;; be in a comment
2664 (progn
2665 (setq searching nil) ; search is done either way
2666 (setq state (parse-partial-sexp start
2667 (match-beginning 0)))
2668 (setq answer (not (nth 4 state)))))
2669 ;; search failed: couldn't find another interesting colon
2670 (setq searching nil)))
2671 answer)))
2672
Barry Warsawf831d811996-07-31 20:42:59 +00002673(defun py-statement-closes-block-p ()
2674 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002675 ;; starts with `return', `raise', `break', `continue', and `pass'.
2676 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002677 (let ((here (point)))
2678 (back-to-indentation)
2679 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002680 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002681 (goto-char here))))
2682
Barry Warsaw7ae77681994-12-12 20:38:05 +00002683;; go to point right beyond final line of block begun by the current
2684;; line. This is the same as where py-goto-beyond-final-line goes
2685;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002686;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002687(defun py-goto-beyond-block ()
2688 (if (py-statement-opens-block-p)
2689 (py-mark-block nil 'just-move)
2690 (py-goto-beyond-final-line)))
2691
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002692;; go to start of first statement (not blank or comment or
2693;; continuation line) at or preceding point. returns t if there is
2694;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002695(defun py-goto-statement-at-or-above ()
2696 (py-goto-initial-line)
2697 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002698 ;; skip back over blank & comment lines
2699 ;; note: will skip a blank or comment line that happens to be
2700 ;; a continuation line too
2701 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2702 (progn (py-goto-initial-line) t)
2703 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002704 t))
2705
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002706;; go to start of first statement (not blank or comment or
2707;; continuation line) following the statement containing point returns
2708;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002709(defun py-goto-statement-below ()
2710 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002711 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002712 (py-goto-beyond-final-line)
2713 (while (and
2714 (looking-at py-blank-or-comment-re)
2715 (not (eobp)))
2716 (forward-line 1))
2717 (if (eobp)
2718 (progn (goto-char start) nil)
2719 t)))
2720
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002721;; go to start of statement, at or preceding point, starting with
2722;; keyword KEY. Skips blank lines and non-indenting comments upward
2723;; first. If that statement starts with KEY, done, else go back to
2724;; first enclosing block starting with KEY. If successful, leaves
2725;; point at the start of the KEY line & returns t. Else leaves point
2726;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002727(defun py-go-up-tree-to-keyword (key)
2728 ;; skip blanks and non-indenting #
2729 (py-goto-initial-line)
2730 (while (and
2731 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2732 (zerop (forward-line -1))) ; go back
2733 nil)
2734 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002735 (let* ((re (concat "[ \t]*" key "\\b"))
2736 (case-fold-search nil) ; let* so looking-at sees this
2737 (found (looking-at re))
2738 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002739 (while (not (or found dead))
2740 (condition-case nil ; in case no enclosing block
2741 (py-goto-block-up 'no-mark)
2742 (error (setq dead t)))
2743 (or dead (setq found (looking-at re))))
2744 (beginning-of-line)
2745 found))
2746
2747;; return string in buffer from start of indentation to end of line;
2748;; prefix "..." if leading whitespace was skipped
2749(defun py-suck-up-leading-text ()
2750 (save-excursion
2751 (back-to-indentation)
2752 (concat
2753 (if (bolp) "" "...")
2754 (buffer-substring (point) (progn (end-of-line) (point))))))
2755
2756;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2757;; as a Lisp symbol; return nil if none
2758(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002759 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002760 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2761 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2762 nil)))
2763
Barry Warsawb3e81d51996-09-04 15:12:42 +00002764(defun py-current-defun ()
2765 ;; tell add-log.el how to find the current function/method/variable
2766 (save-excursion
2767 (if (re-search-backward py-defun-start-re nil t)
2768 (or (match-string 3)
2769 (let ((method (match-string 2)))
2770 (if (and (not (zerop (length (match-string 1))))
2771 (re-search-backward py-class-start-re nil t))
2772 (concat (match-string 1) "." method)
2773 method)))
2774 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002775
2776
Barry Warsawfec75d61995-07-05 23:26:15 +00002777(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002778 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002779
Barry Warsaw850437a1995-03-08 21:50:28 +00002780(defun py-version ()
2781 "Echo the current version of `python-mode' in the minibuffer."
2782 (interactive)
2783 (message "Using `python-mode' version %s" py-version)
2784 (py-keep-region-active))
2785
2786;; only works under Emacs 19
2787;(eval-when-compile
2788; (require 'reporter))
2789
2790(defun py-submit-bug-report (enhancement-p)
2791 "Submit via mail a bug report on `python-mode'.
2792With \\[universal-argument] just submit an enhancement request."
2793 (interactive
2794 (list (not (y-or-n-p
2795 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002796 (let ((reporter-prompt-for-summary-p (if enhancement-p
2797 "(Very) brief summary: "
2798 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002799 (require 'reporter)
2800 (reporter-submit-bug-report
2801 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002802 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002803 ;; varlist
2804 (if enhancement-p nil
2805 '(py-python-command
2806 py-indent-offset
2807 py-block-comment-prefix
2808 py-scroll-process-buffer
2809 py-temp-directory
2810 py-beep-if-tab-change))
2811 nil ;pre-hooks
2812 nil ;post-hooks
2813 "Dear Barry,") ;salutation
2814 (if enhancement-p nil
2815 (set-mark (point))
2816 (insert
2817"Please replace this text with a sufficiently large code sample\n\
2818and an exact recipe so that I can reproduce your problem. Failure\n\
2819to do so may mean a greater delay in fixing your bug.\n\n")
2820 (exchange-point-and-mark)
2821 (py-keep-region-active))))
2822
2823
Barry Warsaw47384781997-11-26 05:27:45 +00002824(defun py-kill-emacs-hook ()
2825 (mapcar #'(lambda (filename)
2826 (py-safe (delete-file filename)))
2827 py-file-queue))
2828
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002829;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002830(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002831
2832
2833
2834(provide 'python-mode)
2835;;; python-mode.el ends here