blob: 3ea1f3b15b3919be3b7928cef886989ef32c7c31 [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 Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 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 Warsawaffc0ca1997-11-03 16:59:38 +000027;; Note: this version of python-mode.el is no longer compatible with
28;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
29;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
Barry Warsawa0ee8cd1997-11-26 01:04:44 +000030;; you may need to acquire the Custom library. Please see
31;; <http://www.python.org/ftp/emacs/> for details.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
Barry Warsaw673d05f1997-12-02 21:51:57 +000033;; You will want to byte-compile this file.
34
Barry Warsawaffc0ca1997-11-03 16:59:38 +000035;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
36;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000037;; but it is compatible with 19.34 and the current 20 series Emacsen.
38;; By default, in XEmacs when you visit a .py file, it is put in
39;; Python mode. In Emacs, you need to add the following to your
40;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000041;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000042;; (autoload 'python-mode "python-mode" "Python editing mode." t)
43;; (setq auto-mode-alist
44;; (cons '("\\.py$" . python-mode) auto-mode-alist))
45;; (setq interpreter-mode-alist
46;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000047;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000048;; Assuming python-mode.el is on your load-path, it will be invoked
49;; when you visit a .py file, or a file with a first line that looks
50;; like:
51;;
52;; #! /usr/bin/env python
53
Barry Warsaw44b72201996-07-05 20:11:35 +000054;; If you want font-lock support for Python source code (a.k.a. syntax
55;; coloring, highlighting), add this to your .emacs file:
56;;
57;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000058;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000059;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000060
Barry Warsawaffc0ca1997-11-03 16:59:38 +000061;; To submit bug reports, use C-c C-b. Please include a complete, but
62;; concise code sample and a recipe for reproducing the bug. Send
63;; suggestions and other comments to python-mode@python.org.
64
65;; When in a Python mode buffer, do a C-h m for more help. It's
66;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000067
Barry Warsaw7b0f5681995-03-08 21:33:04 +000068;; Here's a brief to do list:
69;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000070;; - Better integration with gud-mode for debugging.
71;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000072;; - possibly force indent-tabs-mode == nil, and add a
73;; write-file-hooks that runs untabify on the whole buffer (to work
74;; around potential tab/space mismatch problems). In practice this
75;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000076;; - have py-execute-region on indented code act as if the region is
77;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000078;; - Add a py-goto-error or some such that would scan an exception in
79;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
Barry Warsaw7b0f5681995-03-08 21:33:04 +000081;;; Code:
82
Barry Warsawc72c11c1997-08-09 06:42:08 +000083(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +000084(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +000085 (require 'cl)
86 (require 'custom)
87 ;; Stock Emacs 19.34 has a broken/old Custom library that does more
88 ;; harm than good
89 (or (fboundp 'defcustom)
90 (error "STOP! STOP! STOP! STOP!
91
92The Custom library was not found or is out of date. A more current
93version is required. Please download and install the latest version
94of the Custom library from:
95
96 <http://www.dina.kvl.dk/~abraham/custom/>
97
98See the Python Mode home page for details:
99
100 <http://www.python.org/ftp/emacs/>
101")))
102
Barry Warsawc72c11c1997-08-09 06:42:08 +0000103
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000104
105;; user definable variables
106;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(defgroup python nil
109 "Support for the Python programming language, <http://www.python.org/>"
110 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000111
Barry Warsawc72c11c1997-08-09 06:42:08 +0000112(defcustom py-python-command "python"
113 "*Shell command used to start Python interpreter."
114 :type 'string
115 :group 'python)
116
117(defcustom py-indent-offset 4
118 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000119Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120when you're editing someone else's Python code."
121 :type 'integer
122 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000123
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124(defcustom py-align-multiline-strings-p t
125 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000126When this flag is non-nil, continuation lines are lined up under the
127preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000128lines are aligned to column zero."
129 :type '(choice (const :tag "Align under preceding line" t)
130 (const :tag "Align to column zero" nil))
131 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000132
Barry Warsawc72c11c1997-08-09 06:42:08 +0000133(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000134 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135This should follow the convention for non-indenting comment lines so
136that the indentation commands won't get confused (i.e., the string
137should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000138`...' is arbitrary)."
139 :type 'string
140 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000141
Barry Warsawc72c11c1997-08-09 06:42:08 +0000142(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000143 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000144
Barry Warsaw6d627751996-03-06 18:41:38 +0000145When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000146if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000147
148When t, lines that begin with a single `#' are a hint to subsequent
149line indentation. If the previous line is such a comment line (as
150opposed to one that starts with `py-block-comment-prefix'), then it's
151indentation is used as a hint for this line's indentation. Lines that
152begin with `py-block-comment-prefix' are ignored for indentation
153purposes.
154
155When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000156indentation hints, unless the comment character is in column zero."
157 :type '(choice
158 (const :tag "Skip all comment lines (fast)" nil)
159 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000160 (const :tag "Single # `sets' indentation except at column zero"
161 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000162 )
163 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000164
Barry Warsawc72c11c1997-08-09 06:42:08 +0000165(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166 "*Scroll Python process buffer as output arrives.
167If nil, the Python process buffer acts, with respect to scrolling, like
168Shell-mode buffers normally act. This is surprisingly complicated and
169so won't be explained here; in fact, you can't get the whole story
170without studying the Emacs C code.
171
172If non-nil, the behavior is different in two respects (which are
173slightly inaccurate in the interest of brevity):
174
175 - If the buffer is in a window, and you left point at its end, the
176 window will scroll as new output arrives, and point will move to the
177 buffer's end, even if the window is not the selected window (that
178 being the one the cursor is in). The usual behavior for shell-mode
179 windows is not to scroll, and to leave point where it was, if the
180 buffer is in a window other than the selected window.
181
182 - If the buffer is not visible in any window, and you left point at
183 its end, the buffer will be popped into a window as soon as more
184 output arrives. This is handy if you have a long-running
185 computation and don't want to tie up screen area waiting for the
186 output. The usual behavior for a shell-mode buffer is to stay
187 invisible until you explicitly visit it.
188
189Note the `and if you left point at its end' clauses in both of the
190above: you can `turn off' the special behaviors while output is in
191progress, by visiting the Python buffer and moving point to anywhere
192besides the end. Then the buffer won't scroll, point will remain where
193you leave it, and if you hide the buffer it will stay hidden until you
194visit it again. You can enable and disable the special behaviors as
195often as you like, while output is in progress, by (respectively) moving
196point to, or away from, the end of the buffer.
197
198Warning: If you expect a large amount of output, you'll probably be
199happier setting this option to nil.
200
201Obscure: `End of buffer' above should really say `at or beyond the
202process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000203told <grin>."
204 :type 'boolean
205 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000206
Barry Warsaw516b6201997-08-09 06:43:20 +0000207(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000208 (let ((ok '(lambda (x)
209 (and x
210 (setq x (expand-file-name x)) ; always true
211 (file-directory-p x)
212 (file-writable-p x)
213 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000214 (or (funcall ok (getenv "TMPDIR"))
215 (funcall ok "/usr/tmp")
216 (funcall ok "/tmp")
217 (funcall ok ".")
218 (error
219 "Couldn't find a usable temp directory -- set py-temp-directory")))
220 "*Directory used for temp files created by a *Python* process.
221By default, the first directory from this list that exists and that you
222can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000223/usr/tmp, /tmp, or the current directory."
224 :type 'string
225 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000226
Barry Warsaw516b6201997-08-09 06:43:20 +0000227(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000228 "*Ring the bell if tab-width is changed.
229If a comment of the form
230
231 \t# vi:set tabsize=<number>:
232
233is found before the first code line when the file is entered, and the
234current value of (the general Emacs variable) `tab-width' does not
235equal <number>, `tab-width' is set to <number>, a message saying so is
236displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000237the Emacs bell is also rung as a warning."
238 :type 'boolean
239 :group 'python)
240
Barry Warsaw9981d221997-12-03 05:25:48 +0000241(defcustom py-jump-on-exception t
242 "*Jump to innermost exception frame in *Python Output* buffer.
243When this variable is non-nil and ane exception occurs when running
244Python code synchronously in a subprocess, jump immediately to the
245source code of the innermost frame.")
246
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000247(defcustom py-backspace-function 'backward-delete-char-untabify
248 "*Function called by `py-electric-backspace' when deleting backwards."
249 :type 'function
250 :group 'python)
251
252(defcustom py-delete-function 'delete-char
253 "*Function called by `py-electric-delete' when deleting forwards."
254 :type 'function
255 :group 'python)
256
257
Barry Warsawc72c11c1997-08-09 06:42:08 +0000258
259;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
260;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
261
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000262(defconst py-emacs-features
263 (let (features)
264 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
265 ;; the same string.
266 (let ((tmp1 (make-temp-name ""))
267 (tmp2 (make-temp-name "")))
268 (if (string-equal tmp1 tmp2)
269 (push 'broken-temp-names features)))
270 ;; return the features
271 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000272 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000273There are many flavors of Emacs out there, with different levels of
274support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000275
Barry Warsawfb07f401997-02-24 03:37:22 +0000276(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000277 (let ((kw1 (mapconcat 'identity
278 '("and" "assert" "break" "class"
279 "continue" "def" "del" "elif"
280 "else" "except" "exec" "for"
281 "from" "global" "if" "import"
282 "in" "is" "lambda" "not"
283 "or" "pass" "print" "raise"
284 "return" "while"
285 )
286 "\\|"))
287 (kw2 (mapconcat 'identity
288 '("else:" "except:" "finally:" "try:")
289 "\\|"))
290 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000291 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000292 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000293 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
294 ;; block introducing keywords with immediately following colons.
295 ;; Yes "except" is in both lists.
296 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000297 ;; classes
298 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
299 1 font-lock-type-face)
300 ;; functions
301 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
302 1 font-lock-function-name-face)
303 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000304 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000305(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
306
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000307
Barry Warsaw81437461996-08-01 19:48:02 +0000308(defvar imenu-example--python-show-method-args-p nil
309 "*Controls echoing of arguments of functions & methods in the imenu buffer.
310When non-nil, arguments are printed.")
311
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000312(make-variable-buffer-local 'py-indent-offset)
313
Barry Warsawe467bfb1997-11-26 05:40:58 +0000314;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315(defvar py-file-queue nil
316 "Queue of Python temp files awaiting execution.
317Currently-active file is at the head of the list.")
318
Barry Warsawc72c11c1997-08-09 06:42:08 +0000319
320;; Constants
321
322;; Regexp matching a Python string literal
323(defconst py-stringlit-re
324 (concat
325 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
326 "\\|" ; or
327 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
328
329;; Regexp matching Python lines that are continued via backslash.
330;; This is tricky because a trailing backslash does not mean
331;; continuation if it's in a comment
332(defconst py-continued-re
333 (concat
334 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
335 "\\\\$"))
336
337;; Regexp matching blank or comment lines.
338(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
339
340;; Regexp matching clauses to be outdented one level.
341(defconst py-outdent-re
342 (concat "\\(" (mapconcat 'identity
343 '("else:"
344 "except\\(\\s +.*\\)?:"
345 "finally:"
346 "elif\\s +.*:")
347 "\\|")
348 "\\)"))
349
350
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000351;; Regexp matching keywords which typically close a block
352(defconst py-block-closing-keywords-re
353 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
354
Barry Warsawc72c11c1997-08-09 06:42:08 +0000355;; Regexp matching lines to not outdent after.
356(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000357 (concat
358 "\\("
359 (mapconcat 'identity
360 (list "try:"
361 "except\\(\\s +.*\\)?:"
362 "while\\s +.*:"
363 "for\\s +.*:"
364 "if\\s +.*:"
365 "elif\\s +.*:"
366 (concat py-block-closing-keywords-re "[ \t\n]")
367 )
368 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000369 "\\)"))
370
371;; Regexp matching a function, method or variable assignment. If you
372;; change this, you probably have to change `py-current-defun' as
373;; well. This is only used by `py-current-defun' to find the name for
374;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000375(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000376 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
377
378;; Regexp for finding a class name. If you change this, you probably
379;; have to change `py-current-defun' as well. This is only used by
380;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000381(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
382
383;; Regexp that describes tracebacks
384(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000385 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000386
387
388
389;; Utilities
390
391(defmacro py-safe (&rest body)
392 ;; safely execute BODY, return nil if an error occurred
393 (` (condition-case nil
394 (progn (,@ body))
395 (error nil))))
396
397(defsubst py-keep-region-active ()
398 ;; Do whatever is necessary to keep the region active in XEmacs.
399 ;; Ignore byte-compiler warnings you might see. Also note that
400 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
401 ;; to take explicit action.
402 (and (boundp 'zmacs-region-stays)
403 (setq zmacs-region-stays t)))
404
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000405(defsubst py-point (position)
406 ;; Returns the value of point at certain commonly referenced POSITIONs.
407 ;; POSITION can be one of the following symbols:
408 ;;
409 ;; bol -- beginning of line
410 ;; eol -- end of line
411 ;; bod -- beginning of defun
412 ;; boi -- back to indentation
413 ;;
414 ;; This function does not modify point or mark.
415 (let ((here (point)))
416 (cond
417 ((eq position 'bol) (beginning-of-line))
418 ((eq position 'eol) (end-of-line))
419 ((eq position 'bod) (beginning-of-python-def-or-class))
420 ((eq position 'bob) (beginning-of-buffer))
421 ((eq position 'eob) (end-of-buffer))
422 ((eq position 'boi) (back-to-indentation))
423 (t (error "unknown buffer position requested: %s" position))
424 )
425 (prog1
426 (point)
427 (goto-char here))))
428
429(defsubst py-highlight-line (from to file line)
430 (cond
431 ((fboundp 'make-extent)
432 ;; XEmacs
433 (let ((e (make-extent from to)))
434 (set-extent-property e 'mouse-face 'highlight)
435 (set-extent-property e 'py-exc-info (cons file line))
436 (set-extent-property e 'keymap py-mode-output-map)))
437 (t
438 ;; Emacs -- Please port this!
439 )
440 ))
441
Barry Warsawc72c11c1997-08-09 06:42:08 +0000442
443;; Major mode boilerplate
444
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445;; define a mode-specific abbrev table for those who use such things
446(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000447 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000448(define-abbrev-table 'python-mode-abbrev-table nil)
449
Barry Warsaw7ae77681994-12-12 20:38:05 +0000450(defvar python-mode-hook nil
451 "*Hook called by `python-mode'.")
452
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453;; in previous version of python-mode.el, the hook was incorrectly
454;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000455(and (fboundp 'make-obsolete-variable)
456 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
457
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000458(defvar py-mode-map ()
459 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000460(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000461 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000462 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000463 ;; electric keys
464 (define-key py-mode-map ":" 'py-electric-colon)
465 ;; indentation level modifiers
466 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
467 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
468 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
469 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
470 ;; subprocess commands
471 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
472 (define-key py-mode-map "\C-c|" 'py-execute-region)
473 (define-key py-mode-map "\C-c!" 'py-shell)
474 ;; Caution! Enter here at your own risk. We are trying to support
475 ;; several behaviors and it gets disgusting. :-( This logic ripped
476 ;; largely from CC Mode.
477 ;;
478 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
479 ;; backwards deletion behavior to DEL, which both Delete and
480 ;; Backspace get translated to. There's no way to separate this
481 ;; behavior in a clean way, so deal with it! Besides, it's been
482 ;; this way since the dawn of time.
483 (if (not (boundp 'delete-key-deletes-forward))
484 (define-key py-mode-map "\177" 'py-electric-backspace)
485 ;; However, XEmacs 20 actually achieved enlightenment. It is
486 ;; possible to sanely define both backward and forward deletion
487 ;; behavior under X separately (TTYs are forever beyond hope, but
488 ;; who cares? XEmacs 20 does the right thing with these too).
489 (define-key py-mode-map [delete] 'py-electric-delete)
490 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000491 ;; Separate M-BS from C-M-h. The former should remain
492 ;; backward-kill-word.
493 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000494 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000495 ;; Miscellaneous
496 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
497 (define-key py-mode-map "\C-c\t" 'py-indent-region)
498 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
499 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
500 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000501 (define-key py-mode-map "\C-c#" 'py-comment-region)
502 (define-key py-mode-map "\C-c?" 'py-describe-mode)
503 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
504 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
505 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000506 (define-key py-mode-map "\C-c-" 'py-up-exception)
507 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000508 ;; information
509 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
510 (define-key py-mode-map "\C-c\C-v" 'py-version)
511 ;; py-newline-and-indent mappings
512 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000513 ;; shadow global bindings for newline-and-indent w/ the py- version.
514 ;; BAW - this is extremely bad form, but I'm not going to change it
515 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000516 (mapcar #'(lambda (key)
517 (define-key py-mode-map key 'py-newline-and-indent))
518 (where-is-internal 'newline-and-indent))
519 )
520
521(defvar py-mode-output-map nil
522 "Keymap used in *Python Output* buffers*")
523(if py-mode-output-map
524 nil
525 (setq py-mode-output-map (make-sparse-keymap))
526 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
527 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
528 ;; TBD: Disable all self-inserting keys. This is bogus, we should
529 ;; really implement this as *Python Output* buffer being read-only
530 (mapcar #' (lambda (key)
531 (define-key py-mode-output-map key
532 #'(lambda () (interactive) (beep))))
533 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000534 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000535
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000536(defvar py-mode-syntax-table nil
537 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000538(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000539 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000540 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000541 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
542 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
543 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
544 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
545 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
546 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
547 ;; Add operator symbols misassigned in the std table
548 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
549 (modify-syntax-entry ?\% "." py-mode-syntax-table)
550 (modify-syntax-entry ?\& "." py-mode-syntax-table)
551 (modify-syntax-entry ?\* "." py-mode-syntax-table)
552 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
553 (modify-syntax-entry ?\- "." py-mode-syntax-table)
554 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
555 (modify-syntax-entry ?\< "." py-mode-syntax-table)
556 (modify-syntax-entry ?\= "." py-mode-syntax-table)
557 (modify-syntax-entry ?\> "." py-mode-syntax-table)
558 (modify-syntax-entry ?\| "." py-mode-syntax-table)
559 ;; For historical reasons, underscore is word class instead of
560 ;; symbol class. GNU conventions say it should be symbol class, but
561 ;; there's a natural conflict between what major mode authors want
562 ;; and what users expect from `forward-word' and `backward-word'.
563 ;; Guido and I have hashed this out and have decided to keep
564 ;; underscore in word class. If you're tempted to change it, try
565 ;; binding M-f and M-b to py-forward-into-nomenclature and
566 ;; py-backward-into-nomenclature instead.
567 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
568 ;; Both single quote and double quote are string delimiters
569 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
570 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
571 ;; backquote is open and close paren
572 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
573 ;; comment delimiters
574 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
575 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
576 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000577
Barry Warsawb3e81d51996-09-04 15:12:42 +0000578
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000579
Barry Warsaw42f707f1996-07-29 21:05:05 +0000580;; Menu definitions, only relevent if you have the easymenu.el package
581;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000582(defvar py-menu nil
583 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000584This menu will get created automatically if you have the `easymenu'
585package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000586
Barry Warsawc72c11c1997-08-09 06:42:08 +0000587(and (py-safe (require 'easymenu) t)
588 (easy-menu-define
589 py-menu py-mode-map "Python Mode menu"
590 '("Python"
591 ["Comment Out Region" py-comment-region (mark)]
592 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
593 "-"
594 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000595 ["Mark current def" py-mark-def-or-class t]
596 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000597 "-"
598 ["Shift region left" py-shift-region-left (mark)]
599 ["Shift region right" py-shift-region-right (mark)]
600 "-"
601 ["Execute buffer" py-execute-buffer t]
602 ["Execute region" py-execute-region (mark)]
603 ["Start interpreter..." py-shell t]
604 "-"
605 ["Go to start of block" py-goto-block-up t]
606 ["Go to start of class" (beginning-of-python-def-or-class t) t]
607 ["Move to end of class" (end-of-python-def-or-class t) t]
608 ["Move to start of def" beginning-of-python-def-or-class t]
609 ["Move to end of def" end-of-python-def-or-class t]
610 "-"
611 ["Describe mode" py-describe-mode t]
612 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000613
Barry Warsaw81437461996-08-01 19:48:02 +0000614
615
616;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
617(defvar imenu-example--python-class-regexp
618 (concat ; <<classes>>
619 "\\(" ;
620 "^[ \t]*" ; newline and maybe whitespace
621 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
622 ; possibly multiple superclasses
623 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
624 "[ \t]*:" ; and the final :
625 "\\)" ; >>classes<<
626 )
627 "Regexp for Python classes for use with the imenu package."
628 )
629
630(defvar imenu-example--python-method-regexp
631 (concat ; <<methods and functions>>
632 "\\(" ;
633 "^[ \t]*" ; new line and maybe whitespace
634 "\\(def[ \t]+" ; function definitions start with def
635 "\\([a-zA-Z0-9_]+\\)" ; name is here
636 ; function arguments...
637 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
638 "\\)" ; end of def
639 "[ \t]*:" ; and then the :
640 "\\)" ; >>methods and functions<<
641 )
642 "Regexp for Python methods/functions for use with the imenu package."
643 )
644
645(defvar imenu-example--python-method-no-arg-parens '(2 8)
646 "Indicies into groups of the Python regexp for use with imenu.
647
648Using these values will result in smaller imenu lists, as arguments to
649functions are not listed.
650
651See the variable `imenu-example--python-show-method-args-p' for more
652information.")
653
654(defvar imenu-example--python-method-arg-parens '(2 7)
655 "Indicies into groups of the Python regexp for use with imenu.
656Using these values will result in large imenu lists, as arguments to
657functions are listed.
658
659See the variable `imenu-example--python-show-method-args-p' for more
660information.")
661
662;; Note that in this format, this variable can still be used with the
663;; imenu--generic-function. Otherwise, there is no real reason to have
664;; it.
665(defvar imenu-example--generic-python-expression
666 (cons
667 (concat
668 imenu-example--python-class-regexp
669 "\\|" ; or...
670 imenu-example--python-method-regexp
671 )
672 imenu-example--python-method-no-arg-parens)
673 "Generic Python expression which may be used directly with imenu.
674Used by setting the variable `imenu-generic-expression' to this value.
675Also, see the function \\[imenu-example--create-python-index] for a
676better alternative for finding the index.")
677
678;; These next two variables are used when searching for the python
679;; class/definitions. Just saving some time in accessing the
680;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000681(defvar imenu-example--python-generic-regexp nil)
682(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000683
684
Barry Warsaw81437461996-08-01 19:48:02 +0000685(defun imenu-example--create-python-index ()
686 "Python interface function for imenu package.
687Finds all python classes and functions/methods. Calls function
688\\[imenu-example--create-python-index-engine]. See that function for
689the details of how this works."
690 (setq imenu-example--python-generic-regexp
691 (car imenu-example--generic-python-expression))
692 (setq imenu-example--python-generic-parens
693 (if imenu-example--python-show-method-args-p
694 imenu-example--python-method-arg-parens
695 imenu-example--python-method-no-arg-parens))
696 (goto-char (point-min))
697 (imenu-example--create-python-index-engine nil))
698
699(defun imenu-example--create-python-index-engine (&optional start-indent)
700 "Function for finding imenu definitions in Python.
701
702Finds all definitions (classes, methods, or functions) in a Python
703file for the imenu package.
704
705Returns a possibly nested alist of the form
706
707 (INDEX-NAME . INDEX-POSITION)
708
709The second element of the alist may be an alist, producing a nested
710list as in
711
712 (INDEX-NAME . INDEX-ALIST)
713
714This function should not be called directly, as it calls itself
715recursively and requires some setup. Rather this is the engine for
716the function \\[imenu-example--create-python-index].
717
718It works recursively by looking for all definitions at the current
719indention level. When it finds one, it adds it to the alist. If it
720finds a definition at a greater indentation level, it removes the
721previous definition from the alist. In it's place it adds all
722definitions found at the next indentation level. When it finds a
723definition that is less indented then the current level, it retuns the
724alist it has created thus far.
725
726The optional argument START-INDENT indicates the starting indentation
727at which to continue looking for Python classes, methods, or
728functions. If this is not supplied, the function uses the indentation
729of the first definition found."
730 (let ((index-alist '())
731 (sub-method-alist '())
732 looking-p
733 def-name prev-name
734 cur-indent def-pos
735 (class-paren (first imenu-example--python-generic-parens))
736 (def-paren (second imenu-example--python-generic-parens)))
737 (setq looking-p
738 (re-search-forward imenu-example--python-generic-regexp
739 (point-max) t))
740 (while looking-p
741 (save-excursion
742 ;; used to set def-name to this value but generic-extract-name is
743 ;; new to imenu-1.14. this way it still works with imenu-1.11
744 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
745 (let ((cur-paren (if (match-beginning class-paren)
746 class-paren def-paren)))
747 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000748 (buffer-substring-no-properties (match-beginning cur-paren)
749 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000750 (beginning-of-line)
751 (setq cur-indent (current-indentation)))
752
753 ;; HACK: want to go to the next correct definition location. we
754 ;; explicitly list them here. would be better to have them in a
755 ;; list.
756 (setq def-pos
757 (or (match-beginning class-paren)
758 (match-beginning def-paren)))
759
760 ;; if we don't have a starting indent level, take this one
761 (or start-indent
762 (setq start-indent cur-indent))
763
764 ;; if we don't have class name yet, take this one
765 (or prev-name
766 (setq prev-name def-name))
767
768 ;; what level is the next definition on? must be same, deeper
769 ;; or shallower indentation
770 (cond
771 ;; at the same indent level, add it to the list...
772 ((= start-indent cur-indent)
773
774 ;; if we don't have push, use the following...
775 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
776 (push (cons def-name def-pos) index-alist))
777
778 ;; deeper indented expression, recur...
779 ((< start-indent cur-indent)
780
781 ;; the point is currently on the expression we're supposed to
782 ;; start on, so go back to the last expression. The recursive
783 ;; call will find this place again and add it to the correct
784 ;; list
785 (re-search-backward imenu-example--python-generic-regexp
786 (point-min) 'move)
787 (setq sub-method-alist (imenu-example--create-python-index-engine
788 cur-indent))
789
790 (if sub-method-alist
791 ;; we put the last element on the index-alist on the start
792 ;; of the submethod alist so the user can still get to it.
793 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000794 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000795 (cons save-elmt sub-method-alist))
796 index-alist))))
797
798 ;; found less indented expression, we're done.
799 (t
800 (setq looking-p nil)
801 (re-search-backward imenu-example--python-generic-regexp
802 (point-min) t)))
803 (setq prev-name def-name)
804 (and looking-p
805 (setq looking-p
806 (re-search-forward imenu-example--python-generic-regexp
807 (point-max) 'move))))
808 (nreverse index-alist)))
809
Barry Warsaw42f707f1996-07-29 21:05:05 +0000810
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000811;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812(defun python-mode ()
813 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000814To submit a problem report, enter `\\[py-submit-bug-report]' from a
815`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
816documentation. To see what version of `python-mode' you are running,
817enter `\\[py-version]'.
818
819This mode knows about Python indentation, tokens, comments and
820continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000821
822COMMANDS
823\\{py-mode-map}
824VARIABLES
825
Barry Warsaw42f707f1996-07-29 21:05:05 +0000826py-indent-offset\t\tindentation increment
827py-block-comment-prefix\t\tcomment string used by comment-region
828py-python-command\t\tshell command to invoke Python interpreter
829py-scroll-process-buffer\t\talways scroll Python process buffer
830py-temp-directory\t\tdirectory used for temp files (if needed)
831py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000832 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000833 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000834 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000835 (make-local-variable 'font-lock-defaults)
836 (make-local-variable 'paragraph-separate)
837 (make-local-variable 'paragraph-start)
838 (make-local-variable 'require-final-newline)
839 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000840 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000841 (make-local-variable 'comment-start-skip)
842 (make-local-variable 'comment-column)
843 (make-local-variable 'indent-region-function)
844 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000845 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000846 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000847 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000848 (setq major-mode 'python-mode
849 mode-name "Python"
850 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000851 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000852 paragraph-separate "^[ \t]*$"
853 paragraph-start "^[ \t]*$"
854 require-final-newline t
855 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000856 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000857 comment-start-skip "# *"
858 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000859 indent-region-function 'py-indent-region
860 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000861 ;; tell add-log.el how to find the current function/method/variable
862 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000863 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000864 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000865 ;; add the menu
866 (if py-menu
867 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000868 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000869 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000870 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000871 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000872 ;;
873 ;; not sure where the magic comment has to be; to save time
874 ;; searching for a rarity, we give up if it's not found prior to the
875 ;; first executable statement.
876 ;;
877 ;; BAW - on first glance, this seems like complete hackery. Why was
878 ;; this necessary, and is it still necessary?
879 (let ((case-fold-search nil)
880 (start (point))
881 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882 (if (re-search-forward
883 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
884 (prog2 (py-next-statement 1) (point) (goto-char 1))
885 t)
886 (progn
887 (setq new-tab-width
888 (string-to-int
889 (buffer-substring (match-beginning 1) (match-end 1))))
890 (if (= tab-width new-tab-width)
891 nil
892 (setq tab-width new-tab-width)
893 (message "Caution: tab-width changed to %d" new-tab-width)
894 (if py-beep-if-tab-change (beep)))))
895 (goto-char start))
896
Barry Warsaw755c6711996-08-01 20:02:55 +0000897 ;; install imenu
Barry Warsaw27ee1151997-12-03 05:03:44 +0000898 (if (py-safe (require 'imenu))
899 (progn
900 (make-variable-buffer-local 'imenu-create-index-function)
901 (setq imenu-create-index-function
902 (function imenu-example--create-python-index))
903 (setq imenu-generic-expression
904 imenu-example--generic-python-expression)
905 (if (fboundp 'imenu-add-to-menubar)
906 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
907 ))
Barry Warsaw755c6711996-08-01 20:02:55 +0000908
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000909 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000910 (if python-mode-hook
911 (run-hooks 'python-mode-hook)
912 (run-hooks 'py-mode-hook)))
913
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000914
Barry Warsawb91b7431995-03-14 15:55:20 +0000915;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000916(defun py-outdent-p ()
917 ;; returns non-nil if the current line should outdent one level
918 (save-excursion
919 (and (progn (back-to-indentation)
920 (looking-at py-outdent-re))
921 (progn (backward-to-indentation 1)
922 (while (or (looking-at py-blank-or-comment-re)
923 (bobp))
924 (backward-to-indentation 1))
925 (not (looking-at py-no-outdent-re)))
926 )))
927
Barry Warsawb91b7431995-03-14 15:55:20 +0000928(defun py-electric-colon (arg)
929 "Insert a colon.
930In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000931argument is provided, that many colons are inserted non-electrically.
932Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000933 (interactive "P")
934 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000935 ;; are we in a string or comment?
936 (if (save-excursion
937 (let ((pps (parse-partial-sexp (save-excursion
938 (beginning-of-python-def-or-class)
939 (point))
940 (point))))
941 (not (or (nth 3 pps) (nth 4 pps)))))
942 (save-excursion
943 (let ((here (point))
944 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000945 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000946 (if (and (not arg)
947 (py-outdent-p)
948 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000949 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000950 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000951 )
952 (setq outdent py-indent-offset))
953 ;; Don't indent, only outdent. This assumes that any lines that
954 ;; are already outdented relative to py-compute-indentation were
955 ;; put there on purpose. Its highly annoying to have `:' indent
956 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
957 ;; there a better way to determine this???
958 (if (< (current-indentation) indent) nil
959 (goto-char here)
960 (beginning-of-line)
961 (delete-horizontal-space)
962 (indent-to (- indent outdent))
963 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000964
965
Barry Warsawa97a3f31997-11-04 18:47:06 +0000966;; Python subprocess utilities and filters
967(defun py-execute-file (proc filename)
968 ;; Send a properly formatted execfile('FILENAME') to the underlying
969 ;; Python interpreter process FILENAME. Make that process's buffer
970 ;; visible and force display. Also make comint believe the user
971 ;; typed this string so that kill-output-from-shell does The Right
972 ;; Thing.
973 (let ((curbuf (current-buffer))
974 (procbuf (process-buffer proc))
975 (comint-scroll-to-bottom-on-output t)
976 (msg (format "## working on region in file %s...\n" filename))
977 (cmd (format "execfile('%s')\n" filename)))
978 (unwind-protect
979 (progn
980 (set-buffer procbuf)
981 (goto-char (point-max))
982 (move-marker (process-mark proc) (point))
983 (funcall (process-filter proc) proc msg))
984 (set-buffer curbuf))
985 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000986
987(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000988 (let ((curbuf (current-buffer))
989 (pbuf (process-buffer pyproc))
990 (pmark (process-mark pyproc))
991 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992 ;; make sure we switch to a different buffer at least once. if we
993 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994 ;; window, and point is before the end, and lots of output is
995 ;; coming at a fast pace, then (a) simple cursor-movement commands
996 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
997 ;; to have a visible effect (the window just doesn't get updated,
998 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
999 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001000 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001001 ;; #b makes no sense to me at all. #a almost makes sense: unless
1002 ;; we actually change buffers, set_buffer_internal in buffer.c
1003 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1004 ;; seems to make the Emacs command loop reluctant to update the
1005 ;; display. Perhaps the default process filter in process.c's
1006 ;; read_process_output has update_mode_lines++ for a similar
1007 ;; reason? beats me ...
1008
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001009 (unwind-protect
1010 ;; make sure current buffer is restored
1011 ;; BAW - we want to check to see if this still applies
1012 (progn
1013 ;; mysterious ugly hack
1014 (if (eq curbuf pbuf)
1015 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001017 (set-buffer pbuf)
1018 (let* ((start (point))
1019 (goback (< start pmark))
1020 (goend (and (not goback) (= start (point-max))))
1021 (buffer-read-only nil))
1022 (goto-char pmark)
1023 (insert string)
1024 (move-marker pmark (point))
1025 (setq file-finished
1026 (and py-file-queue
1027 (equal ">>> "
1028 (buffer-substring
1029 (prog2 (beginning-of-line) (point)
1030 (goto-char pmark))
1031 (point)))))
1032 (if goback (goto-char start)
1033 ;; else
1034 (if py-scroll-process-buffer
1035 (let* ((pop-up-windows t)
1036 (pwin (display-buffer pbuf)))
1037 (set-window-point pwin (point)))))
1038 (set-buffer curbuf)
1039 (if file-finished
1040 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001041 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001042 (setq py-file-queue (cdr py-file-queue))
1043 (if py-file-queue
1044 (py-execute-file pyproc (car py-file-queue)))))
1045 (and goend
1046 (progn (set-buffer pbuf)
1047 (goto-char (point-max))))
1048 ))
1049 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001050
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001051(defun py-postprocess-output-buffer (buf)
Barry Warsaw9981d221997-12-03 05:25:48 +00001052 (let (line file bol)
1053 (save-excursion
1054 (set-buffer buf)
1055 (beginning-of-buffer)
1056 (while (re-search-forward py-traceback-line-re nil t)
1057 (setq file (match-string 1)
1058 line (string-to-int (match-string 2))
1059 bol (py-point 'bol))
1060 (py-highlight-line bol (py-point 'eol) file line))
1061 (when (and py-jump-on-exception line)
1062 (beep)
1063 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001064 )))
1065
Barry Warsaw9981d221997-12-03 05:25:48 +00001066
Barry Warsawa97a3f31997-11-04 18:47:06 +00001067
1068;;; Subprocess commands
1069
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001070;; only used when (memq 'broken-temp-names py-emacs-features)
1071(defvar py-serial-number 0)
1072(defvar py-exception-buffer nil)
1073(defconst py-output-buffer "*Python Output*")
1074
Barry Warsawa97a3f31997-11-04 18:47:06 +00001075;;;###autoload
1076(defun py-shell ()
1077 "Start an interactive Python interpreter in another window.
1078This is like Shell mode, except that Python is running in the window
1079instead of a shell. See the `Interactive Shell' and `Shell Mode'
1080sections of the Emacs manual for details, especially for the key
1081bindings active in the `*Python*' buffer.
1082
1083See the docs for variable `py-scroll-buffer' for info on scrolling
1084behavior in the process window.
1085
1086Warning: Don't use an interactive Python if you change sys.ps1 or
1087sys.ps2 from their default values, or if you're running code that
1088prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1089distinguish your output from Python's output, and assumes that `>>> '
1090at the start of a line is a prompt from Python. Similarly, the Emacs
1091Shell mode code assumes that both `>>> ' and `... ' at the start of a
1092line are Python prompts. Bad things can happen if you fool either
1093mode.
1094
1095Warning: If you do any editing *in* the process buffer *while* the
1096buffer is accepting output from Python, do NOT attempt to `undo' the
1097changes. Some of the output (nowhere near the parts you changed!) may
1098be lost if you do. This appears to be an Emacs bug, an unfortunate
1099interaction between undo and process filters; the same problem exists in
1100non-Python process buffers using the default (Emacs-supplied) process
1101filter."
1102 ;; BAW - should undo be disabled in the python process buffer, if
1103 ;; this bug still exists?
1104 (interactive)
1105 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001106 (switch-to-buffer-other-window
1107 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001108 (make-local-variable 'comint-prompt-regexp)
1109 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1110 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1111 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001112 ;; set up keybindings for this subshell
1113 (local-set-key [tab] 'self-insert-command)
1114 (local-set-key "\C-c-" 'py-up-exception)
1115 (local-set-key "\C-c=" 'py-down-exception)
1116 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001117
Barry Warsawa97a3f31997-11-04 18:47:06 +00001118(defun py-clear-queue ()
1119 "Clear the queue of temporary files waiting to execute."
1120 (interactive)
1121 (let ((n (length py-file-queue)))
1122 (mapcar 'delete-file py-file-queue)
1123 (setq py-file-queue nil)
1124 (message "%d pending files de-queued." n)))
1125
1126(defun py-execute-region (start end &optional async)
1127 "Execute the the region in a Python interpreter.
1128The region is first copied into a temporary file (in the directory
1129`py-temp-directory'). If there is no Python interpreter shell
1130running, this file is executed synchronously using
1131`shell-command-on-region'. If the program is long running, use an
1132optional \\[universal-argument] to run the command asynchronously in
1133its own buffer.
1134
1135If the Python interpreter shell is running, the region is execfile()'d
1136in that shell. If you try to execute regions too quickly,
1137`python-mode' will queue them up and execute them one at a time when
1138it sees a `>>> ' prompt from Python. Each time this happens, the
1139process buffer is popped into a window (if it's not already in some
1140window) so you can see it, and a comment of the form
1141
1142 \t## working on region in file <name>...
1143
1144is inserted at the end. See also the command `py-clear-queue'."
1145 (interactive "r\nP")
1146 (or (< start end)
1147 (error "Region is empty"))
1148 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001149 (temp (if (memq 'broken-temp-names py-emacs-features)
1150 (prog1
1151 (format "python-%d" py-serial-number)
1152 (setq py-serial-number (1+ py-serial-number)))
1153 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001154 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001155 (write-region start end file nil 'nomsg)
1156 (cond
1157 ;; always run the code in it's own asynchronous subprocess
1158 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001159 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001160 (start-process "Python" buf py-python-command "-u" file)
1161 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001162 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001163 ))
1164 ;; if the Python interpreter shell is running, queue it up for
1165 ;; execution there.
1166 (proc
1167 ;; use the existing python shell
1168 (if (not py-file-queue)
1169 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001170 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001171 (push file py-file-queue)
1172 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001173 (t
1174 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001175 (shell-command-on-region start end py-python-command py-output-buffer)
1176 (setq py-exception-buffer (current-buffer))
1177 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001178 ))))
1179
1180;; Code execution command
1181(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001182 "Send the contents of the buffer to a Python interpreter.
1183If there is a *Python* process buffer it is used. If a clipping
1184restriction is in effect, only the accessible portion of the buffer is
1185sent. A trailing newline will be supplied if needed.
1186
1187See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001188 (interactive "P")
1189 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001191
1192
1193(defun py-jump-to-exception (file line)
1194 (let ((buffer (cond ((string-equal file "<stdin>")
1195 py-exception-buffer)
1196 ((and (consp py-exception-buffer)
1197 (string-equal file (car py-exception-buffer)))
1198 (cdr py-exception-buffer))
1199 ((py-safe (find-file-noselect file)))
1200 ;; could not figure out what file the exception
1201 ;; is pointing to, so prompt for it
1202 (t (find-file (read-file-name "Exception file: "
1203 nil
1204 file t))))))
1205 (pop-to-buffer buffer)
1206 (goto-line line)
1207 (message "Jumping to exception in file %s on line %d" file line)))
1208
1209(defun py-mouseto-exception (event)
1210 (interactive "e")
1211 (cond
1212 ((fboundp 'event-point)
1213 ;; XEmacs
1214 (let* ((point (event-point event))
1215 (buffer (event-buffer event))
1216 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1217 (info (and e (extent-property e 'py-exc-info))))
1218 (message "Event point: %d, info: %s" point info)
1219 (and info
1220 (py-jump-to-exception (car info) (cdr info)))
1221 ))
1222 ;; Emacs -- Please port this!
1223 ))
1224
1225(defun py-goto-exception ()
1226 "Go to the line indicated by the traceback."
1227 (interactive)
1228 (let (file line)
1229 (save-excursion
1230 (beginning-of-line)
1231 (if (looking-at py-traceback-line-re)
1232 (setq file (match-string 1)
1233 line (string-to-int (match-string 2)))))
1234 (if (not file)
1235 (error "Not on a traceback line."))
1236 (py-jump-to-exception file line)))
1237
1238(defun py-find-next-exception (start buffer searchdir errwhere)
1239 ;; Go to start position in buffer, search in the specified
1240 ;; direction, and jump to the exception found. If at the end of the
1241 ;; exception, print error message
1242 (let (file line)
1243 (save-excursion
1244 (set-buffer buffer)
1245 (goto-char (py-point start))
1246 (if (funcall searchdir py-traceback-line-re nil t)
1247 (setq file (match-string 1)
1248 line (string-to-int (match-string 2)))))
1249 (if (and file line)
1250 (py-jump-to-exception file line)
1251 (error "%s of traceback" errwhere))))
1252
1253(defun py-down-exception (&optional bottom)
1254 "Go to the next line down in the traceback.
1255With optional \\[universal-argument], jump to the bottom (innermost)
1256exception in the exception stack."
1257 (interactive "P")
1258 (let* ((proc (get-process "Python"))
1259 (buffer (if proc "*Python*" py-output-buffer)))
1260 (if bottom
1261 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1262 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1263
1264(defun py-up-exception (&optional top)
1265 "Go to the previous line up in the traceback.
1266With optional \\[universal-argument], jump to the top (outermost)
1267exception in the exception stack."
1268 (interactive "P")
1269 (let* ((proc (get-process "Python"))
1270 (buffer (if proc "*Python*" py-output-buffer)))
1271 (if top
1272 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001273 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001274
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001275
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001276;; Electric deletion
1277(defun py-electric-backspace (arg)
1278 "Deletes preceding character or levels of indentation.
1279Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001280with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001281
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001282If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001283
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001284Otherwise, if point is at the leftmost non-whitespace character of a
1285line that is neither a continuation line nor a non-indenting comment
1286line, or if point is at the end of a blank line, this command reduces
1287the indentation to match that of the line that opened the current
1288block of code. The line that opened the block is displayed in the
1289echo area to help you keep track of where you are. With numeric arg,
1290outdents that many blocks (but not past column zero).
1291
1292Otherwise the preceding character is deleted, converting a tab to
1293spaces if needed so that only a single column position is deleted.
1294Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001295 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296 (if (or (/= (current-indentation) (current-column))
1297 (bolp)
1298 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001299 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001300 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001301 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001302 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001303 ;; force non-blank so py-goto-block-up doesn't ignore it
1304 (insert-char ?* 1)
1305 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001306 (let ((base-indent 0) ; indentation of base line
1307 (base-text "") ; and text of base line
1308 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001309 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001310 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001311 (condition-case nil ; in case no enclosing block
1312 (progn
1313 (py-goto-block-up 'no-mark)
1314 (setq base-indent (current-indentation)
1315 base-text (py-suck-up-leading-text)
1316 base-found-p t))
1317 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001318 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001319 (delete-char 1) ; toss the dummy character
1320 (delete-horizontal-space)
1321 (indent-to base-indent)
1322 (if base-found-p
1323 (message "Closes block: %s" base-text)))))
1324
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001325
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001326(defun py-electric-delete (arg)
1327 "Deletes preceding or following character or levels of whitespace.
1328
1329The behavior of this function depends on the variable
1330`delete-key-deletes-forward'. If this variable is nil (or does not
1331exist, as in older Emacsen), then this function behaves identical to
1332\\[c-electric-backspace].
1333
1334If `delete-key-deletes-forward' is non-nil and is supported in your
1335Emacs, then deletion occurs in the forward direction, by calling the
1336function in `py-delete-function'."
1337 (interactive "*p")
1338 (if (and (boundp 'delete-key-deletes-forward)
1339 delete-key-deletes-forward)
1340 (funcall py-delete-function arg)
1341 ;; else
1342 (py-electric-backspace arg)))
1343
1344;; required for pending-del and delsel modes
1345(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1346(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1347(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1348(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1349
1350
1351
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001352(defun py-indent-line (&optional arg)
1353 "Fix the indentation of the current line according to Python rules.
1354With \\[universal-argument], ignore outdenting rules for block
1355closing statements (e.g. return, raise, break, continue, pass)
1356
1357This function is normally bound to `indent-line-function' so
1358\\[indent-for-tab-command] will call it."
1359 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360 (let* ((ci (current-indentation))
1361 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001362 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001363 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001364 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001365 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001366 (if (/= ci need)
1367 (save-excursion
1368 (beginning-of-line)
1369 (delete-horizontal-space)
1370 (indent-to need)))
1371 (if move-to-indentation-p (back-to-indentation))))
1372
1373(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001374 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001375This is just `strives to' because correct indentation can't be computed
1376from scratch for Python code. In general, deletes the whitespace before
1377point, inserts a newline, and takes an educated guess as to how you want
1378the new line indented."
1379 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001380 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001381 (if (< ci (current-column)) ; if point beyond indentation
1382 (newline-and-indent)
1383 ;; else try to act like newline-and-indent "normally" acts
1384 (beginning-of-line)
1385 (insert-char ?\n 1)
1386 (move-to-column ci))))
1387
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001388(defun py-compute-indentation (honor-block-close-p)
1389 ;; implements all the rules for indentation computation. when
1390 ;; honor-block-close-p is non-nil, statements such as return, raise,
1391 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001392 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001393 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001394 (pps (parse-partial-sexp bod (point)))
1395 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001396 (beginning-of-line)
1397 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001398 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001399 ((or (and (nth 3 pps) (nth 3 boipps))
1400 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001401 (save-excursion
1402 (if (not py-align-multiline-strings-p) 0
1403 ;; skip back over blank & non-indenting comment lines
1404 ;; note: will skip a blank or non-indenting comment line
1405 ;; that happens to be a continuation line too
1406 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1407 (back-to-indentation)
1408 (current-column))))
1409 ;; are we on a continuation line?
1410 ((py-continuation-line-p)
1411 (let ((startpos (point))
1412 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001413 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001414 (if open-bracket-pos
1415 (progn
1416 ;; align with first item in list; else a normal
1417 ;; indent beyond the line with the open bracket
1418 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1419 ;; is the first list item on the same line?
1420 (skip-chars-forward " \t")
1421 (if (null (memq (following-char) '(?\n ?# ?\\)))
1422 ; yes, so line up with it
1423 (current-column)
1424 ;; first list item on another line, or doesn't exist yet
1425 (forward-line 1)
1426 (while (and (< (point) startpos)
1427 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1428 (forward-line 1))
1429 (if (< (point) startpos)
1430 ;; again mimic the first list item
1431 (current-indentation)
1432 ;; else they're about to enter the first item
1433 (goto-char open-bracket-pos)
1434 (+ (current-indentation) py-indent-offset))))
1435
1436 ;; else on backslash continuation line
1437 (forward-line -1)
1438 (if (py-continuation-line-p) ; on at least 3rd line in block
1439 (current-indentation) ; so just continue the pattern
1440 ;; else started on 2nd line in block, so indent more.
1441 ;; if base line is an assignment with a start on a RHS,
1442 ;; indent to 2 beyond the leftmost "="; else skip first
1443 ;; chunk of non-whitespace characters on base line, + 1 more
1444 ;; column
1445 (end-of-line)
1446 (setq endpos (point) searching t)
1447 (back-to-indentation)
1448 (setq startpos (point))
1449 ;; look at all "=" from left to right, stopping at first
1450 ;; one not nested in a list or string
1451 (while searching
1452 (skip-chars-forward "^=" endpos)
1453 (if (= (point) endpos)
1454 (setq searching nil)
1455 (forward-char 1)
1456 (setq state (parse-partial-sexp startpos (point)))
1457 (if (and (zerop (car state)) ; not in a bracket
1458 (null (nth 3 state))) ; & not in a string
1459 (progn
1460 (setq searching nil) ; done searching in any case
1461 (setq found
1462 (not (or
1463 (eq (following-char) ?=)
1464 (memq (char-after (- (point) 2))
1465 '(?< ?> ?!)))))))))
1466 (if (or (not found) ; not an assignment
1467 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1468 (progn
1469 (goto-char startpos)
1470 (skip-chars-forward "^ \t\n")))
1471 (1+ (current-column))))))
1472
1473 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001474 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001475
Barry Warsawa7891711996-08-01 15:53:09 +00001476 ;; Dfn: "Indenting comment line". A line containing only a
1477 ;; comment, but which is treated like a statement for
1478 ;; indentation calculation purposes. Such lines are only
1479 ;; treated specially by the mode; they are not treated
1480 ;; specially by the Python interpreter.
1481
1482 ;; The rules for indenting comment lines are a line where:
1483 ;; - the first non-whitespace character is `#', and
1484 ;; - the character following the `#' is whitespace, and
1485 ;; - the line is outdented with respect to (i.e. to the left
1486 ;; of) the indentation of the preceding non-blank line.
1487
1488 ;; The first non-blank line following an indenting comment
1489 ;; line is given the same amount of indentation as the
1490 ;; indenting comment line.
1491
1492 ;; All other comment-only lines are ignored for indentation
1493 ;; purposes.
1494
1495 ;; Are we looking at a comment-only line which is *not* an
1496 ;; indenting comment line? If so, we assume that its been
1497 ;; placed at the desired indentation, so leave it alone.
1498 ;; Indenting comment lines are aligned as statements down
1499 ;; below.
1500 ((and (looking-at "[ \t]*#[^ \t\n]")
1501 ;; NOTE: this test will not be performed in older Emacsen
1502 (fboundp 'forward-comment)
1503 (<= (current-indentation)
1504 (save-excursion
1505 (forward-comment (- (point-max)))
1506 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001507 (current-indentation))
1508
1509 ;; else indentation based on that of the statement that
1510 ;; precedes us; use the first line of that statement to
1511 ;; establish the base, in case the user forced a non-std
1512 ;; indentation for the continuation lines (if any)
1513 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001514 ;; skip back over blank & non-indenting comment lines note:
1515 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001516 ;; happens to be a continuation line too. use fast Emacs 19
1517 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001518 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001519 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001520 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001521 (let (done)
1522 (while (not done)
1523 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1524 nil 'move)
1525 (setq done (or (eq py-honor-comment-indentation t)
1526 (bobp)
1527 (/= (following-char) ?#)
1528 (not (zerop (current-column)))))
1529 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001530 ;; if we landed inside a string, go to the beginning of that
1531 ;; string. this handles triple quoted, multi-line spanning
1532 ;; strings.
1533 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001534 (+ (current-indentation)
1535 (if (py-statement-opens-block-p)
1536 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001537 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001538 (- py-indent-offset)
1539 0)))
1540 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001543 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001545`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001546Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548their own buffer-local copy), both those currently existing and those
1549created later in the Emacs session.
1550
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552There's no excuse for such foolishness, but sometimes you have to deal
1553with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001554`py-indent-offset' to what it thinks it was when they created the
1555mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001556
1557Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001558looking for a line that opens a block of code. `py-indent-offset' is
1559set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001560statement following it. If the search doesn't succeed going forward,
1561it's tried again going backward."
1562 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001563 (let (new-value
1564 (start (point))
1565 restart
1566 (found nil)
1567 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001568 (py-goto-initial-line)
1569 (while (not (or found (eobp)))
1570 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1571 (progn
1572 (setq restart (point))
1573 (py-goto-initial-line)
1574 (if (py-statement-opens-block-p)
1575 (setq found t)
1576 (goto-char restart)))))
1577 (if found
1578 ()
1579 (goto-char start)
1580 (py-goto-initial-line)
1581 (while (not (or found (bobp)))
1582 (setq found
1583 (and
1584 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1585 (or (py-goto-initial-line) t) ; always true -- side effect
1586 (py-statement-opens-block-p)))))
1587 (setq colon-indent (current-indentation)
1588 found (and found (zerop (py-next-statement 1)))
1589 new-value (- (current-indentation) colon-indent))
1590 (goto-char start)
1591 (if found
1592 (progn
1593 (funcall (if global 'kill-local-variable 'make-local-variable)
1594 'py-indent-offset)
1595 (setq py-indent-offset new-value)
1596 (message "%s value of py-indent-offset set to %d"
1597 (if global "Global" "Local")
1598 py-indent-offset))
1599 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1600
1601(defun py-shift-region (start end count)
1602 (save-excursion
1603 (goto-char end) (beginning-of-line) (setq end (point))
1604 (goto-char start) (beginning-of-line) (setq start (point))
1605 (indent-rigidly start end count)))
1606
1607(defun py-shift-region-left (start end &optional count)
1608 "Shift region of Python code to the left.
1609The lines from the line containing the start of the current region up
1610to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001611shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001612
1613If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001614many columns. With no active region, outdent only the current line.
1615You cannot outdent the region if any line is already at column zero."
1616 (interactive
1617 (let ((p (point))
1618 (m (mark))
1619 (arg current-prefix-arg))
1620 (if m
1621 (list (min p m) (max p m) arg)
1622 (list p (save-excursion (forward-line 1) (point)) arg))))
1623 ;; if any line is at column zero, don't shift the region
1624 (save-excursion
1625 (goto-char start)
1626 (while (< (point) end)
1627 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001628 (if (and (zerop (current-column))
1629 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001630 (error "Region is at left edge."))
1631 (forward-line 1)))
1632 (py-shift-region start end (- (prefix-numeric-value
1633 (or count py-indent-offset))))
1634 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001635
1636(defun py-shift-region-right (start end &optional count)
1637 "Shift region of Python code to the right.
1638The lines from the line containing the start of the current region up
1639to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001640shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641
1642If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001643many columns. With no active region, indent only the current line."
1644 (interactive
1645 (let ((p (point))
1646 (m (mark))
1647 (arg current-prefix-arg))
1648 (if m
1649 (list (min p m) (max p m) arg)
1650 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001651 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001652 (or count py-indent-offset)))
1653 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654
1655(defun py-indent-region (start end &optional indent-offset)
1656 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001657
Barry Warsaw7ae77681994-12-12 20:38:05 +00001658The lines from the line containing the start of the current region up
1659to (but not including) the line containing the end of the region are
1660reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001661character in the first column, the first line is left alone and the
1662rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001663region is reindented with respect to the (closest code or indenting
1664comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001665
1666This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667control structures are introduced or removed, or to reformat code
1668using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001669
1670If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001672used.
1673
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001674Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675is called! This function does not compute proper indentation from
1676scratch (that's impossible in Python), it merely adjusts the existing
1677indentation to be correct in context.
1678
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001679Warning: This function really has no idea what to do with
1680non-indenting comment lines, and shifts them as if they were indenting
1681comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001682
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001683Special cases: whitespace is deleted from blank lines; continuation
1684lines are shifted by the same amount their initial line was shifted,
1685in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001686initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001687 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001688 (save-excursion
1689 (goto-char end) (beginning-of-line) (setq end (point-marker))
1690 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001691 (let ((py-indent-offset (prefix-numeric-value
1692 (or indent-offset py-indent-offset)))
1693 (indents '(-1)) ; stack of active indent levels
1694 (target-column 0) ; column to which to indent
1695 (base-shifted-by 0) ; amount last base line was shifted
1696 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001697 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001698 0))
1699 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001700 (while (< (point) end)
1701 (setq ci (current-indentation))
1702 ;; figure out appropriate target column
1703 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001704 ((or (eq (following-char) ?#) ; comment in column 1
1705 (looking-at "[ \t]*$")) ; entirely blank
1706 (setq target-column 0))
1707 ((py-continuation-line-p) ; shift relative to base line
1708 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001709 (t ; new base line
1710 (if (> ci (car indents)) ; going deeper; push it
1711 (setq indents (cons ci indents))
1712 ;; else we should have seen this indent before
1713 (setq indents (memq ci indents)) ; pop deeper indents
1714 (if (null indents)
1715 (error "Bad indentation in region, at line %d"
1716 (save-restriction
1717 (widen)
1718 (1+ (count-lines 1 (point)))))))
1719 (setq target-column (+ indent-base
1720 (* py-indent-offset
1721 (- (length indents) 2))))
1722 (setq base-shifted-by (- target-column ci))))
1723 ;; shift as needed
1724 (if (/= ci target-column)
1725 (progn
1726 (delete-horizontal-space)
1727 (indent-to target-column)))
1728 (forward-line 1))))
1729 (set-marker end nil))
1730
Barry Warsawa7891711996-08-01 15:53:09 +00001731(defun py-comment-region (beg end &optional arg)
1732 "Like `comment-region' but uses double hash (`#') comment starter."
1733 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001734 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001735 (comment-region beg end arg)))
1736
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001737
1738;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739(defun py-previous-statement (count)
1740 "Go to the start of previous Python statement.
1741If the statement at point is the i'th Python statement, goes to the
1742start of statement i-COUNT. If there is no such statement, goes to the
1743first statement. Returns count of statements left to move.
1744`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001745 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746 (if (< count 0) (py-next-statement (- count))
1747 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001748 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001749 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001750 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001751 (> count 0)
1752 (zerop (forward-line -1))
1753 (py-goto-statement-at-or-above))
1754 (setq count (1- count)))
1755 (if (> count 0) (goto-char start)))
1756 count))
1757
1758(defun py-next-statement (count)
1759 "Go to the start of next Python statement.
1760If the statement at point is the i'th Python statement, goes to the
1761start of statement i+COUNT. If there is no such statement, goes to the
1762last statement. Returns count of statements left to move. `Statements'
1763do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001765 (if (< count 0) (py-previous-statement (- count))
1766 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001767 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001769 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001770 (> count 0)
1771 (py-goto-statement-below))
1772 (setq count (1- count)))
1773 (if (> count 0) (goto-char start)))
1774 count))
1775
1776(defun py-goto-block-up (&optional nomark)
1777 "Move up to start of current block.
1778Go to the statement that starts the smallest enclosing block; roughly
1779speaking, this will be the closest preceding statement that ends with a
1780colon and is indented less than the statement you started on. If
1781successful, also sets the mark to the starting point.
1782
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001783`\\[py-mark-block]' can be used afterward to mark the whole code
1784block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785
1786If called from a program, the mark will not be set if optional argument
1787NOMARK is not nil."
1788 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789 (let ((start (point))
1790 (found nil)
1791 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792 (py-goto-initial-line)
1793 ;; if on blank or non-indenting comment line, use the preceding stmt
1794 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1795 (progn
1796 (py-goto-statement-at-or-above)
1797 (setq found (py-statement-opens-block-p))))
1798 ;; search back for colon line indented less
1799 (setq initial-indent (current-indentation))
1800 (if (zerop initial-indent)
1801 ;; force fast exit
1802 (goto-char (point-min)))
1803 (while (not (or found (bobp)))
1804 (setq found
1805 (and
1806 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1807 (or (py-goto-initial-line) t) ; always true -- side effect
1808 (< (current-indentation) initial-indent)
1809 (py-statement-opens-block-p))))
1810 (if found
1811 (progn
1812 (or nomark (push-mark start))
1813 (back-to-indentation))
1814 (goto-char start)
1815 (error "Enclosing block not found"))))
1816
1817(defun beginning-of-python-def-or-class (&optional class)
1818 "Move point to start of def (or class, with prefix arg).
1819
1820Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821arg, looks for a `class' instead. The docs assume the `def' case;
1822just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001823
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001824If point is in a def statement already, and after the `d', simply
1825moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827Else (point is not in a def statement, or at or before the `d' of a
1828def statement), searches for the closest preceding def statement, and
1829leaves point at its start. If no such statement can be found, leaves
1830point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001831
1832Returns t iff a def statement is found by these rules.
1833
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834Note that doing this command repeatedly will take you closer to the
1835start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001836
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001838`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1841 (start-of-line (progn (beginning-of-line) (point)))
1842 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001843 (if (or (/= start-of-stmt start-of-line)
1844 (not at-or-before-p))
1845 (end-of-line)) ; OK to match on this line
1846 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848
1849(defun end-of-python-def-or-class (&optional class)
1850 "Move point beyond end of def (or class, with prefix arg) body.
1851
1852By default, looks for an appropriate `def'. If you supply a prefix arg,
1853looks for a `class' instead. The docs assume the `def' case; just
1854substitute `class' for `def' for the other case.
1855
1856If point is in a def statement already, this is the def we use.
1857
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858Else if the def found by `\\[beginning-of-python-def-or-class]'
1859contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860
1861Else we search forward for the closest following def, and use that.
1862
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863If a def can be found by these rules, point is moved to the start of
1864the line immediately following the def block, and the position of the
1865start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866
1867Else point is moved to the end of the buffer, and nil is returned.
1868
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869Note that doing this command repeatedly will take you closer to the
1870end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001871
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001873`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875 (let ((start (progn (py-goto-initial-line) (point)))
1876 (which (if class "class" "def"))
1877 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878 ;; move point to start of appropriate def/class
1879 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1880 (setq state 'at-beginning)
1881 ;; else see if beginning-of-python-def-or-class hits container
1882 (if (and (beginning-of-python-def-or-class class)
1883 (progn (py-goto-beyond-block)
1884 (> (point) start)))
1885 (setq state 'at-end)
1886 ;; else search forward
1887 (goto-char start)
1888 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1889 (progn (setq state 'at-beginning)
1890 (beginning-of-line)))))
1891 (cond
1892 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1893 ((eq state 'at-end) t)
1894 ((eq state 'not-found) nil)
1895 (t (error "internal error in end-of-python-def-or-class")))))
1896
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897
1898;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001899(defun py-mark-block (&optional extend just-move)
1900 "Mark following block of lines. With prefix arg, mark structure.
1901Easier to use than explain. It sets the region to an `interesting'
1902block of succeeding lines. If point is on a blank line, it goes down to
1903the next non-blank line. That will be the start of the region. The end
1904of the region depends on the kind of line at the start:
1905
1906 - If a comment, the region will include all succeeding comment lines up
1907 to (but not including) the next non-comment line (if any).
1908
1909 - Else if a prefix arg is given, and the line begins one of these
1910 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001911
1912 if elif else try except finally for while def class
1913
Barry Warsaw7ae77681994-12-12 20:38:05 +00001914 the region will be set to the body of the structure, including
1915 following blocks that `belong' to it, but excluding trailing blank
1916 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001917 and all (if any) of the following `except' and `finally' blocks
1918 that belong to the `try' structure will be in the region. Ditto
1919 for if/elif/else, for/else and while/else structures, and (a bit
1920 degenerate, since they're always one-block structures) def and
1921 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922
1923 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924 block (see list above), and the block is not a `one-liner' (i.e.,
1925 the statement ends with a colon, not with code), the region will
1926 include all succeeding lines up to (but not including) the next
1927 code statement (if any) that's indented no more than the starting
1928 line, except that trailing blank and comment lines are excluded.
1929 E.g., if the starting line begins a multi-statement `def'
1930 structure, the region will be set to the full function definition,
1931 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932
1933 - Else the region will include all succeeding lines up to (but not
1934 including) the next blank line, or code or indenting-comment line
1935 indented strictly less than the starting line. Trailing indenting
1936 comment lines are included in this case, but not trailing blank
1937 lines.
1938
1939A msg identifying the location of the mark is displayed in the echo
1940area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1941
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001942If called from a program, optional argument EXTEND plays the role of
1943the prefix arg, and if optional argument JUST-MOVE is not nil, just
1944moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945 (interactive "P") ; raw prefix arg
1946 (py-goto-initial-line)
1947 ;; skip over blank lines
1948 (while (and
1949 (looking-at "[ \t]*$") ; while blank line
1950 (not (eobp))) ; & somewhere to go
1951 (forward-line 1))
1952 (if (eobp)
1953 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001954 (let ((initial-pos (point))
1955 (initial-indent (current-indentation))
1956 last-pos ; position of last stmt in region
1957 (followers
1958 '((if elif else) (elif elif else) (else)
1959 (try except finally) (except except) (finally)
1960 (for else) (while else)
1961 (def) (class) ) )
1962 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001963
1964 (cond
1965 ;; if comment line, suck up the following comment lines
1966 ((looking-at "[ \t]*#")
1967 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1968 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1969 (setq last-pos (point)))
1970
1971 ;; else if line is a block line and EXTEND given, suck up
1972 ;; the whole structure
1973 ((and extend
1974 (setq first-symbol (py-suck-up-first-keyword) )
1975 (assq first-symbol followers))
1976 (while (and
1977 (or (py-goto-beyond-block) t) ; side effect
1978 (forward-line -1) ; side effect
1979 (setq last-pos (point)) ; side effect
1980 (py-goto-statement-below)
1981 (= (current-indentation) initial-indent)
1982 (setq next-symbol (py-suck-up-first-keyword))
1983 (memq next-symbol (cdr (assq first-symbol followers))))
1984 (setq first-symbol next-symbol)))
1985
1986 ;; else if line *opens* a block, search for next stmt indented <=
1987 ((py-statement-opens-block-p)
1988 (while (and
1989 (setq last-pos (point)) ; always true -- side effect
1990 (py-goto-statement-below)
1991 (> (current-indentation) initial-indent))
1992 nil))
1993
1994 ;; else plain code line; stop at next blank line, or stmt or
1995 ;; indenting comment line indented <
1996 (t
1997 (while (and
1998 (setq last-pos (point)) ; always true -- side effect
1999 (or (py-goto-beyond-final-line) t)
2000 (not (looking-at "[ \t]*$")) ; stop at blank line
2001 (or
2002 (>= (current-indentation) initial-indent)
2003 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2004 nil)))
2005
2006 ;; skip to end of last stmt
2007 (goto-char last-pos)
2008 (py-goto-beyond-final-line)
2009
2010 ;; set mark & display
2011 (if just-move
2012 () ; just return
2013 (push-mark (point) 'no-msg)
2014 (forward-line -1)
2015 (message "Mark set after: %s" (py-suck-up-leading-text))
2016 (goto-char initial-pos))))
2017
Barry Warsaw2518c671997-11-05 00:51:08 +00002018(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002019 "Set region to body of def (or class, with prefix arg) enclosing point.
2020Pushes the current mark, then point, on the mark ring (all language
2021modes do this, but although it's handy it's never documented ...).
2022
2023In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002024hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2025`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002026
2027And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028Turned out that was more confusing than useful: the `goto start' and
2029`goto end' commands are usually used to search through a file, and
2030people expect them to act a lot like `search backward' and `search
2031forward' string-search commands. But because Python `def' and `class'
2032can nest to arbitrary levels, finding the smallest def containing
2033point cannot be done via a simple backward search: the def containing
2034point may not be the closest preceding def, or even the closest
2035preceding def that's indented less. The fancy algorithm required is
2036appropriate for the usual uses of this `mark' command, but not for the
2037`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002039So the def marked by this command may not be the one either of the
2040`goto' commands find: If point is on a blank or non-indenting comment
2041line, moves back to start of the closest preceding code statement or
2042indenting comment line. If this is a `def' statement, that's the def
2043we use. Else searches for the smallest enclosing `def' block and uses
2044that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002045
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002046When an enclosing def is found: The mark is left immediately beyond
2047the last line of the def block. Point is left at the start of the
2048def, except that: if the def is preceded by a number of comment lines
2049followed by (at most) one optional blank line, point is left at the
2050start of the comments; else if the def is preceded by a blank line,
2051point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002052
2053The intent is to mark the containing def/class and its associated
2054documentation, to make moving and duplicating functions and classes
2055pleasant."
2056 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002057 (let ((start (point))
2058 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059 (push-mark start)
2060 (if (not (py-go-up-tree-to-keyword which))
2061 (progn (goto-char start)
2062 (error "Enclosing %s not found" which))
2063 ;; else enclosing def/class found
2064 (setq start (point))
2065 (py-goto-beyond-block)
2066 (push-mark (point))
2067 (goto-char start)
2068 (if (zerop (forward-line -1)) ; if there is a preceding line
2069 (progn
2070 (if (looking-at "[ \t]*$") ; it's blank
2071 (setq start (point)) ; so reset start point
2072 (goto-char start)) ; else try again
2073 (if (zerop (forward-line -1))
2074 (if (looking-at "[ \t]*#") ; a comment
2075 ;; look back for non-comment line
2076 ;; tricky: note that the regexp matches a blank
2077 ;; line, cuz \n is in the 2nd character class
2078 (and
2079 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2080 (forward-line 1))
2081 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002082 (goto-char start)))))))
2083 (exchange-point-and-mark)
2084 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002085
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002086;; ripped from cc-mode
2087(defun py-forward-into-nomenclature (&optional arg)
2088 "Move forward to end of a nomenclature section or word.
2089With arg, to it arg times.
2090
2091A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2092 (interactive "p")
2093 (let ((case-fold-search nil))
2094 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002095 (re-search-forward
2096 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2097 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002098 (while (and (< arg 0)
2099 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002100 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002101 (point-min) 0))
2102 (forward-char 1)
2103 (setq arg (1+ arg)))))
2104 (py-keep-region-active))
2105
2106(defun py-backward-into-nomenclature (&optional arg)
2107 "Move backward to beginning of a nomenclature section or word.
2108With optional ARG, move that many times. If ARG is negative, move
2109forward.
2110
2111A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2112 (interactive "p")
2113 (py-forward-into-nomenclature (- arg))
2114 (py-keep-region-active))
2115
2116
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002117
2118;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002119
2120;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002121;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2122;; out of the right places, along with the keys they're on & current
2123;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002124(defun py-dump-help-string (str)
2125 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002126 (let ((locals (buffer-local-variables))
2127 funckind funcname func funcdoc
2128 (start 0) mstart end
2129 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002130 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2131 (setq mstart (match-beginning 0) end (match-end 0)
2132 funckind (substring str (match-beginning 1) (match-end 1))
2133 funcname (substring str (match-beginning 2) (match-end 2))
2134 func (intern funcname))
2135 (princ (substitute-command-keys (substring str start mstart)))
2136 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002137 ((equal funckind "c") ; command
2138 (setq funcdoc (documentation func)
2139 keys (concat
2140 "Key(s): "
2141 (mapconcat 'key-description
2142 (where-is-internal func py-mode-map)
2143 ", "))))
2144 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002145 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002146 keys (if (assq func locals)
2147 (concat
2148 "Local/Global values: "
2149 (prin1-to-string (symbol-value func))
2150 " / "
2151 (prin1-to-string (default-value func)))
2152 (concat
2153 "Value: "
2154 (prin1-to-string (symbol-value func))))))
2155 (t ; unexpected
2156 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002157 (princ (format "\n-> %s:\t%s\t%s\n\n"
2158 (if (equal funckind "c") "Command" "Variable")
2159 funcname keys))
2160 (princ funcdoc)
2161 (terpri)
2162 (setq start end))
2163 (princ (substitute-command-keys (substring str start))))
2164 (print-help-return-message)))
2165
2166(defun py-describe-mode ()
2167 "Dump long form of Python-mode docs."
2168 (interactive)
2169 (py-dump-help-string "Major mode for editing Python files.
2170Knows about Python indentation, tokens, comments and continuation lines.
2171Paragraphs are separated by blank lines only.
2172
2173Major sections below begin with the string `@'; specific function and
2174variable docs begin with `->'.
2175
2176@EXECUTING PYTHON CODE
2177
2178\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2179\\[py-execute-region]\tsends the current region
2180\\[py-shell]\tstarts a Python interpreter window; this will be used by
2181\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2182%c:py-execute-buffer
2183%c:py-execute-region
2184%c:py-shell
2185
2186@VARIABLES
2187
2188py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002189py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002190
2191py-python-command\tshell command to invoke Python interpreter
2192py-scroll-process-buffer\talways scroll Python process buffer
2193py-temp-directory\tdirectory used for temp files (if needed)
2194
2195py-beep-if-tab-change\tring the bell if tab-width is changed
2196%v:py-indent-offset
2197%v:py-block-comment-prefix
2198%v:py-python-command
2199%v:py-scroll-process-buffer
2200%v:py-temp-directory
2201%v:py-beep-if-tab-change
2202
2203@KINDS OF LINES
2204
2205Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002206preceding line ends with a backslash that's not part of a comment, or
2207the paren/bracket/brace nesting level at the start of the line is
2208non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002209
2210An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002211possibly blanks or tabs), a `comment line' (leftmost non-blank
2212character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002213
2214Comment Lines
2215
2216Although all comment lines are treated alike by Python, Python mode
2217recognizes two kinds that act differently with respect to indentation.
2218
2219An `indenting comment line' is a comment line with a blank, tab or
2220nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002221treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002222indenting comment line will be indented like the comment line. All
2223other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002224following the initial `#') are `non-indenting comment lines', and
2225their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226
2227Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002228whenever possible. Non-indenting comment lines are useful in cases
2229like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002230
2231\ta = b # a very wordy single-line comment that ends up being
2232\t #... continued onto another line
2233
2234\tif a == b:
2235##\t\tprint 'panic!' # old code we've `commented out'
2236\t\treturn a
2237
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002238Since the `#...' and `##' comment lines have a non-whitespace
2239character following the initial `#', Python mode ignores them when
2240computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002241
2242Continuation Lines and Statements
2243
2244The Python-mode commands generally work on statements instead of on
2245individual lines, where a `statement' is a comment or blank line, or a
2246code line and all of its following continuation lines (if any)
2247considered as a single logical unit. The commands in this mode
2248generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002249statement containing point, even if point happens to be in the middle
2250of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002251
2252
2253@INDENTATION
2254
2255Primarily for entering new code:
2256\t\\[indent-for-tab-command]\t indent line appropriately
2257\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002258\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002259
2260Primarily for reindenting existing code:
2261\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2262\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2263
2264\t\\[py-indent-region]\t reindent region to match its context
2265\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2266\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2267
2268Unlike most programming languages, Python uses indentation, and only
2269indentation, to specify block structure. Hence the indentation supplied
2270automatically by Python-mode is just an educated guess: only you know
2271the block structure you intend, so only you can supply correct
2272indentation.
2273
2274The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2275the indentation of preceding statements. E.g., assuming
2276py-indent-offset is 4, after you enter
2277\tif a > 0: \\[py-newline-and-indent]
2278the cursor will be moved to the position of the `_' (_ is not a
2279character in the file, it's just used here to indicate the location of
2280the cursor):
2281\tif a > 0:
2282\t _
2283If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2284to
2285\tif a > 0:
2286\t c = d
2287\t _
2288Python-mode cannot know whether that's what you intended, or whether
2289\tif a > 0:
2290\t c = d
2291\t_
2292was your intent. In general, Python-mode either reproduces the
2293indentation of the (closest code or indenting-comment) preceding
2294statement, or adds an extra py-indent-offset blanks if the preceding
2295statement has `:' as its last significant (non-whitespace and non-
2296comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002297\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002298
2299Continuation lines are given extra indentation. If you don't like the
2300suggested indentation, change it to something you do like, and Python-
2301mode will strive to indent later lines of the statement in the same way.
2302
2303If a line is a continuation line by virtue of being in an unclosed
2304paren/bracket/brace structure (`list', for short), the suggested
2305indentation depends on whether the current line contains the first item
2306in the list. If it does, it's indented py-indent-offset columns beyond
2307the indentation of the line containing the open bracket. If you don't
2308like that, change it by hand. The remaining items in the list will mimic
2309whatever indentation you give to the first item.
2310
2311If a line is a continuation line because the line preceding it ends with
2312a backslash, the third and following lines of the statement inherit their
2313indentation from the line preceding them. The indentation of the second
2314line in the statement depends on the form of the first (base) line: if
2315the base line is an assignment statement with anything more interesting
2316than the backslash following the leftmost assigning `=', the second line
2317is indented two columns beyond that `='. Else it's indented to two
2318columns beyond the leftmost solid chunk of non-whitespace characters on
2319the base line.
2320
2321Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2322repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2323structure you intend.
2324%c:indent-for-tab-command
2325%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002326%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002327
2328
2329The next function may be handy when editing code you didn't write:
2330%c:py-guess-indent-offset
2331
2332
2333The remaining `indent' functions apply to a region of Python code. They
2334assume the block structure (equals indentation, in Python) of the region
2335is correct, and alter the indentation in various ways while preserving
2336the block structure:
2337%c:py-indent-region
2338%c:py-shift-region-left
2339%c:py-shift-region-right
2340
2341@MARKING & MANIPULATING REGIONS OF CODE
2342
2343\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002344\\[py-mark-def-or-class]\t mark smallest enclosing def
2345\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002346\\[comment-region]\t comment out region of code
2347\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002348%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002349%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002350%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002351
2352@MOVING POINT
2353
2354\\[py-previous-statement]\t move to statement preceding point
2355\\[py-next-statement]\t move to statement following point
2356\\[py-goto-block-up]\t move up to start of current block
2357\\[beginning-of-python-def-or-class]\t move to start of def
2358\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2359\\[end-of-python-def-or-class]\t move to end of def
2360\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2361
2362The first two move to one statement beyond the statement that contains
2363point. A numeric prefix argument tells them to move that many
2364statements instead. Blank lines, comment lines, and continuation lines
2365do not count as `statements' for these commands. So, e.g., you can go
2366to the first code statement in a file by entering
2367\t\\[beginning-of-buffer]\t to move to the top of the file
2368\t\\[py-next-statement]\t to skip over initial comments and blank lines
2369Or do `\\[py-previous-statement]' with a huge prefix argument.
2370%c:py-previous-statement
2371%c:py-next-statement
2372%c:py-goto-block-up
2373%c:beginning-of-python-def-or-class
2374%c:end-of-python-def-or-class
2375
2376@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2377
2378`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2379
2380`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2381overall class and def structure of a module.
2382
2383`\\[back-to-indentation]' moves point to a line's first non-blank character.
2384
2385`\\[indent-relative]' is handy for creating odd indentation.
2386
2387@OTHER EMACS HINTS
2388
2389If you don't like the default value of a variable, change its value to
2390whatever you do like by putting a `setq' line in your .emacs file.
2391E.g., to set the indentation increment to 4, put this line in your
2392.emacs:
2393\t(setq py-indent-offset 4)
2394To see the value of a variable, do `\\[describe-variable]' and enter the variable
2395name at the prompt.
2396
2397When entering a key sequence like `C-c C-n', it is not necessary to
2398release the CONTROL key after doing the `C-c' part -- it suffices to
2399press the CONTROL key, press and release `c' (while still holding down
2400CONTROL), press and release `n' (while still holding down CONTROL), &
2401then release CONTROL.
2402
2403Entering Python mode calls with no arguments the value of the variable
2404`python-mode-hook', if that value exists and is not nil; for backward
2405compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2406the Elisp manual for details.
2407
2408Obscure: When python-mode is first loaded, it looks for all bindings
2409to newline-and-indent in the global keymap, and shadows them with
2410local bindings to py-newline-and-indent."))
2411
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002412
2413;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002414(defvar py-parse-state-re
2415 (concat
2416 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2417 "\\|"
2418 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002419
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420;; returns the parse state at point (see parse-partial-sexp docs)
2421(defun py-parse-state ()
2422 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002423 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002424 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002425 (while (not done)
2426 ;; back up to the first preceding line (if any; else start of
2427 ;; buffer) that begins with a popular Python keyword, or a
2428 ;; non- whitespace and non-comment character. These are good
2429 ;; places to start parsing to see whether where we started is
2430 ;; at a non-zero nesting level. It may be slow for people who
2431 ;; write huge code blocks or huge lists ... tough beans.
2432 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002433 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002434 (beginning-of-line)
2435 (save-excursion
2436 (setq pps (parse-partial-sexp (point) here)))
2437 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002438 (setq done (or (zerop ci)
2439 (not (nth 3 pps))
2440 (bobp)))
2441 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002442 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002443
2444;; if point is at a non-zero nesting level, returns the number of the
2445;; character that opens the smallest enclosing unclosed list; else
2446;; returns nil.
2447(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002448 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002449 (if (zerop (car status))
2450 nil ; not in a nest
2451 (car (cdr status))))) ; char# of open bracket
2452
2453;; t iff preceding line ends with backslash that's not in a comment
2454(defun py-backslash-continuation-line-p ()
2455 (save-excursion
2456 (beginning-of-line)
2457 (and
2458 ;; use a cheap test first to avoid the regexp if possible
2459 ;; use 'eq' because char-after may return nil
2460 (eq (char-after (- (point) 2)) ?\\ )
2461 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002462 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002463 (looking-at py-continued-re))))
2464
2465;; t iff current line is a continuation line
2466(defun py-continuation-line-p ()
2467 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002468 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002469 (or (py-backslash-continuation-line-p)
2470 (py-nesting-level))))
2471
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002472;; go to initial line of current statement; usually this is the line
2473;; we're on, but if we're on the 2nd or following lines of a
2474;; continuation block, we need to go up to the first line of the
2475;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002476;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002477;; Tricky: We want to avoid quadratic-time behavior for long continued
2478;; blocks, whether of the backslash or open-bracket varieties, or a
2479;; mix of the two. The following manages to do that in the usual
2480;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002481(defun py-goto-initial-line ()
2482 (let ( open-bracket-pos )
2483 (while (py-continuation-line-p)
2484 (beginning-of-line)
2485 (if (py-backslash-continuation-line-p)
2486 (while (py-backslash-continuation-line-p)
2487 (forward-line -1))
2488 ;; else zip out of nested brackets/braces/parens
2489 (while (setq open-bracket-pos (py-nesting-level))
2490 (goto-char open-bracket-pos)))))
2491 (beginning-of-line))
2492
2493;; go to point right beyond final line of current statement; usually
2494;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002495;; statement we need to skip over the continuation lines. Tricky:
2496;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497(defun py-goto-beyond-final-line ()
2498 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002499 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002500 (while (and (py-continuation-line-p)
2501 (not (eobp)))
2502 ;; skip over the backslash flavor
2503 (while (and (py-backslash-continuation-line-p)
2504 (not (eobp)))
2505 (forward-line 1))
2506 ;; if in nest, zip to the end of the nest
2507 (setq state (py-parse-state))
2508 (if (and (not (zerop (car state)))
2509 (not (eobp)))
2510 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002511 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002512 (forward-line 1))))))
2513
2514;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002515;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002516(defun py-statement-opens-block-p ()
2517 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002518 (let ((start (point))
2519 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2520 (searching t)
2521 (answer nil)
2522 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523 (goto-char start)
2524 (while searching
2525 ;; look for a colon with nothing after it except whitespace, and
2526 ;; maybe a comment
2527 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2528 finish t)
2529 (if (eq (point) finish) ; note: no `else' clause; just
2530 ; keep searching if we're not at
2531 ; the end yet
2532 ;; sure looks like it opens a block -- but it might
2533 ;; be in a comment
2534 (progn
2535 (setq searching nil) ; search is done either way
2536 (setq state (parse-partial-sexp start
2537 (match-beginning 0)))
2538 (setq answer (not (nth 4 state)))))
2539 ;; search failed: couldn't find another interesting colon
2540 (setq searching nil)))
2541 answer)))
2542
Barry Warsawf831d811996-07-31 20:42:59 +00002543(defun py-statement-closes-block-p ()
2544 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002545 ;; starts with `return', `raise', `break', `continue', and `pass'.
2546 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002547 (let ((here (point)))
2548 (back-to-indentation)
2549 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002550 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002551 (goto-char here))))
2552
Barry Warsaw7ae77681994-12-12 20:38:05 +00002553;; go to point right beyond final line of block begun by the current
2554;; line. This is the same as where py-goto-beyond-final-line goes
2555;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002556;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002557(defun py-goto-beyond-block ()
2558 (if (py-statement-opens-block-p)
2559 (py-mark-block nil 'just-move)
2560 (py-goto-beyond-final-line)))
2561
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002562;; go to start of first statement (not blank or comment or
2563;; continuation line) at or preceding point. returns t if there is
2564;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002565(defun py-goto-statement-at-or-above ()
2566 (py-goto-initial-line)
2567 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002568 ;; skip back over blank & comment lines
2569 ;; note: will skip a blank or comment line that happens to be
2570 ;; a continuation line too
2571 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2572 (progn (py-goto-initial-line) t)
2573 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002574 t))
2575
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002576;; go to start of first statement (not blank or comment or
2577;; continuation line) following the statement containing point returns
2578;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002579(defun py-goto-statement-below ()
2580 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002581 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002582 (py-goto-beyond-final-line)
2583 (while (and
2584 (looking-at py-blank-or-comment-re)
2585 (not (eobp)))
2586 (forward-line 1))
2587 (if (eobp)
2588 (progn (goto-char start) nil)
2589 t)))
2590
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002591;; go to start of statement, at or preceding point, starting with
2592;; keyword KEY. Skips blank lines and non-indenting comments upward
2593;; first. If that statement starts with KEY, done, else go back to
2594;; first enclosing block starting with KEY. If successful, leaves
2595;; point at the start of the KEY line & returns t. Else leaves point
2596;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002597(defun py-go-up-tree-to-keyword (key)
2598 ;; skip blanks and non-indenting #
2599 (py-goto-initial-line)
2600 (while (and
2601 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2602 (zerop (forward-line -1))) ; go back
2603 nil)
2604 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002605 (let* ((re (concat "[ \t]*" key "\\b"))
2606 (case-fold-search nil) ; let* so looking-at sees this
2607 (found (looking-at re))
2608 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002609 (while (not (or found dead))
2610 (condition-case nil ; in case no enclosing block
2611 (py-goto-block-up 'no-mark)
2612 (error (setq dead t)))
2613 (or dead (setq found (looking-at re))))
2614 (beginning-of-line)
2615 found))
2616
2617;; return string in buffer from start of indentation to end of line;
2618;; prefix "..." if leading whitespace was skipped
2619(defun py-suck-up-leading-text ()
2620 (save-excursion
2621 (back-to-indentation)
2622 (concat
2623 (if (bolp) "" "...")
2624 (buffer-substring (point) (progn (end-of-line) (point))))))
2625
2626;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2627;; as a Lisp symbol; return nil if none
2628(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002629 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002630 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2631 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2632 nil)))
2633
Barry Warsawb3e81d51996-09-04 15:12:42 +00002634(defun py-current-defun ()
2635 ;; tell add-log.el how to find the current function/method/variable
2636 (save-excursion
2637 (if (re-search-backward py-defun-start-re nil t)
2638 (or (match-string 3)
2639 (let ((method (match-string 2)))
2640 (if (and (not (zerop (length (match-string 1))))
2641 (re-search-backward py-class-start-re nil t))
2642 (concat (match-string 1) "." method)
2643 method)))
2644 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002645
2646
Barry Warsawfec75d61995-07-05 23:26:15 +00002647(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002648 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002649
Barry Warsaw850437a1995-03-08 21:50:28 +00002650(defun py-version ()
2651 "Echo the current version of `python-mode' in the minibuffer."
2652 (interactive)
2653 (message "Using `python-mode' version %s" py-version)
2654 (py-keep-region-active))
2655
2656;; only works under Emacs 19
2657;(eval-when-compile
2658; (require 'reporter))
2659
2660(defun py-submit-bug-report (enhancement-p)
2661 "Submit via mail a bug report on `python-mode'.
2662With \\[universal-argument] just submit an enhancement request."
2663 (interactive
2664 (list (not (y-or-n-p
2665 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002666 (let ((reporter-prompt-for-summary-p (if enhancement-p
2667 "(Very) brief summary: "
2668 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002669 (require 'reporter)
2670 (reporter-submit-bug-report
2671 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002672 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002673 ;; varlist
2674 (if enhancement-p nil
2675 '(py-python-command
2676 py-indent-offset
2677 py-block-comment-prefix
2678 py-scroll-process-buffer
2679 py-temp-directory
2680 py-beep-if-tab-change))
2681 nil ;pre-hooks
2682 nil ;post-hooks
2683 "Dear Barry,") ;salutation
2684 (if enhancement-p nil
2685 (set-mark (point))
2686 (insert
2687"Please replace this text with a sufficiently large code sample\n\
2688and an exact recipe so that I can reproduce your problem. Failure\n\
2689to do so may mean a greater delay in fixing your bug.\n\n")
2690 (exchange-point-and-mark)
2691 (py-keep-region-active))))
2692
2693
Barry Warsaw47384781997-11-26 05:27:45 +00002694(defun py-kill-emacs-hook ()
2695 (mapcar #'(lambda (filename)
2696 (py-safe (delete-file filename)))
2697 py-file-queue))
2698
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002699;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002700(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002701
2702
2703
2704(provide 'python-mode)
2705;;; python-mode.el ends here