blob: 211fd3c0fe373a1adc1a559db2b5e6f85e6aa6b9 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5e21cb01997-11-05 18:41:11 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
67;; Please see <http://www.python.org/ftp/emacs/pmdetails.html> for the
68;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsaw8f972b71998-02-05 20:45:49 +0000145(defcustom py-python-command-args '("-i")
146 "*List of string arguments to be used when starting a Python shell."
147 :type '(repeat string)
148 :group 'python)
149
Barry Warsawc72c11c1997-08-09 06:42:08 +0000150(defcustom py-indent-offset 4
151 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000152Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000153when you're editing someone else's Python code."
154 :type 'integer
155 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000156
Barry Warsaw742a5111998-03-13 17:29:15 +0000157(defcustom py-smart-indentation t
158 "*Should `python-mode' try to automagically set some indentation variables?
159When this variable is non-nil, two things happen when a buffer is set
160to `python-mode':
161
162 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000163 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000164 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000165 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000166
Barry Warsaw639eea61998-03-16 18:12:13 +0000167 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
168 equal `tab-width' (`indent-tabs-mode' is never turned on by
169 Python mode). This means that for newly written code, tabs are
170 only inserted in indentation if one tab is one indentation
171 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000172
Barry Warsaw8046bef1998-03-13 20:04:52 +0000173Note that both these settings occur *after* `python-mode-hook' is run,
174so if you want to defeat the automagic configuration, you must also
175set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000176 :type 'boolean
177 :group 'python)
178
Barry Warsawc72c11c1997-08-09 06:42:08 +0000179(defcustom py-align-multiline-strings-p t
180 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000181When this flag is non-nil, continuation lines are lined up under the
182preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000183lines are aligned to column zero."
184 :type '(choice (const :tag "Align under preceding line" t)
185 (const :tag "Align to column zero" nil))
186 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000187
Barry Warsawc72c11c1997-08-09 06:42:08 +0000188(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000189 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000190This should follow the convention for non-indenting comment lines so
191that the indentation commands won't get confused (i.e., the string
192should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193`...' is arbitrary)."
194 :type 'string
195 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000196
Barry Warsawc72c11c1997-08-09 06:42:08 +0000197(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000198 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000199
Barry Warsaw6d627751996-03-06 18:41:38 +0000200When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000202
203When t, lines that begin with a single `#' are a hint to subsequent
204line indentation. If the previous line is such a comment line (as
205opposed to one that starts with `py-block-comment-prefix'), then it's
206indentation is used as a hint for this line's indentation. Lines that
207begin with `py-block-comment-prefix' are ignored for indentation
208purposes.
209
210When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211indentation hints, unless the comment character is in column zero."
212 :type '(choice
213 (const :tag "Skip all comment lines (fast)" nil)
214 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000215 (const :tag "Single # `sets' indentation except at column zero"
216 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000217 )
218 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000219
Barry Warsaw8ee4a601998-02-06 16:01:52 +0000220(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000221 "*Scroll Python process buffer as output arrives.
222If nil, the Python process buffer acts, with respect to scrolling, like
223Shell-mode buffers normally act. This is surprisingly complicated and
224so won't be explained here; in fact, you can't get the whole story
225without studying the Emacs C code.
226
227If non-nil, the behavior is different in two respects (which are
228slightly inaccurate in the interest of brevity):
229
230 - If the buffer is in a window, and you left point at its end, the
231 window will scroll as new output arrives, and point will move to the
232 buffer's end, even if the window is not the selected window (that
233 being the one the cursor is in). The usual behavior for shell-mode
234 windows is not to scroll, and to leave point where it was, if the
235 buffer is in a window other than the selected window.
236
237 - If the buffer is not visible in any window, and you left point at
238 its end, the buffer will be popped into a window as soon as more
239 output arrives. This is handy if you have a long-running
240 computation and don't want to tie up screen area waiting for the
241 output. The usual behavior for a shell-mode buffer is to stay
242 invisible until you explicitly visit it.
243
244Note the `and if you left point at its end' clauses in both of the
245above: you can `turn off' the special behaviors while output is in
246progress, by visiting the Python buffer and moving point to anywhere
247besides the end. Then the buffer won't scroll, point will remain where
248you leave it, and if you hide the buffer it will stay hidden until you
249visit it again. You can enable and disable the special behaviors as
250often as you like, while output is in progress, by (respectively) moving
251point to, or away from, the end of the buffer.
252
253Warning: If you expect a large amount of output, you'll probably be
254happier setting this option to nil.
255
256Obscure: `End of buffer' above should really say `at or beyond the
257process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000258told <grin>."
259 :type 'boolean
260 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261
Barry Warsaw516b6201997-08-09 06:43:20 +0000262(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000263 (let ((ok '(lambda (x)
264 (and x
265 (setq x (expand-file-name x)) ; always true
266 (file-directory-p x)
267 (file-writable-p x)
268 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269 (or (funcall ok (getenv "TMPDIR"))
270 (funcall ok "/usr/tmp")
271 (funcall ok "/tmp")
272 (funcall ok ".")
273 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000274 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000275 "*Directory used for temp files created by a *Python* process.
276By default, the first directory from this list that exists and that you
277can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000278/usr/tmp, /tmp, or the current directory."
279 :type 'string
280 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000281
Barry Warsaw516b6201997-08-09 06:43:20 +0000282(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 "*Ring the bell if tab-width is changed.
284If a comment of the form
285
286 \t# vi:set tabsize=<number>:
287
288is found before the first code line when the file is entered, and the
289current value of (the general Emacs variable) `tab-width' does not
290equal <number>, `tab-width' is set to <number>, a message saying so is
291displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000292the Emacs bell is also rung as a warning."
293 :type 'boolean
294 :group 'python)
295
Barry Warsaw9981d221997-12-03 05:25:48 +0000296(defcustom py-jump-on-exception t
297 "*Jump to innermost exception frame in *Python Output* buffer.
298When this variable is non-nil and ane exception occurs when running
299Python code synchronously in a subprocess, jump immediately to the
300source code of the innermost frame.")
301
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000302(defcustom py-backspace-function 'backward-delete-char-untabify
303 "*Function called by `py-electric-backspace' when deleting backwards."
304 :type 'function
305 :group 'python)
306
307(defcustom py-delete-function 'delete-char
308 "*Function called by `py-electric-delete' when deleting forwards."
309 :type 'function
310 :group 'python)
311
Barry Warsawc0ecb531998-01-20 21:43:34 +0000312;; Not customizable
313(defvar py-master-file nil
314 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000315The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000316variable section, e.g.:
317
318 # Local Variables:
319 # py-master-file: \"master.py\"
320 # End:
321
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000322so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000323named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000324name has a relative path, the `default-directory' for the buffer is
325prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000326(make-variable-buffer-local 'py-master-file)
327
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000328
Barry Warsawc72c11c1997-08-09 06:42:08 +0000329
330;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
331;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
332
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000333(defconst py-emacs-features
334 (let (features)
335 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
336 ;; the same string.
337 (let ((tmp1 (make-temp-name ""))
338 (tmp2 (make-temp-name "")))
339 (if (string-equal tmp1 tmp2)
340 (push 'broken-temp-names features)))
341 ;; return the features
342 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000343 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000344There are many flavors of Emacs out there, with different levels of
345support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000346
Barry Warsawfb07f401997-02-24 03:37:22 +0000347(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000348 (let ((kw1 (mapconcat 'identity
349 '("and" "assert" "break" "class"
350 "continue" "def" "del" "elif"
351 "else" "except" "exec" "for"
352 "from" "global" "if" "import"
353 "in" "is" "lambda" "not"
354 "or" "pass" "print" "raise"
355 "return" "while"
356 )
357 "\\|"))
358 (kw2 (mapconcat 'identity
359 '("else:" "except:" "finally:" "try:")
360 "\\|"))
361 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000362 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000363 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000364 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
365 ;; block introducing keywords with immediately following colons.
366 ;; Yes "except" is in both lists.
367 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000368 ;; classes
369 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
370 1 font-lock-type-face)
371 ;; functions
372 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
373 1 font-lock-function-name-face)
374 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000375 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000376(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
377
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000378
Barry Warsaw81437461996-08-01 19:48:02 +0000379(defvar imenu-example--python-show-method-args-p nil
380 "*Controls echoing of arguments of functions & methods in the imenu buffer.
381When non-nil, arguments are printed.")
382
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000383(make-variable-buffer-local 'py-indent-offset)
384
Barry Warsawe467bfb1997-11-26 05:40:58 +0000385;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386(defvar py-file-queue nil
387 "Queue of Python temp files awaiting execution.
388Currently-active file is at the head of the list.")
389
Barry Warsawc72c11c1997-08-09 06:42:08 +0000390
391;; Constants
392
393;; Regexp matching a Python string literal
394(defconst py-stringlit-re
395 (concat
396 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
397 "\\|" ; or
398 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
399
400;; Regexp matching Python lines that are continued via backslash.
401;; This is tricky because a trailing backslash does not mean
402;; continuation if it's in a comment
403(defconst py-continued-re
404 (concat
405 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
406 "\\\\$"))
407
408;; Regexp matching blank or comment lines.
409(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
410
411;; Regexp matching clauses to be outdented one level.
412(defconst py-outdent-re
413 (concat "\\(" (mapconcat 'identity
414 '("else:"
415 "except\\(\\s +.*\\)?:"
416 "finally:"
417 "elif\\s +.*:")
418 "\\|")
419 "\\)"))
420
421
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000422;; Regexp matching keywords which typically close a block
423(defconst py-block-closing-keywords-re
424 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
425
Barry Warsawc72c11c1997-08-09 06:42:08 +0000426;; Regexp matching lines to not outdent after.
427(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000428 (concat
429 "\\("
430 (mapconcat 'identity
431 (list "try:"
432 "except\\(\\s +.*\\)?:"
433 "while\\s +.*:"
434 "for\\s +.*:"
435 "if\\s +.*:"
436 "elif\\s +.*:"
437 (concat py-block-closing-keywords-re "[ \t\n]")
438 )
439 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000440 "\\)"))
441
442;; Regexp matching a function, method or variable assignment. If you
443;; change this, you probably have to change `py-current-defun' as
444;; well. This is only used by `py-current-defun' to find the name for
445;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000446(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000447 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
448
449;; Regexp for finding a class name. If you change this, you probably
450;; have to change `py-current-defun' as well. This is only used by
451;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000452(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
453
454;; Regexp that describes tracebacks
455(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000456 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000457
458
459
460;; Utilities
461
462(defmacro py-safe (&rest body)
463 ;; safely execute BODY, return nil if an error occurred
464 (` (condition-case nil
465 (progn (,@ body))
466 (error nil))))
467
468(defsubst py-keep-region-active ()
469 ;; Do whatever is necessary to keep the region active in XEmacs.
470 ;; Ignore byte-compiler warnings you might see. Also note that
471 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
472 ;; to take explicit action.
473 (and (boundp 'zmacs-region-stays)
474 (setq zmacs-region-stays t)))
475
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000476(defsubst py-point (position)
477 ;; Returns the value of point at certain commonly referenced POSITIONs.
478 ;; POSITION can be one of the following symbols:
479 ;;
480 ;; bol -- beginning of line
481 ;; eol -- end of line
482 ;; bod -- beginning of defun
483 ;; boi -- back to indentation
484 ;;
485 ;; This function does not modify point or mark.
486 (let ((here (point)))
487 (cond
488 ((eq position 'bol) (beginning-of-line))
489 ((eq position 'eol) (end-of-line))
490 ((eq position 'bod) (beginning-of-python-def-or-class))
491 ((eq position 'bob) (beginning-of-buffer))
492 ((eq position 'eob) (end-of-buffer))
493 ((eq position 'boi) (back-to-indentation))
494 (t (error "unknown buffer position requested: %s" position))
495 )
496 (prog1
497 (point)
498 (goto-char here))))
499
500(defsubst py-highlight-line (from to file line)
501 (cond
502 ((fboundp 'make-extent)
503 ;; XEmacs
504 (let ((e (make-extent from to)))
505 (set-extent-property e 'mouse-face 'highlight)
506 (set-extent-property e 'py-exc-info (cons file line))
507 (set-extent-property e 'keymap py-mode-output-map)))
508 (t
509 ;; Emacs -- Please port this!
510 )
511 ))
512
Barry Warsawe908b6b1998-03-19 22:48:02 +0000513(defun py-in-literal (&optional lim)
514 ;; Determine if point is in a Python literal, defined as a comment
515 ;; or string. This is the version used for non-XEmacs, which has a
516 ;; nicer interface.
517 ;;
518 ;; WARNING: Watch out for infinite recursion.
519 (let* ((lim (or lim (c-point 'bod)))
520 (state (parse-partial-sexp lim (point))))
521 (cond
522 ((nth 3 state) 'string)
523 ((nth 4 state) 'comment)
524 (t nil))))
525
526;; XEmacs has a built-in function that should make this much quicker.
527;; In this case, lim is ignored
528(defun py-fast-in-literal (&optional lim)
529 ;; don't have to worry about context == 'block-comment
530 (buffer-syntactic-context))
531
532(if (fboundp 'buffer-syntactic-context)
533 (defalias 'c-in-literal 'c-fast-in-literal))
534
535
Barry Warsawc72c11c1997-08-09 06:42:08 +0000536
537;; Major mode boilerplate
538
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539;; define a mode-specific abbrev table for those who use such things
540(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000541 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542(define-abbrev-table 'python-mode-abbrev-table nil)
543
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544(defvar python-mode-hook nil
545 "*Hook called by `python-mode'.")
546
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000547;; in previous version of python-mode.el, the hook was incorrectly
548;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549(and (fboundp 'make-obsolete-variable)
550 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
551
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000552(defvar py-mode-map ()
553 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000555 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000557 ;; electric keys
558 (define-key py-mode-map ":" 'py-electric-colon)
559 ;; indentation level modifiers
560 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
561 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
562 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
563 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
564 ;; subprocess commands
565 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
566 (define-key py-mode-map "\C-c|" 'py-execute-region)
567 (define-key py-mode-map "\C-c!" 'py-shell)
568 ;; Caution! Enter here at your own risk. We are trying to support
569 ;; several behaviors and it gets disgusting. :-( This logic ripped
570 ;; largely from CC Mode.
571 ;;
572 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
573 ;; backwards deletion behavior to DEL, which both Delete and
574 ;; Backspace get translated to. There's no way to separate this
575 ;; behavior in a clean way, so deal with it! Besides, it's been
576 ;; this way since the dawn of time.
577 (if (not (boundp 'delete-key-deletes-forward))
578 (define-key py-mode-map "\177" 'py-electric-backspace)
579 ;; However, XEmacs 20 actually achieved enlightenment. It is
580 ;; possible to sanely define both backward and forward deletion
581 ;; behavior under X separately (TTYs are forever beyond hope, but
582 ;; who cares? XEmacs 20 does the right thing with these too).
583 (define-key py-mode-map [delete] 'py-electric-delete)
584 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000585 ;; Separate M-BS from C-M-h. The former should remain
586 ;; backward-kill-word.
587 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000588 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000589 ;; Miscellaneous
590 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
591 (define-key py-mode-map "\C-c\t" 'py-indent-region)
592 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
593 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
594 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000595 (define-key py-mode-map "\C-c#" 'py-comment-region)
596 (define-key py-mode-map "\C-c?" 'py-describe-mode)
597 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
598 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
599 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000600 (define-key py-mode-map "\C-c-" 'py-up-exception)
601 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000602 ;; information
603 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
604 (define-key py-mode-map "\C-c\C-v" 'py-version)
605 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000606 (define-key py-mode-map "\n" 'py-newline-and-indent)
607 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000608 ;; shadow global bindings for newline-and-indent w/ the py- version.
609 ;; BAW - this is extremely bad form, but I'm not going to change it
610 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000611 (mapcar #'(lambda (key)
612 (define-key py-mode-map key 'py-newline-and-indent))
613 (where-is-internal 'newline-and-indent))
614 )
615
616(defvar py-mode-output-map nil
617 "Keymap used in *Python Output* buffers*")
618(if py-mode-output-map
619 nil
620 (setq py-mode-output-map (make-sparse-keymap))
621 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
622 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
623 ;; TBD: Disable all self-inserting keys. This is bogus, we should
624 ;; really implement this as *Python Output* buffer being read-only
625 (mapcar #' (lambda (key)
626 (define-key py-mode-output-map key
627 #'(lambda () (interactive) (beep))))
628 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000629 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000631(defvar py-mode-syntax-table nil
632 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000633(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000634 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000635 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000636 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
637 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
638 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
639 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
640 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
641 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
642 ;; Add operator symbols misassigned in the std table
643 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
644 (modify-syntax-entry ?\% "." py-mode-syntax-table)
645 (modify-syntax-entry ?\& "." py-mode-syntax-table)
646 (modify-syntax-entry ?\* "." py-mode-syntax-table)
647 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
648 (modify-syntax-entry ?\- "." py-mode-syntax-table)
649 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
650 (modify-syntax-entry ?\< "." py-mode-syntax-table)
651 (modify-syntax-entry ?\= "." py-mode-syntax-table)
652 (modify-syntax-entry ?\> "." py-mode-syntax-table)
653 (modify-syntax-entry ?\| "." py-mode-syntax-table)
654 ;; For historical reasons, underscore is word class instead of
655 ;; symbol class. GNU conventions say it should be symbol class, but
656 ;; there's a natural conflict between what major mode authors want
657 ;; and what users expect from `forward-word' and `backward-word'.
658 ;; Guido and I have hashed this out and have decided to keep
659 ;; underscore in word class. If you're tempted to change it, try
660 ;; binding M-f and M-b to py-forward-into-nomenclature and
661 ;; py-backward-into-nomenclature instead.
662 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
663 ;; Both single quote and double quote are string delimiters
664 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
665 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
666 ;; backquote is open and close paren
667 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
668 ;; comment delimiters
669 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
670 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
671 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000672
Barry Warsawb3e81d51996-09-04 15:12:42 +0000673
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000674
Barry Warsaw42f707f1996-07-29 21:05:05 +0000675;; Menu definitions, only relevent if you have the easymenu.el package
676;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000677(defvar py-menu nil
678 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000679This menu will get created automatically if you have the `easymenu'
680package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000681
Barry Warsawc72c11c1997-08-09 06:42:08 +0000682(and (py-safe (require 'easymenu) t)
683 (easy-menu-define
684 py-menu py-mode-map "Python Mode menu"
685 '("Python"
686 ["Comment Out Region" py-comment-region (mark)]
687 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
688 "-"
689 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000690 ["Mark current def" py-mark-def-or-class t]
691 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000692 "-"
693 ["Shift region left" py-shift-region-left (mark)]
694 ["Shift region right" py-shift-region-right (mark)]
695 "-"
696 ["Execute buffer" py-execute-buffer t]
697 ["Execute region" py-execute-region (mark)]
698 ["Start interpreter..." py-shell t]
699 "-"
700 ["Go to start of block" py-goto-block-up t]
701 ["Go to start of class" (beginning-of-python-def-or-class t) t]
702 ["Move to end of class" (end-of-python-def-or-class t) t]
703 ["Move to start of def" beginning-of-python-def-or-class t]
704 ["Move to end of def" end-of-python-def-or-class t]
705 "-"
706 ["Describe mode" py-describe-mode t]
707 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000708
Barry Warsaw81437461996-08-01 19:48:02 +0000709
710
711;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
712(defvar imenu-example--python-class-regexp
713 (concat ; <<classes>>
714 "\\(" ;
715 "^[ \t]*" ; newline and maybe whitespace
716 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
717 ; possibly multiple superclasses
718 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
719 "[ \t]*:" ; and the final :
720 "\\)" ; >>classes<<
721 )
722 "Regexp for Python classes for use with the imenu package."
723 )
724
725(defvar imenu-example--python-method-regexp
726 (concat ; <<methods and functions>>
727 "\\(" ;
728 "^[ \t]*" ; new line and maybe whitespace
729 "\\(def[ \t]+" ; function definitions start with def
730 "\\([a-zA-Z0-9_]+\\)" ; name is here
731 ; function arguments...
732 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
733 "\\)" ; end of def
734 "[ \t]*:" ; and then the :
735 "\\)" ; >>methods and functions<<
736 )
737 "Regexp for Python methods/functions for use with the imenu package."
738 )
739
740(defvar imenu-example--python-method-no-arg-parens '(2 8)
741 "Indicies into groups of the Python regexp for use with imenu.
742
743Using these values will result in smaller imenu lists, as arguments to
744functions are not listed.
745
746See the variable `imenu-example--python-show-method-args-p' for more
747information.")
748
749(defvar imenu-example--python-method-arg-parens '(2 7)
750 "Indicies into groups of the Python regexp for use with imenu.
751Using these values will result in large imenu lists, as arguments to
752functions are listed.
753
754See the variable `imenu-example--python-show-method-args-p' for more
755information.")
756
757;; Note that in this format, this variable can still be used with the
758;; imenu--generic-function. Otherwise, there is no real reason to have
759;; it.
760(defvar imenu-example--generic-python-expression
761 (cons
762 (concat
763 imenu-example--python-class-regexp
764 "\\|" ; or...
765 imenu-example--python-method-regexp
766 )
767 imenu-example--python-method-no-arg-parens)
768 "Generic Python expression which may be used directly with imenu.
769Used by setting the variable `imenu-generic-expression' to this value.
770Also, see the function \\[imenu-example--create-python-index] for a
771better alternative for finding the index.")
772
773;; These next two variables are used when searching for the python
774;; class/definitions. Just saving some time in accessing the
775;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000776(defvar imenu-example--python-generic-regexp nil)
777(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000778
779
Barry Warsaw81437461996-08-01 19:48:02 +0000780(defun imenu-example--create-python-index ()
781 "Python interface function for imenu package.
782Finds all python classes and functions/methods. Calls function
783\\[imenu-example--create-python-index-engine]. See that function for
784the details of how this works."
785 (setq imenu-example--python-generic-regexp
786 (car imenu-example--generic-python-expression))
787 (setq imenu-example--python-generic-parens
788 (if imenu-example--python-show-method-args-p
789 imenu-example--python-method-arg-parens
790 imenu-example--python-method-no-arg-parens))
791 (goto-char (point-min))
792 (imenu-example--create-python-index-engine nil))
793
794(defun imenu-example--create-python-index-engine (&optional start-indent)
795 "Function for finding imenu definitions in Python.
796
797Finds all definitions (classes, methods, or functions) in a Python
798file for the imenu package.
799
800Returns a possibly nested alist of the form
801
802 (INDEX-NAME . INDEX-POSITION)
803
804The second element of the alist may be an alist, producing a nested
805list as in
806
807 (INDEX-NAME . INDEX-ALIST)
808
809This function should not be called directly, as it calls itself
810recursively and requires some setup. Rather this is the engine for
811the function \\[imenu-example--create-python-index].
812
813It works recursively by looking for all definitions at the current
814indention level. When it finds one, it adds it to the alist. If it
815finds a definition at a greater indentation level, it removes the
816previous definition from the alist. In it's place it adds all
817definitions found at the next indentation level. When it finds a
818definition that is less indented then the current level, it retuns the
819alist it has created thus far.
820
821The optional argument START-INDENT indicates the starting indentation
822at which to continue looking for Python classes, methods, or
823functions. If this is not supplied, the function uses the indentation
824of the first definition found."
825 (let ((index-alist '())
826 (sub-method-alist '())
827 looking-p
828 def-name prev-name
829 cur-indent def-pos
830 (class-paren (first imenu-example--python-generic-parens))
831 (def-paren (second imenu-example--python-generic-parens)))
832 (setq looking-p
833 (re-search-forward imenu-example--python-generic-regexp
834 (point-max) t))
835 (while looking-p
836 (save-excursion
837 ;; used to set def-name to this value but generic-extract-name is
838 ;; new to imenu-1.14. this way it still works with imenu-1.11
839 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
840 (let ((cur-paren (if (match-beginning class-paren)
841 class-paren def-paren)))
842 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000843 (buffer-substring-no-properties (match-beginning cur-paren)
844 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000845 (beginning-of-line)
846 (setq cur-indent (current-indentation)))
847
848 ;; HACK: want to go to the next correct definition location. we
849 ;; explicitly list them here. would be better to have them in a
850 ;; list.
851 (setq def-pos
852 (or (match-beginning class-paren)
853 (match-beginning def-paren)))
854
855 ;; if we don't have a starting indent level, take this one
856 (or start-indent
857 (setq start-indent cur-indent))
858
859 ;; if we don't have class name yet, take this one
860 (or prev-name
861 (setq prev-name def-name))
862
863 ;; what level is the next definition on? must be same, deeper
864 ;; or shallower indentation
865 (cond
866 ;; at the same indent level, add it to the list...
867 ((= start-indent cur-indent)
868
869 ;; if we don't have push, use the following...
870 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
871 (push (cons def-name def-pos) index-alist))
872
873 ;; deeper indented expression, recur...
874 ((< start-indent cur-indent)
875
876 ;; the point is currently on the expression we're supposed to
877 ;; start on, so go back to the last expression. The recursive
878 ;; call will find this place again and add it to the correct
879 ;; list
880 (re-search-backward imenu-example--python-generic-regexp
881 (point-min) 'move)
882 (setq sub-method-alist (imenu-example--create-python-index-engine
883 cur-indent))
884
885 (if sub-method-alist
886 ;; we put the last element on the index-alist on the start
887 ;; of the submethod alist so the user can still get to it.
888 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000889 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000890 (cons save-elmt sub-method-alist))
891 index-alist))))
892
893 ;; found less indented expression, we're done.
894 (t
895 (setq looking-p nil)
896 (re-search-backward imenu-example--python-generic-regexp
897 (point-min) t)))
898 (setq prev-name def-name)
899 (and looking-p
900 (setq looking-p
901 (re-search-forward imenu-example--python-generic-regexp
902 (point-max) 'move))))
903 (nreverse index-alist)))
904
Barry Warsaw42f707f1996-07-29 21:05:05 +0000905
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000906;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907(defun python-mode ()
908 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000909To submit a problem report, enter `\\[py-submit-bug-report]' from a
910`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
911documentation. To see what version of `python-mode' you are running,
912enter `\\[py-version]'.
913
914This mode knows about Python indentation, tokens, comments and
915continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916
917COMMANDS
918\\{py-mode-map}
919VARIABLES
920
Barry Warsaw42f707f1996-07-29 21:05:05 +0000921py-indent-offset\t\tindentation increment
922py-block-comment-prefix\t\tcomment string used by comment-region
923py-python-command\t\tshell command to invoke Python interpreter
924py-scroll-process-buffer\t\talways scroll Python process buffer
925py-temp-directory\t\tdirectory used for temp files (if needed)
926py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000927 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000928 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000929 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000930 (make-local-variable 'font-lock-defaults)
931 (make-local-variable 'paragraph-separate)
932 (make-local-variable 'paragraph-start)
933 (make-local-variable 'require-final-newline)
934 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000935 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000936 (make-local-variable 'comment-start-skip)
937 (make-local-variable 'comment-column)
938 (make-local-variable 'indent-region-function)
939 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000940 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000941 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000942 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000943 (setq major-mode 'python-mode
944 mode-name "Python"
945 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000946 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000947 paragraph-separate "^[ \t]*$"
948 paragraph-start "^[ \t]*$"
949 require-final-newline t
950 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000951 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 comment-start-skip "# *"
953 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000954 indent-region-function 'py-indent-region
955 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000956 ;; tell add-log.el how to find the current function/method/variable
957 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000958 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000959 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000960 ;; add the menu
961 (if py-menu
962 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000963 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000964 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000965 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000966 ;; Install Imenu, only works for Emacs.
967 (when (py-safe (require 'imenu))
968 (make-variable-buffer-local 'imenu-create-index-function)
969 (setq imenu-create-index-function
970 (function imenu-example--create-python-index))
971 (setq imenu-generic-expression
972 imenu-example--generic-python-expression)
973 (if (fboundp 'imenu-add-to-menubar)
974 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
975 )
976 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977 (if python-mode-hook
978 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000979 (run-hooks 'py-mode-hook))
980 ;; Now do the automagical guessing
981 (if py-smart-indentation
982 (let ((offset py-indent-offset))
983 ;; Its okay if this fails to guess a good value
984 (if (and (py-safe (py-guess-indent-offset))
985 (<= py-indent-offset 8)
986 (>= py-indent-offset 2))
987 (setq offset py-indent-offset))
988 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000989 ;; Only turn indent-tabs-mode off if tab-width !=
990 ;; py-indent-offset. Never turn it on, because the user must
991 ;; have explicitly turned it off.
992 (if (/= tab-width py-indent-offset)
993 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000994 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000996
Barry Warsawb91b7431995-03-14 15:55:20 +0000997;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000998(defun py-outdent-p ()
999 ;; returns non-nil if the current line should outdent one level
1000 (save-excursion
1001 (and (progn (back-to-indentation)
1002 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001003 (progn (forward-line -1)
1004 (py-goto-initial-line)
1005 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001006 (while (or (looking-at py-blank-or-comment-re)
1007 (bobp))
1008 (backward-to-indentation 1))
1009 (not (looking-at py-no-outdent-re)))
1010 )))
1011
Barry Warsawb91b7431995-03-14 15:55:20 +00001012(defun py-electric-colon (arg)
1013 "Insert a colon.
1014In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001015argument is provided, that many colons are inserted non-electrically.
1016Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001017 (interactive "P")
1018 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001019 ;; are we in a string or comment?
1020 (if (save-excursion
1021 (let ((pps (parse-partial-sexp (save-excursion
1022 (beginning-of-python-def-or-class)
1023 (point))
1024 (point))))
1025 (not (or (nth 3 pps) (nth 4 pps)))))
1026 (save-excursion
1027 (let ((here (point))
1028 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001029 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001030 (if (and (not arg)
1031 (py-outdent-p)
1032 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001033 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001034 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001035 )
1036 (setq outdent py-indent-offset))
1037 ;; Don't indent, only outdent. This assumes that any lines that
1038 ;; are already outdented relative to py-compute-indentation were
1039 ;; put there on purpose. Its highly annoying to have `:' indent
1040 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1041 ;; there a better way to determine this???
1042 (if (< (current-indentation) indent) nil
1043 (goto-char here)
1044 (beginning-of-line)
1045 (delete-horizontal-space)
1046 (indent-to (- indent outdent))
1047 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001048
1049
Barry Warsawa97a3f31997-11-04 18:47:06 +00001050;; Python subprocess utilities and filters
1051(defun py-execute-file (proc filename)
1052 ;; Send a properly formatted execfile('FILENAME') to the underlying
1053 ;; Python interpreter process FILENAME. Make that process's buffer
1054 ;; visible and force display. Also make comint believe the user
1055 ;; typed this string so that kill-output-from-shell does The Right
1056 ;; Thing.
1057 (let ((curbuf (current-buffer))
1058 (procbuf (process-buffer proc))
1059 (comint-scroll-to-bottom-on-output t)
1060 (msg (format "## working on region in file %s...\n" filename))
1061 (cmd (format "execfile('%s')\n" filename)))
1062 (unwind-protect
1063 (progn
1064 (set-buffer procbuf)
1065 (goto-char (point-max))
1066 (move-marker (process-mark proc) (point))
1067 (funcall (process-filter proc) proc msg))
1068 (set-buffer curbuf))
1069 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070
1071(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (let ((curbuf (current-buffer))
1073 (pbuf (process-buffer pyproc))
1074 (pmark (process-mark pyproc))
1075 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 ;; make sure we switch to a different buffer at least once. if we
1077 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 ;; window, and point is before the end, and lots of output is
1079 ;; coming at a fast pace, then (a) simple cursor-movement commands
1080 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1081 ;; to have a visible effect (the window just doesn't get updated,
1082 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1083 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 ;; #b makes no sense to me at all. #a almost makes sense: unless
1086 ;; we actually change buffers, set_buffer_internal in buffer.c
1087 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1088 ;; seems to make the Emacs command loop reluctant to update the
1089 ;; display. Perhaps the default process filter in process.c's
1090 ;; read_process_output has update_mode_lines++ for a similar
1091 ;; reason? beats me ...
1092
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001093 (unwind-protect
1094 ;; make sure current buffer is restored
1095 ;; BAW - we want to check to see if this still applies
1096 (progn
1097 ;; mysterious ugly hack
1098 (if (eq curbuf pbuf)
1099 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001101 (set-buffer pbuf)
1102 (let* ((start (point))
1103 (goback (< start pmark))
1104 (goend (and (not goback) (= start (point-max))))
1105 (buffer-read-only nil))
1106 (goto-char pmark)
1107 (insert string)
1108 (move-marker pmark (point))
1109 (setq file-finished
1110 (and py-file-queue
1111 (equal ">>> "
1112 (buffer-substring
1113 (prog2 (beginning-of-line) (point)
1114 (goto-char pmark))
1115 (point)))))
1116 (if goback (goto-char start)
1117 ;; else
1118 (if py-scroll-process-buffer
1119 (let* ((pop-up-windows t)
1120 (pwin (display-buffer pbuf)))
1121 (set-window-point pwin (point)))))
1122 (set-buffer curbuf)
1123 (if file-finished
1124 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001125 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001126 (setq py-file-queue (cdr py-file-queue))
1127 (if py-file-queue
1128 (py-execute-file pyproc (car py-file-queue)))))
1129 (and goend
1130 (progn (set-buffer pbuf)
1131 (goto-char (point-max))))
1132 ))
1133 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001135(defun py-postprocess-output-buffer (buf)
Barry 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))
1532 (if (< (point) startpos)
1533 ;; again mimic the first list item
1534 (current-indentation)
1535 ;; else they're about to enter the first item
1536 (goto-char open-bracket-pos)
1537 (+ (current-indentation) py-indent-offset))))
1538
1539 ;; else on backslash continuation line
1540 (forward-line -1)
1541 (if (py-continuation-line-p) ; on at least 3rd line in block
1542 (current-indentation) ; so just continue the pattern
1543 ;; else started on 2nd line in block, so indent more.
1544 ;; if base line is an assignment with a start on a RHS,
1545 ;; indent to 2 beyond the leftmost "="; else skip first
1546 ;; chunk of non-whitespace characters on base line, + 1 more
1547 ;; column
1548 (end-of-line)
1549 (setq endpos (point) searching t)
1550 (back-to-indentation)
1551 (setq startpos (point))
1552 ;; look at all "=" from left to right, stopping at first
1553 ;; one not nested in a list or string
1554 (while searching
1555 (skip-chars-forward "^=" endpos)
1556 (if (= (point) endpos)
1557 (setq searching nil)
1558 (forward-char 1)
1559 (setq state (parse-partial-sexp startpos (point)))
1560 (if (and (zerop (car state)) ; not in a bracket
1561 (null (nth 3 state))) ; & not in a string
1562 (progn
1563 (setq searching nil) ; done searching in any case
1564 (setq found
1565 (not (or
1566 (eq (following-char) ?=)
1567 (memq (char-after (- (point) 2))
1568 '(?< ?> ?!)))))))))
1569 (if (or (not found) ; not an assignment
1570 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1571 (progn
1572 (goto-char startpos)
1573 (skip-chars-forward "^ \t\n")))
1574 (1+ (current-column))))))
1575
1576 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001577 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001578
Barry Warsawa7891711996-08-01 15:53:09 +00001579 ;; Dfn: "Indenting comment line". A line containing only a
1580 ;; comment, but which is treated like a statement for
1581 ;; indentation calculation purposes. Such lines are only
1582 ;; treated specially by the mode; they are not treated
1583 ;; specially by the Python interpreter.
1584
1585 ;; The rules for indenting comment lines are a line where:
1586 ;; - the first non-whitespace character is `#', and
1587 ;; - the character following the `#' is whitespace, and
1588 ;; - the line is outdented with respect to (i.e. to the left
1589 ;; of) the indentation of the preceding non-blank line.
1590
1591 ;; The first non-blank line following an indenting comment
1592 ;; line is given the same amount of indentation as the
1593 ;; indenting comment line.
1594
1595 ;; All other comment-only lines are ignored for indentation
1596 ;; purposes.
1597
1598 ;; Are we looking at a comment-only line which is *not* an
1599 ;; indenting comment line? If so, we assume that its been
1600 ;; placed at the desired indentation, so leave it alone.
1601 ;; Indenting comment lines are aligned as statements down
1602 ;; below.
1603 ((and (looking-at "[ \t]*#[^ \t\n]")
1604 ;; NOTE: this test will not be performed in older Emacsen
1605 (fboundp 'forward-comment)
1606 (<= (current-indentation)
1607 (save-excursion
1608 (forward-comment (- (point-max)))
1609 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001610 (current-indentation))
1611
1612 ;; else indentation based on that of the statement that
1613 ;; precedes us; use the first line of that statement to
1614 ;; establish the base, in case the user forced a non-std
1615 ;; indentation for the continuation lines (if any)
1616 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001617 ;; skip back over blank & non-indenting comment lines note:
1618 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001619 ;; happens to be a continuation line too. use fast Emacs 19
1620 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001621 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001622 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001623 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001624 (let (done)
1625 (while (not done)
1626 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1627 nil 'move)
1628 (setq done (or (eq py-honor-comment-indentation t)
1629 (bobp)
1630 (/= (following-char) ?#)
1631 (not (zerop (current-column)))))
1632 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001633 ;; if we landed inside a string, go to the beginning of that
1634 ;; string. this handles triple quoted, multi-line spanning
1635 ;; strings.
Barry Warsawf64b4051998-02-12 16:52:14 +00001636 (let* ((pps3 (nth 3 (parse-partial-sexp bod (point))))
1637 (delim (and pps3 (int-to-char pps3)))
1638 (skip (and delim (make-string 1 delim))))
1639 (when skip
1640 (save-excursion
1641 (py-safe (search-backward skip))
1642 (if (and (eq (char-before) delim)
1643 (eq (char-before (1- (point))) delim))
1644 (setq skip (make-string 3 delim))))
1645 ;; we're looking at a triple-quoted string
1646 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001647 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001648 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001649 (+ (current-indentation)
1650 (if (py-statement-opens-block-p)
1651 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001652 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001653 (- py-indent-offset)
1654 0)))
1655 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
1657(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001658 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001659By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001660`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001661Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663their own buffer-local copy), both those currently existing and those
1664created later in the Emacs session.
1665
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667There's no excuse for such foolishness, but sometimes you have to deal
1668with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669`py-indent-offset' to what it thinks it was when they created the
1670mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001671
1672Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673looking for a line that opens a block of code. `py-indent-offset' is
1674set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675statement following it. If the search doesn't succeed going forward,
1676it's tried again going backward."
1677 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001678 (let (new-value
1679 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001680 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001681 (found nil)
1682 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683 (py-goto-initial-line)
1684 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001685 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1686 (not (py-in-literal restart)))
1687 (setq restart (point))
1688 (py-goto-initial-line)
1689 (if (py-statement-opens-block-p)
1690 (setq found t)
1691 (goto-char restart))))
1692 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001693 (goto-char start)
1694 (py-goto-initial-line)
1695 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001696 (setq found (and
1697 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1698 (or (py-goto-initial-line) t) ; always true -- side effect
1699 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001700 (setq colon-indent (current-indentation)
1701 found (and found (zerop (py-next-statement 1)))
1702 new-value (- (current-indentation) colon-indent))
1703 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001704 (if (not found)
1705 (error "Sorry, couldn't guess a value for py-indent-offset")
1706 (funcall (if global 'kill-local-variable 'make-local-variable)
1707 'py-indent-offset)
1708 (setq py-indent-offset new-value)
1709 (message "%s value of py-indent-offset set to %d"
1710 (if global "Global" "Local")
1711 py-indent-offset))
1712 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713
1714(defun py-shift-region (start end count)
1715 (save-excursion
1716 (goto-char end) (beginning-of-line) (setq end (point))
1717 (goto-char start) (beginning-of-line) (setq start (point))
1718 (indent-rigidly start end count)))
1719
1720(defun py-shift-region-left (start end &optional count)
1721 "Shift region of Python code to the left.
1722The lines from the line containing the start of the current region up
1723to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001724shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001725
1726If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001727many columns. With no active region, outdent only the current line.
1728You cannot outdent the region if any line is already at column zero."
1729 (interactive
1730 (let ((p (point))
1731 (m (mark))
1732 (arg current-prefix-arg))
1733 (if m
1734 (list (min p m) (max p m) arg)
1735 (list p (save-excursion (forward-line 1) (point)) arg))))
1736 ;; if any line is at column zero, don't shift the region
1737 (save-excursion
1738 (goto-char start)
1739 (while (< (point) end)
1740 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001741 (if (and (zerop (current-column))
1742 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001743 (error "Region is at left edge."))
1744 (forward-line 1)))
1745 (py-shift-region start end (- (prefix-numeric-value
1746 (or count py-indent-offset))))
1747 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001748
1749(defun py-shift-region-right (start end &optional count)
1750 "Shift region of Python code to the right.
1751The lines from the line containing the start of the current region up
1752to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001753shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754
1755If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001756many columns. With no active region, indent only the current line."
1757 (interactive
1758 (let ((p (point))
1759 (m (mark))
1760 (arg current-prefix-arg))
1761 (if m
1762 (list (min p m) (max p m) arg)
1763 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001765 (or count py-indent-offset)))
1766 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001767
1768(defun py-indent-region (start end &optional indent-offset)
1769 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001770
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771The lines from the line containing the start of the current region up
1772to (but not including) the line containing the end of the region are
1773reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001774character in the first column, the first line is left alone and the
1775rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001776region is reindented with respect to the (closest code or indenting
1777comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778
1779This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780control structures are introduced or removed, or to reformat code
1781using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001782
1783If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785used.
1786
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001787Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001788is called! This function does not compute proper indentation from
1789scratch (that's impossible in Python), it merely adjusts the existing
1790indentation to be correct in context.
1791
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792Warning: This function really has no idea what to do with
1793non-indenting comment lines, and shifts them as if they were indenting
1794comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001796Special cases: whitespace is deleted from blank lines; continuation
1797lines are shifted by the same amount their initial line was shifted,
1798in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001799initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001801 (save-excursion
1802 (goto-char end) (beginning-of-line) (setq end (point-marker))
1803 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001804 (let ((py-indent-offset (prefix-numeric-value
1805 (or indent-offset py-indent-offset)))
1806 (indents '(-1)) ; stack of active indent levels
1807 (target-column 0) ; column to which to indent
1808 (base-shifted-by 0) ; amount last base line was shifted
1809 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001810 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811 0))
1812 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813 (while (< (point) end)
1814 (setq ci (current-indentation))
1815 ;; figure out appropriate target column
1816 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001817 ((or (eq (following-char) ?#) ; comment in column 1
1818 (looking-at "[ \t]*$")) ; entirely blank
1819 (setq target-column 0))
1820 ((py-continuation-line-p) ; shift relative to base line
1821 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822 (t ; new base line
1823 (if (> ci (car indents)) ; going deeper; push it
1824 (setq indents (cons ci indents))
1825 ;; else we should have seen this indent before
1826 (setq indents (memq ci indents)) ; pop deeper indents
1827 (if (null indents)
1828 (error "Bad indentation in region, at line %d"
1829 (save-restriction
1830 (widen)
1831 (1+ (count-lines 1 (point)))))))
1832 (setq target-column (+ indent-base
1833 (* py-indent-offset
1834 (- (length indents) 2))))
1835 (setq base-shifted-by (- target-column ci))))
1836 ;; shift as needed
1837 (if (/= ci target-column)
1838 (progn
1839 (delete-horizontal-space)
1840 (indent-to target-column)))
1841 (forward-line 1))))
1842 (set-marker end nil))
1843
Barry Warsawa7891711996-08-01 15:53:09 +00001844(defun py-comment-region (beg end &optional arg)
1845 "Like `comment-region' but uses double hash (`#') comment starter."
1846 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001847 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001848 (comment-region beg end arg)))
1849
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001850
1851;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001852(defun py-previous-statement (count)
1853 "Go to the start of previous Python statement.
1854If the statement at point is the i'th Python statement, goes to the
1855start of statement i-COUNT. If there is no such statement, goes to the
1856first statement. Returns count of statements left to move.
1857`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001859 (if (< count 0) (py-next-statement (- count))
1860 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001861 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864 (> count 0)
1865 (zerop (forward-line -1))
1866 (py-goto-statement-at-or-above))
1867 (setq count (1- count)))
1868 (if (> count 0) (goto-char start)))
1869 count))
1870
1871(defun py-next-statement (count)
1872 "Go to the start of next Python statement.
1873If the statement at point is the i'th Python statement, goes to the
1874start of statement i+COUNT. If there is no such statement, goes to the
1875last statement. Returns count of statements left to move. `Statements'
1876do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878 (if (< count 0) (py-previous-statement (- count))
1879 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001880 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001882 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883 (> count 0)
1884 (py-goto-statement-below))
1885 (setq count (1- count)))
1886 (if (> count 0) (goto-char start)))
1887 count))
1888
1889(defun py-goto-block-up (&optional nomark)
1890 "Move up to start of current block.
1891Go to the statement that starts the smallest enclosing block; roughly
1892speaking, this will be the closest preceding statement that ends with a
1893colon and is indented less than the statement you started on. If
1894successful, also sets the mark to the starting point.
1895
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896`\\[py-mark-block]' can be used afterward to mark the whole code
1897block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001898
1899If called from a program, the mark will not be set if optional argument
1900NOMARK is not nil."
1901 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001902 (let ((start (point))
1903 (found nil)
1904 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905 (py-goto-initial-line)
1906 ;; if on blank or non-indenting comment line, use the preceding stmt
1907 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1908 (progn
1909 (py-goto-statement-at-or-above)
1910 (setq found (py-statement-opens-block-p))))
1911 ;; search back for colon line indented less
1912 (setq initial-indent (current-indentation))
1913 (if (zerop initial-indent)
1914 ;; force fast exit
1915 (goto-char (point-min)))
1916 (while (not (or found (bobp)))
1917 (setq found
1918 (and
1919 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1920 (or (py-goto-initial-line) t) ; always true -- side effect
1921 (< (current-indentation) initial-indent)
1922 (py-statement-opens-block-p))))
1923 (if found
1924 (progn
1925 (or nomark (push-mark start))
1926 (back-to-indentation))
1927 (goto-char start)
1928 (error "Enclosing block not found"))))
1929
1930(defun beginning-of-python-def-or-class (&optional class)
1931 "Move point to start of def (or class, with prefix arg).
1932
1933Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001934arg, looks for a `class' instead. The docs assume the `def' case;
1935just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001936
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001937If point is in a def statement already, and after the `d', simply
1938moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940Else (point is not in a def statement, or at or before the `d' of a
1941def statement), searches for the closest preceding def statement, and
1942leaves point at its start. If no such statement can be found, leaves
1943point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001944
1945Returns t iff a def statement is found by these rules.
1946
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001947Note that doing this command repeatedly will take you closer to the
1948start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001951`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001952 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001953 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1954 (start-of-line (progn (beginning-of-line) (point)))
1955 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001956 (if (or (/= start-of-stmt start-of-line)
1957 (not at-or-before-p))
1958 (end-of-line)) ; OK to match on this line
1959 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001960 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001961
1962(defun end-of-python-def-or-class (&optional class)
1963 "Move point beyond end of def (or class, with prefix arg) body.
1964
1965By default, looks for an appropriate `def'. If you supply a prefix arg,
1966looks for a `class' instead. The docs assume the `def' case; just
1967substitute `class' for `def' for the other case.
1968
1969If point is in a def statement already, this is the def we use.
1970
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001971Else if the def found by `\\[beginning-of-python-def-or-class]'
1972contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001973
1974Else we search forward for the closest following def, and use that.
1975
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001976If a def can be found by these rules, point is moved to the start of
1977the line immediately following the def block, and the position of the
1978start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001979
1980Else point is moved to the end of the buffer, and nil is returned.
1981
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001982Note that doing this command repeatedly will take you closer to the
1983end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001984
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001985If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001986`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001987 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001988 (let ((start (progn (py-goto-initial-line) (point)))
1989 (which (if class "class" "def"))
1990 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991 ;; move point to start of appropriate def/class
1992 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1993 (setq state 'at-beginning)
1994 ;; else see if beginning-of-python-def-or-class hits container
1995 (if (and (beginning-of-python-def-or-class class)
1996 (progn (py-goto-beyond-block)
1997 (> (point) start)))
1998 (setq state 'at-end)
1999 ;; else search forward
2000 (goto-char start)
2001 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2002 (progn (setq state 'at-beginning)
2003 (beginning-of-line)))))
2004 (cond
2005 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2006 ((eq state 'at-end) t)
2007 ((eq state 'not-found) nil)
2008 (t (error "internal error in end-of-python-def-or-class")))))
2009
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002010
2011;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002012(defun py-mark-block (&optional extend just-move)
2013 "Mark following block of lines. With prefix arg, mark structure.
2014Easier to use than explain. It sets the region to an `interesting'
2015block of succeeding lines. If point is on a blank line, it goes down to
2016the next non-blank line. That will be the start of the region. The end
2017of the region depends on the kind of line at the start:
2018
2019 - If a comment, the region will include all succeeding comment lines up
2020 to (but not including) the next non-comment line (if any).
2021
2022 - Else if a prefix arg is given, and the line begins one of these
2023 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002024
2025 if elif else try except finally for while def class
2026
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 the region will be set to the body of the structure, including
2028 following blocks that `belong' to it, but excluding trailing blank
2029 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030 and all (if any) of the following `except' and `finally' blocks
2031 that belong to the `try' structure will be in the region. Ditto
2032 for if/elif/else, for/else and while/else structures, and (a bit
2033 degenerate, since they're always one-block structures) def and
2034 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002035
2036 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002037 block (see list above), and the block is not a `one-liner' (i.e.,
2038 the statement ends with a colon, not with code), the region will
2039 include all succeeding lines up to (but not including) the next
2040 code statement (if any) that's indented no more than the starting
2041 line, except that trailing blank and comment lines are excluded.
2042 E.g., if the starting line begins a multi-statement `def'
2043 structure, the region will be set to the full function definition,
2044 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002045
2046 - Else the region will include all succeeding lines up to (but not
2047 including) the next blank line, or code or indenting-comment line
2048 indented strictly less than the starting line. Trailing indenting
2049 comment lines are included in this case, but not trailing blank
2050 lines.
2051
2052A msg identifying the location of the mark is displayed in the echo
2053area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2054
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002055If called from a program, optional argument EXTEND plays the role of
2056the prefix arg, and if optional argument JUST-MOVE is not nil, just
2057moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002058 (interactive "P") ; raw prefix arg
2059 (py-goto-initial-line)
2060 ;; skip over blank lines
2061 (while (and
2062 (looking-at "[ \t]*$") ; while blank line
2063 (not (eobp))) ; & somewhere to go
2064 (forward-line 1))
2065 (if (eobp)
2066 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002067 (let ((initial-pos (point))
2068 (initial-indent (current-indentation))
2069 last-pos ; position of last stmt in region
2070 (followers
2071 '((if elif else) (elif elif else) (else)
2072 (try except finally) (except except) (finally)
2073 (for else) (while else)
2074 (def) (class) ) )
2075 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002076
2077 (cond
2078 ;; if comment line, suck up the following comment lines
2079 ((looking-at "[ \t]*#")
2080 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2081 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2082 (setq last-pos (point)))
2083
2084 ;; else if line is a block line and EXTEND given, suck up
2085 ;; the whole structure
2086 ((and extend
2087 (setq first-symbol (py-suck-up-first-keyword) )
2088 (assq first-symbol followers))
2089 (while (and
2090 (or (py-goto-beyond-block) t) ; side effect
2091 (forward-line -1) ; side effect
2092 (setq last-pos (point)) ; side effect
2093 (py-goto-statement-below)
2094 (= (current-indentation) initial-indent)
2095 (setq next-symbol (py-suck-up-first-keyword))
2096 (memq next-symbol (cdr (assq first-symbol followers))))
2097 (setq first-symbol next-symbol)))
2098
2099 ;; else if line *opens* a block, search for next stmt indented <=
2100 ((py-statement-opens-block-p)
2101 (while (and
2102 (setq last-pos (point)) ; always true -- side effect
2103 (py-goto-statement-below)
2104 (> (current-indentation) initial-indent))
2105 nil))
2106
2107 ;; else plain code line; stop at next blank line, or stmt or
2108 ;; indenting comment line indented <
2109 (t
2110 (while (and
2111 (setq last-pos (point)) ; always true -- side effect
2112 (or (py-goto-beyond-final-line) t)
2113 (not (looking-at "[ \t]*$")) ; stop at blank line
2114 (or
2115 (>= (current-indentation) initial-indent)
2116 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2117 nil)))
2118
2119 ;; skip to end of last stmt
2120 (goto-char last-pos)
2121 (py-goto-beyond-final-line)
2122
2123 ;; set mark & display
2124 (if just-move
2125 () ; just return
2126 (push-mark (point) 'no-msg)
2127 (forward-line -1)
2128 (message "Mark set after: %s" (py-suck-up-leading-text))
2129 (goto-char initial-pos))))
2130
Barry Warsaw2518c671997-11-05 00:51:08 +00002131(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002132 "Set region to body of def (or class, with prefix arg) enclosing point.
2133Pushes the current mark, then point, on the mark ring (all language
2134modes do this, but although it's handy it's never documented ...).
2135
2136In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002137hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2138`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002139
2140And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002141Turned out that was more confusing than useful: the `goto start' and
2142`goto end' commands are usually used to search through a file, and
2143people expect them to act a lot like `search backward' and `search
2144forward' string-search commands. But because Python `def' and `class'
2145can nest to arbitrary levels, finding the smallest def containing
2146point cannot be done via a simple backward search: the def containing
2147point may not be the closest preceding def, or even the closest
2148preceding def that's indented less. The fancy algorithm required is
2149appropriate for the usual uses of this `mark' command, but not for the
2150`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002152So the def marked by this command may not be the one either of the
2153`goto' commands find: If point is on a blank or non-indenting comment
2154line, moves back to start of the closest preceding code statement or
2155indenting comment line. If this is a `def' statement, that's the def
2156we use. Else searches for the smallest enclosing `def' block and uses
2157that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002158
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002159When an enclosing def is found: The mark is left immediately beyond
2160the last line of the def block. Point is left at the start of the
2161def, except that: if the def is preceded by a number of comment lines
2162followed by (at most) one optional blank line, point is left at the
2163start of the comments; else if the def is preceded by a blank line,
2164point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002165
2166The intent is to mark the containing def/class and its associated
2167documentation, to make moving and duplicating functions and classes
2168pleasant."
2169 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002170 (let ((start (point))
2171 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002172 (push-mark start)
2173 (if (not (py-go-up-tree-to-keyword which))
2174 (progn (goto-char start)
2175 (error "Enclosing %s not found" which))
2176 ;; else enclosing def/class found
2177 (setq start (point))
2178 (py-goto-beyond-block)
2179 (push-mark (point))
2180 (goto-char start)
2181 (if (zerop (forward-line -1)) ; if there is a preceding line
2182 (progn
2183 (if (looking-at "[ \t]*$") ; it's blank
2184 (setq start (point)) ; so reset start point
2185 (goto-char start)) ; else try again
2186 (if (zerop (forward-line -1))
2187 (if (looking-at "[ \t]*#") ; a comment
2188 ;; look back for non-comment line
2189 ;; tricky: note that the regexp matches a blank
2190 ;; line, cuz \n is in the 2nd character class
2191 (and
2192 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2193 (forward-line 1))
2194 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002195 (goto-char start)))))))
2196 (exchange-point-and-mark)
2197 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002198
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002199;; ripped from cc-mode
2200(defun py-forward-into-nomenclature (&optional arg)
2201 "Move forward to end of a nomenclature section or word.
2202With arg, to it arg times.
2203
2204A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2205 (interactive "p")
2206 (let ((case-fold-search nil))
2207 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002208 (re-search-forward
2209 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2210 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002211 (while (and (< arg 0)
2212 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002213 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002214 (point-min) 0))
2215 (forward-char 1)
2216 (setq arg (1+ arg)))))
2217 (py-keep-region-active))
2218
2219(defun py-backward-into-nomenclature (&optional arg)
2220 "Move backward to beginning of a nomenclature section or word.
2221With optional ARG, move that many times. If ARG is negative, move
2222forward.
2223
2224A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2225 (interactive "p")
2226 (py-forward-into-nomenclature (- arg))
2227 (py-keep-region-active))
2228
2229
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002230
2231;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002232
2233;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002234;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2235;; out of the right places, along with the keys they're on & current
2236;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002237(defun py-dump-help-string (str)
2238 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002239 (let ((locals (buffer-local-variables))
2240 funckind funcname func funcdoc
2241 (start 0) mstart end
2242 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002243 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2244 (setq mstart (match-beginning 0) end (match-end 0)
2245 funckind (substring str (match-beginning 1) (match-end 1))
2246 funcname (substring str (match-beginning 2) (match-end 2))
2247 func (intern funcname))
2248 (princ (substitute-command-keys (substring str start mstart)))
2249 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002250 ((equal funckind "c") ; command
2251 (setq funcdoc (documentation func)
2252 keys (concat
2253 "Key(s): "
2254 (mapconcat 'key-description
2255 (where-is-internal func py-mode-map)
2256 ", "))))
2257 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002258 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002259 keys (if (assq func locals)
2260 (concat
2261 "Local/Global values: "
2262 (prin1-to-string (symbol-value func))
2263 " / "
2264 (prin1-to-string (default-value func)))
2265 (concat
2266 "Value: "
2267 (prin1-to-string (symbol-value func))))))
2268 (t ; unexpected
2269 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002270 (princ (format "\n-> %s:\t%s\t%s\n\n"
2271 (if (equal funckind "c") "Command" "Variable")
2272 funcname keys))
2273 (princ funcdoc)
2274 (terpri)
2275 (setq start end))
2276 (princ (substitute-command-keys (substring str start))))
2277 (print-help-return-message)))
2278
2279(defun py-describe-mode ()
2280 "Dump long form of Python-mode docs."
2281 (interactive)
2282 (py-dump-help-string "Major mode for editing Python files.
2283Knows about Python indentation, tokens, comments and continuation lines.
2284Paragraphs are separated by blank lines only.
2285
2286Major sections below begin with the string `@'; specific function and
2287variable docs begin with `->'.
2288
2289@EXECUTING PYTHON CODE
2290
2291\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2292\\[py-execute-region]\tsends the current region
2293\\[py-shell]\tstarts a Python interpreter window; this will be used by
2294\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2295%c:py-execute-buffer
2296%c:py-execute-region
2297%c:py-shell
2298
2299@VARIABLES
2300
2301py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002302py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002303
2304py-python-command\tshell command to invoke Python interpreter
2305py-scroll-process-buffer\talways scroll Python process buffer
2306py-temp-directory\tdirectory used for temp files (if needed)
2307
2308py-beep-if-tab-change\tring the bell if tab-width is changed
2309%v:py-indent-offset
2310%v:py-block-comment-prefix
2311%v:py-python-command
2312%v:py-scroll-process-buffer
2313%v:py-temp-directory
2314%v:py-beep-if-tab-change
2315
2316@KINDS OF LINES
2317
2318Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002319preceding line ends with a backslash that's not part of a comment, or
2320the paren/bracket/brace nesting level at the start of the line is
2321non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322
2323An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002324possibly blanks or tabs), a `comment line' (leftmost non-blank
2325character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002326
2327Comment Lines
2328
2329Although all comment lines are treated alike by Python, Python mode
2330recognizes two kinds that act differently with respect to indentation.
2331
2332An `indenting comment line' is a comment line with a blank, tab or
2333nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002334treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002335indenting comment line will be indented like the comment line. All
2336other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002337following the initial `#') are `non-indenting comment lines', and
2338their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002339
2340Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002341whenever possible. Non-indenting comment lines are useful in cases
2342like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002343
2344\ta = b # a very wordy single-line comment that ends up being
2345\t #... continued onto another line
2346
2347\tif a == b:
2348##\t\tprint 'panic!' # old code we've `commented out'
2349\t\treturn a
2350
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002351Since the `#...' and `##' comment lines have a non-whitespace
2352character following the initial `#', Python mode ignores them when
2353computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002354
2355Continuation Lines and Statements
2356
2357The Python-mode commands generally work on statements instead of on
2358individual lines, where a `statement' is a comment or blank line, or a
2359code line and all of its following continuation lines (if any)
2360considered as a single logical unit. The commands in this mode
2361generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002362statement containing point, even if point happens to be in the middle
2363of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002364
2365
2366@INDENTATION
2367
2368Primarily for entering new code:
2369\t\\[indent-for-tab-command]\t indent line appropriately
2370\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002371\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002372
2373Primarily for reindenting existing code:
2374\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2375\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2376
2377\t\\[py-indent-region]\t reindent region to match its context
2378\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2379\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2380
2381Unlike most programming languages, Python uses indentation, and only
2382indentation, to specify block structure. Hence the indentation supplied
2383automatically by Python-mode is just an educated guess: only you know
2384the block structure you intend, so only you can supply correct
2385indentation.
2386
2387The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2388the indentation of preceding statements. E.g., assuming
2389py-indent-offset is 4, after you enter
2390\tif a > 0: \\[py-newline-and-indent]
2391the cursor will be moved to the position of the `_' (_ is not a
2392character in the file, it's just used here to indicate the location of
2393the cursor):
2394\tif a > 0:
2395\t _
2396If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2397to
2398\tif a > 0:
2399\t c = d
2400\t _
2401Python-mode cannot know whether that's what you intended, or whether
2402\tif a > 0:
2403\t c = d
2404\t_
2405was your intent. In general, Python-mode either reproduces the
2406indentation of the (closest code or indenting-comment) preceding
2407statement, or adds an extra py-indent-offset blanks if the preceding
2408statement has `:' as its last significant (non-whitespace and non-
2409comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002410\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002411
2412Continuation lines are given extra indentation. If you don't like the
2413suggested indentation, change it to something you do like, and Python-
2414mode will strive to indent later lines of the statement in the same way.
2415
2416If a line is a continuation line by virtue of being in an unclosed
2417paren/bracket/brace structure (`list', for short), the suggested
2418indentation depends on whether the current line contains the first item
2419in the list. If it does, it's indented py-indent-offset columns beyond
2420the indentation of the line containing the open bracket. If you don't
2421like that, change it by hand. The remaining items in the list will mimic
2422whatever indentation you give to the first item.
2423
2424If a line is a continuation line because the line preceding it ends with
2425a backslash, the third and following lines of the statement inherit their
2426indentation from the line preceding them. The indentation of the second
2427line in the statement depends on the form of the first (base) line: if
2428the base line is an assignment statement with anything more interesting
2429than the backslash following the leftmost assigning `=', the second line
2430is indented two columns beyond that `='. Else it's indented to two
2431columns beyond the leftmost solid chunk of non-whitespace characters on
2432the base line.
2433
2434Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2435repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2436structure you intend.
2437%c:indent-for-tab-command
2438%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002439%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002440
2441
2442The next function may be handy when editing code you didn't write:
2443%c:py-guess-indent-offset
2444
2445
2446The remaining `indent' functions apply to a region of Python code. They
2447assume the block structure (equals indentation, in Python) of the region
2448is correct, and alter the indentation in various ways while preserving
2449the block structure:
2450%c:py-indent-region
2451%c:py-shift-region-left
2452%c:py-shift-region-right
2453
2454@MARKING & MANIPULATING REGIONS OF CODE
2455
2456\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002457\\[py-mark-def-or-class]\t mark smallest enclosing def
2458\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002459\\[comment-region]\t comment out region of code
2460\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002461%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002462%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002463%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002464
2465@MOVING POINT
2466
2467\\[py-previous-statement]\t move to statement preceding point
2468\\[py-next-statement]\t move to statement following point
2469\\[py-goto-block-up]\t move up to start of current block
2470\\[beginning-of-python-def-or-class]\t move to start of def
2471\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2472\\[end-of-python-def-or-class]\t move to end of def
2473\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2474
2475The first two move to one statement beyond the statement that contains
2476point. A numeric prefix argument tells them to move that many
2477statements instead. Blank lines, comment lines, and continuation lines
2478do not count as `statements' for these commands. So, e.g., you can go
2479to the first code statement in a file by entering
2480\t\\[beginning-of-buffer]\t to move to the top of the file
2481\t\\[py-next-statement]\t to skip over initial comments and blank lines
2482Or do `\\[py-previous-statement]' with a huge prefix argument.
2483%c:py-previous-statement
2484%c:py-next-statement
2485%c:py-goto-block-up
2486%c:beginning-of-python-def-or-class
2487%c:end-of-python-def-or-class
2488
2489@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2490
2491`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2492
2493`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2494overall class and def structure of a module.
2495
2496`\\[back-to-indentation]' moves point to a line's first non-blank character.
2497
2498`\\[indent-relative]' is handy for creating odd indentation.
2499
2500@OTHER EMACS HINTS
2501
2502If you don't like the default value of a variable, change its value to
2503whatever you do like by putting a `setq' line in your .emacs file.
2504E.g., to set the indentation increment to 4, put this line in your
2505.emacs:
2506\t(setq py-indent-offset 4)
2507To see the value of a variable, do `\\[describe-variable]' and enter the variable
2508name at the prompt.
2509
2510When entering a key sequence like `C-c C-n', it is not necessary to
2511release the CONTROL key after doing the `C-c' part -- it suffices to
2512press the CONTROL key, press and release `c' (while still holding down
2513CONTROL), press and release `n' (while still holding down CONTROL), &
2514then release CONTROL.
2515
2516Entering Python mode calls with no arguments the value of the variable
2517`python-mode-hook', if that value exists and is not nil; for backward
2518compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2519the Elisp manual for details.
2520
2521Obscure: When python-mode is first loaded, it looks for all bindings
2522to newline-and-indent in the global keymap, and shadows them with
2523local bindings to py-newline-and-indent."))
2524
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002525
2526;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002527(defvar py-parse-state-re
2528 (concat
2529 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2530 "\\|"
2531 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002532
Barry Warsaw7ae77681994-12-12 20:38:05 +00002533;; returns the parse state at point (see parse-partial-sexp docs)
2534(defun py-parse-state ()
2535 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002536 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002537 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002538 (while (not done)
2539 ;; back up to the first preceding line (if any; else start of
2540 ;; buffer) that begins with a popular Python keyword, or a
2541 ;; non- whitespace and non-comment character. These are good
2542 ;; places to start parsing to see whether where we started is
2543 ;; at a non-zero nesting level. It may be slow for people who
2544 ;; write huge code blocks or huge lists ... tough beans.
2545 (re-search-backward py-parse-state-re nil 'move)
2546 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002547 ;; In XEmacs, we have a much better way to test for whether
2548 ;; we're in a triple-quoted string or not. Emacs does not
2549 ;; have this built-in function, which is it's loss because
2550 ;; without scanning from the beginning of the buffer, there's
2551 ;; no accurate way to determine this otherwise.
2552 (if (not (fboundp 'buffer-syntactic-context))
2553 ;; Emacs
2554 (save-excursion
2555 (setq pps (parse-partial-sexp (point) here))
2556 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002557 (setq done (or (not (nth 3 pps))
2558 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002559 ;; XEmacs
2560 (setq done (or (not (buffer-syntactic-context))
2561 (bobp)))
2562 (when done
2563 (setq pps (parse-partial-sexp (point) here)))
2564 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002565 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002566
2567;; if point is at a non-zero nesting level, returns the number of the
2568;; character that opens the smallest enclosing unclosed list; else
2569;; returns nil.
2570(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002571 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002572 (if (zerop (car status))
2573 nil ; not in a nest
2574 (car (cdr status))))) ; char# of open bracket
2575
2576;; t iff preceding line ends with backslash that's not in a comment
2577(defun py-backslash-continuation-line-p ()
2578 (save-excursion
2579 (beginning-of-line)
2580 (and
2581 ;; use a cheap test first to avoid the regexp if possible
2582 ;; use 'eq' because char-after may return nil
2583 (eq (char-after (- (point) 2)) ?\\ )
2584 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002585 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002586 (looking-at py-continued-re))))
2587
2588;; t iff current line is a continuation line
2589(defun py-continuation-line-p ()
2590 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002591 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002592 (or (py-backslash-continuation-line-p)
2593 (py-nesting-level))))
2594
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002595;; go to initial line of current statement; usually this is the line
2596;; we're on, but if we're on the 2nd or following lines of a
2597;; continuation block, we need to go up to the first line of the
2598;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002599;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002600;; Tricky: We want to avoid quadratic-time behavior for long continued
2601;; blocks, whether of the backslash or open-bracket varieties, or a
2602;; mix of the two. The following manages to do that in the usual
2603;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002604;;
2605;; Also, if we're sitting inside a triple quoted string, this will
2606;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002607(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002608 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002609 (while (py-continuation-line-p)
2610 (beginning-of-line)
2611 (if (py-backslash-continuation-line-p)
2612 (while (py-backslash-continuation-line-p)
2613 (forward-line -1))
2614 ;; else zip out of nested brackets/braces/parens
2615 (while (setq open-bracket-pos (py-nesting-level))
2616 (goto-char open-bracket-pos)))))
2617 (beginning-of-line))
2618
2619;; go to point right beyond final line of current statement; usually
2620;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002621;; statement we need to skip over the continuation lines. Tricky:
2622;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002623(defun py-goto-beyond-final-line ()
2624 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002625 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002626 (while (and (py-continuation-line-p)
2627 (not (eobp)))
2628 ;; skip over the backslash flavor
2629 (while (and (py-backslash-continuation-line-p)
2630 (not (eobp)))
2631 (forward-line 1))
2632 ;; if in nest, zip to the end of the nest
2633 (setq state (py-parse-state))
2634 (if (and (not (zerop (car state)))
2635 (not (eobp)))
2636 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002637 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002638 (forward-line 1))))))
2639
2640;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002641;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002642(defun py-statement-opens-block-p ()
2643 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002644 (let ((start (point))
2645 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2646 (searching t)
2647 (answer nil)
2648 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002649 (goto-char start)
2650 (while searching
2651 ;; look for a colon with nothing after it except whitespace, and
2652 ;; maybe a comment
2653 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2654 finish t)
2655 (if (eq (point) finish) ; note: no `else' clause; just
2656 ; keep searching if we're not at
2657 ; the end yet
2658 ;; sure looks like it opens a block -- but it might
2659 ;; be in a comment
2660 (progn
2661 (setq searching nil) ; search is done either way
2662 (setq state (parse-partial-sexp start
2663 (match-beginning 0)))
2664 (setq answer (not (nth 4 state)))))
2665 ;; search failed: couldn't find another interesting colon
2666 (setq searching nil)))
2667 answer)))
2668
Barry Warsawf831d811996-07-31 20:42:59 +00002669(defun py-statement-closes-block-p ()
2670 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002671 ;; starts with `return', `raise', `break', `continue', and `pass'.
2672 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002673 (let ((here (point)))
2674 (back-to-indentation)
2675 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002676 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002677 (goto-char here))))
2678
Barry Warsaw7ae77681994-12-12 20:38:05 +00002679;; go to point right beyond final line of block begun by the current
2680;; line. This is the same as where py-goto-beyond-final-line goes
2681;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002682;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002683(defun py-goto-beyond-block ()
2684 (if (py-statement-opens-block-p)
2685 (py-mark-block nil 'just-move)
2686 (py-goto-beyond-final-line)))
2687
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002688;; go to start of first statement (not blank or comment or
2689;; continuation line) at or preceding point. returns t if there is
2690;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002691(defun py-goto-statement-at-or-above ()
2692 (py-goto-initial-line)
2693 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002694 ;; skip back over blank & comment lines
2695 ;; note: will skip a blank or comment line that happens to be
2696 ;; a continuation line too
2697 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2698 (progn (py-goto-initial-line) t)
2699 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002700 t))
2701
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002702;; go to start of first statement (not blank or comment or
2703;; continuation line) following the statement containing point returns
2704;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002705(defun py-goto-statement-below ()
2706 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002707 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002708 (py-goto-beyond-final-line)
2709 (while (and
2710 (looking-at py-blank-or-comment-re)
2711 (not (eobp)))
2712 (forward-line 1))
2713 (if (eobp)
2714 (progn (goto-char start) nil)
2715 t)))
2716
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002717;; go to start of statement, at or preceding point, starting with
2718;; keyword KEY. Skips blank lines and non-indenting comments upward
2719;; first. If that statement starts with KEY, done, else go back to
2720;; first enclosing block starting with KEY. If successful, leaves
2721;; point at the start of the KEY line & returns t. Else leaves point
2722;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002723(defun py-go-up-tree-to-keyword (key)
2724 ;; skip blanks and non-indenting #
2725 (py-goto-initial-line)
2726 (while (and
2727 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2728 (zerop (forward-line -1))) ; go back
2729 nil)
2730 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002731 (let* ((re (concat "[ \t]*" key "\\b"))
2732 (case-fold-search nil) ; let* so looking-at sees this
2733 (found (looking-at re))
2734 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002735 (while (not (or found dead))
2736 (condition-case nil ; in case no enclosing block
2737 (py-goto-block-up 'no-mark)
2738 (error (setq dead t)))
2739 (or dead (setq found (looking-at re))))
2740 (beginning-of-line)
2741 found))
2742
2743;; return string in buffer from start of indentation to end of line;
2744;; prefix "..." if leading whitespace was skipped
2745(defun py-suck-up-leading-text ()
2746 (save-excursion
2747 (back-to-indentation)
2748 (concat
2749 (if (bolp) "" "...")
2750 (buffer-substring (point) (progn (end-of-line) (point))))))
2751
2752;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2753;; as a Lisp symbol; return nil if none
2754(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002755 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002756 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2757 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2758 nil)))
2759
Barry Warsawb3e81d51996-09-04 15:12:42 +00002760(defun py-current-defun ()
2761 ;; tell add-log.el how to find the current function/method/variable
2762 (save-excursion
2763 (if (re-search-backward py-defun-start-re nil t)
2764 (or (match-string 3)
2765 (let ((method (match-string 2)))
2766 (if (and (not (zerop (length (match-string 1))))
2767 (re-search-backward py-class-start-re nil t))
2768 (concat (match-string 1) "." method)
2769 method)))
2770 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002771
2772
Barry Warsawfec75d61995-07-05 23:26:15 +00002773(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002774 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002775
Barry Warsaw850437a1995-03-08 21:50:28 +00002776(defun py-version ()
2777 "Echo the current version of `python-mode' in the minibuffer."
2778 (interactive)
2779 (message "Using `python-mode' version %s" py-version)
2780 (py-keep-region-active))
2781
2782;; only works under Emacs 19
2783;(eval-when-compile
2784; (require 'reporter))
2785
2786(defun py-submit-bug-report (enhancement-p)
2787 "Submit via mail a bug report on `python-mode'.
2788With \\[universal-argument] just submit an enhancement request."
2789 (interactive
2790 (list (not (y-or-n-p
2791 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002792 (let ((reporter-prompt-for-summary-p (if enhancement-p
2793 "(Very) brief summary: "
2794 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002795 (require 'reporter)
2796 (reporter-submit-bug-report
2797 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002798 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002799 ;; varlist
2800 (if enhancement-p nil
2801 '(py-python-command
2802 py-indent-offset
2803 py-block-comment-prefix
2804 py-scroll-process-buffer
2805 py-temp-directory
2806 py-beep-if-tab-change))
2807 nil ;pre-hooks
2808 nil ;post-hooks
2809 "Dear Barry,") ;salutation
2810 (if enhancement-p nil
2811 (set-mark (point))
2812 (insert
2813"Please replace this text with a sufficiently large code sample\n\
2814and an exact recipe so that I can reproduce your problem. Failure\n\
2815to do so may mean a greater delay in fixing your bug.\n\n")
2816 (exchange-point-and-mark)
2817 (py-keep-region-active))))
2818
2819
Barry Warsaw47384781997-11-26 05:27:45 +00002820(defun py-kill-emacs-hook ()
2821 (mapcar #'(lambda (filename)
2822 (py-safe (delete-file filename)))
2823 py-file-queue))
2824
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002825;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002826(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002827
2828
2829
2830(provide 'python-mode)
2831;;; python-mode.el ends here