blob: 0904800a575f3d0119e4e9c572fc62dbb29fcc7e [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 Warsawaffc0ca1997-11-03 16:59:38 +000033;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
34;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000035;; but it is compatible with 19.34 and the current 20 series Emacsen.
36;; By default, in XEmacs when you visit a .py file, it is put in
37;; Python mode. In Emacs, you need to add the following to your
38;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000040;; (autoload 'python-mode "python-mode" "Python editing mode." t)
41;; (setq auto-mode-alist
42;; (cons '("\\.py$" . python-mode) auto-mode-alist))
43;; (setq interpreter-mode-alist
44;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000045;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000046;; Assuming python-mode.el is on your load-path, it will be invoked
47;; when you visit a .py file, or a file with a first line that looks
48;; like:
49;;
50;; #! /usr/bin/env python
51
Barry Warsaw44b72201996-07-05 20:11:35 +000052;; If you want font-lock support for Python source code (a.k.a. syntax
53;; coloring, highlighting), add this to your .emacs file:
54;;
55;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000056;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000057;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000058
Barry Warsawaffc0ca1997-11-03 16:59:38 +000059;; To submit bug reports, use C-c C-b. Please include a complete, but
60;; concise code sample and a recipe for reproducing the bug. Send
61;; suggestions and other comments to python-mode@python.org.
62
63;; When in a Python mode buffer, do a C-h m for more help. It's
64;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000065
Barry Warsaw7b0f5681995-03-08 21:33:04 +000066;; Here's a brief to do list:
67;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000068;; - Better integration with gud-mode for debugging.
69;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000070;; - possibly force indent-tabs-mode == nil, and add a
71;; write-file-hooks that runs untabify on the whole buffer (to work
72;; around potential tab/space mismatch problems). In practice this
73;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000074;; - have py-execute-region on indented code act as if the region is
75;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000076;; - Add a py-goto-error or some such that would scan an exception in
77;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000078
Barry Warsaw7b0f5681995-03-08 21:33:04 +000079;;; Code:
80
Barry Warsawc72c11c1997-08-09 06:42:08 +000081(require 'custom)
82
Barry Warsaw7b0f5681995-03-08 21:33:04 +000083
84;; user definable variables
85;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000086
Barry Warsawc72c11c1997-08-09 06:42:08 +000087(defgroup python nil
88 "Support for the Python programming language, <http://www.python.org/>"
89 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000090
Barry Warsawc72c11c1997-08-09 06:42:08 +000091(defcustom py-python-command "python"
92 "*Shell command used to start Python interpreter."
93 :type 'string
94 :group 'python)
95
96(defcustom py-indent-offset 4
97 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +000098Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +000099when you're editing someone else's Python code."
100 :type 'integer
101 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000102
Barry Warsawc72c11c1997-08-09 06:42:08 +0000103(defcustom py-align-multiline-strings-p t
104 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000105When this flag is non-nil, continuation lines are lined up under the
106preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000107lines are aligned to column zero."
108 :type '(choice (const :tag "Align under preceding line" t)
109 (const :tag "Align to column zero" nil))
110 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000111
Barry Warsawc72c11c1997-08-09 06:42:08 +0000112(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000113 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000114This should follow the convention for non-indenting comment lines so
115that the indentation commands won't get confused (i.e., the string
116should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000117`...' is arbitrary)."
118 :type 'string
119 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000120
Barry Warsawc72c11c1997-08-09 06:42:08 +0000121(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000122 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000123
Barry Warsaw6d627751996-03-06 18:41:38 +0000124When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000125if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000126
127When t, lines that begin with a single `#' are a hint to subsequent
128line indentation. If the previous line is such a comment line (as
129opposed to one that starts with `py-block-comment-prefix'), then it's
130indentation is used as a hint for this line's indentation. Lines that
131begin with `py-block-comment-prefix' are ignored for indentation
132purposes.
133
134When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000135indentation hints, unless the comment character is in column zero."
136 :type '(choice
137 (const :tag "Skip all comment lines (fast)" nil)
138 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000139 (const :tag "Single # `sets' indentation except at column zero"
140 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000141 )
142 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000143
Barry Warsawc72c11c1997-08-09 06:42:08 +0000144(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000145 "*Scroll Python process buffer as output arrives.
146If nil, the Python process buffer acts, with respect to scrolling, like
147Shell-mode buffers normally act. This is surprisingly complicated and
148so won't be explained here; in fact, you can't get the whole story
149without studying the Emacs C code.
150
151If non-nil, the behavior is different in two respects (which are
152slightly inaccurate in the interest of brevity):
153
154 - If the buffer is in a window, and you left point at its end, the
155 window will scroll as new output arrives, and point will move to the
156 buffer's end, even if the window is not the selected window (that
157 being the one the cursor is in). The usual behavior for shell-mode
158 windows is not to scroll, and to leave point where it was, if the
159 buffer is in a window other than the selected window.
160
161 - If the buffer is not visible in any window, and you left point at
162 its end, the buffer will be popped into a window as soon as more
163 output arrives. This is handy if you have a long-running
164 computation and don't want to tie up screen area waiting for the
165 output. The usual behavior for a shell-mode buffer is to stay
166 invisible until you explicitly visit it.
167
168Note the `and if you left point at its end' clauses in both of the
169above: you can `turn off' the special behaviors while output is in
170progress, by visiting the Python buffer and moving point to anywhere
171besides the end. Then the buffer won't scroll, point will remain where
172you leave it, and if you hide the buffer it will stay hidden until you
173visit it again. You can enable and disable the special behaviors as
174often as you like, while output is in progress, by (respectively) moving
175point to, or away from, the end of the buffer.
176
177Warning: If you expect a large amount of output, you'll probably be
178happier setting this option to nil.
179
180Obscure: `End of buffer' above should really say `at or beyond the
181process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000182told <grin>."
183 :type 'boolean
184 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000185
Barry Warsaw516b6201997-08-09 06:43:20 +0000186(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000187 (let ((ok '(lambda (x)
188 (and x
189 (setq x (expand-file-name x)) ; always true
190 (file-directory-p x)
191 (file-writable-p x)
192 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000193 (or (funcall ok (getenv "TMPDIR"))
194 (funcall ok "/usr/tmp")
195 (funcall ok "/tmp")
196 (funcall ok ".")
197 (error
198 "Couldn't find a usable temp directory -- set py-temp-directory")))
199 "*Directory used for temp files created by a *Python* process.
200By default, the first directory from this list that exists and that you
201can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000202/usr/tmp, /tmp, or the current directory."
203 :type 'string
204 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000205
Barry Warsaw516b6201997-08-09 06:43:20 +0000206(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000207 "*Ring the bell if tab-width is changed.
208If a comment of the form
209
210 \t# vi:set tabsize=<number>:
211
212is found before the first code line when the file is entered, and the
213current value of (the general Emacs variable) `tab-width' does not
214equal <number>, `tab-width' is set to <number>, a message saying so is
215displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000216the Emacs bell is also rung as a warning."
217 :type 'boolean
218 :group 'python)
219
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000220(defcustom py-backspace-function 'backward-delete-char-untabify
221 "*Function called by `py-electric-backspace' when deleting backwards."
222 :type 'function
223 :group 'python)
224
225(defcustom py-delete-function 'delete-char
226 "*Function called by `py-electric-delete' when deleting forwards."
227 :type 'function
228 :group 'python)
229
230
Barry Warsawc72c11c1997-08-09 06:42:08 +0000231
232;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
233;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
234
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000235(defconst py-emacs-features
236 (let (features)
237 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
238 ;; the same string.
239 (let ((tmp1 (make-temp-name ""))
240 (tmp2 (make-temp-name "")))
241 (if (string-equal tmp1 tmp2)
242 (push 'broken-temp-names features)))
243 ;; return the features
244 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000245 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000246There are many flavors of Emacs out there, with different levels of
247support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000248
Barry Warsawfb07f401997-02-24 03:37:22 +0000249(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000250 (let ((kw1 (mapconcat 'identity
251 '("and" "assert" "break" "class"
252 "continue" "def" "del" "elif"
253 "else" "except" "exec" "for"
254 "from" "global" "if" "import"
255 "in" "is" "lambda" "not"
256 "or" "pass" "print" "raise"
257 "return" "while"
258 )
259 "\\|"))
260 (kw2 (mapconcat 'identity
261 '("else:" "except:" "finally:" "try:")
262 "\\|"))
263 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000264 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000265 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000266 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
267 ;; block introducing keywords with immediately following colons.
268 ;; Yes "except" is in both lists.
269 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000270 ;; classes
271 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
272 1 font-lock-type-face)
273 ;; functions
274 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
275 1 font-lock-function-name-face)
276 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000277 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000278(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
279
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000280
Barry Warsaw81437461996-08-01 19:48:02 +0000281(defvar imenu-example--python-show-method-args-p nil
282 "*Controls echoing of arguments of functions & methods in the imenu buffer.
283When non-nil, arguments are printed.")
284
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000285(make-variable-buffer-local 'py-indent-offset)
286
Barry Warsaw7ae77681994-12-12 20:38:05 +0000287;; have to bind py-file-queue before installing the kill-emacs hook
288(defvar py-file-queue nil
289 "Queue of Python temp files awaiting execution.
290Currently-active file is at the head of the list.")
291
Barry Warsawc72c11c1997-08-09 06:42:08 +0000292
293;; Constants
294
295;; Regexp matching a Python string literal
296(defconst py-stringlit-re
297 (concat
298 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
299 "\\|" ; or
300 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
301
302;; Regexp matching Python lines that are continued via backslash.
303;; This is tricky because a trailing backslash does not mean
304;; continuation if it's in a comment
305(defconst py-continued-re
306 (concat
307 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
308 "\\\\$"))
309
310;; Regexp matching blank or comment lines.
311(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
312
313;; Regexp matching clauses to be outdented one level.
314(defconst py-outdent-re
315 (concat "\\(" (mapconcat 'identity
316 '("else:"
317 "except\\(\\s +.*\\)?:"
318 "finally:"
319 "elif\\s +.*:")
320 "\\|")
321 "\\)"))
322
323
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000324;; Regexp matching keywords which typically close a block
325(defconst py-block-closing-keywords-re
326 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
327
Barry Warsawc72c11c1997-08-09 06:42:08 +0000328;; Regexp matching lines to not outdent after.
329(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000330 (concat
331 "\\("
332 (mapconcat 'identity
333 (list "try:"
334 "except\\(\\s +.*\\)?:"
335 "while\\s +.*:"
336 "for\\s +.*:"
337 "if\\s +.*:"
338 "elif\\s +.*:"
339 (concat py-block-closing-keywords-re "[ \t\n]")
340 )
341 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000342 "\\)"))
343
344;; Regexp matching a function, method or variable assignment. If you
345;; change this, you probably have to change `py-current-defun' as
346;; well. This is only used by `py-current-defun' to find the name for
347;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000348(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000349 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
350
351;; Regexp for finding a class name. If you change this, you probably
352;; have to change `py-current-defun' as well. This is only used by
353;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000354(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
355
356;; Regexp that describes tracebacks
357(defconst py-traceback-line-re
358 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\), in ")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000359
360
361
362;; Utilities
363
364(defmacro py-safe (&rest body)
365 ;; safely execute BODY, return nil if an error occurred
366 (` (condition-case nil
367 (progn (,@ body))
368 (error nil))))
369
370(defsubst py-keep-region-active ()
371 ;; Do whatever is necessary to keep the region active in XEmacs.
372 ;; Ignore byte-compiler warnings you might see. Also note that
373 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
374 ;; to take explicit action.
375 (and (boundp 'zmacs-region-stays)
376 (setq zmacs-region-stays t)))
377
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000378(defsubst py-point (position)
379 ;; Returns the value of point at certain commonly referenced POSITIONs.
380 ;; POSITION can be one of the following symbols:
381 ;;
382 ;; bol -- beginning of line
383 ;; eol -- end of line
384 ;; bod -- beginning of defun
385 ;; boi -- back to indentation
386 ;;
387 ;; This function does not modify point or mark.
388 (let ((here (point)))
389 (cond
390 ((eq position 'bol) (beginning-of-line))
391 ((eq position 'eol) (end-of-line))
392 ((eq position 'bod) (beginning-of-python-def-or-class))
393 ((eq position 'bob) (beginning-of-buffer))
394 ((eq position 'eob) (end-of-buffer))
395 ((eq position 'boi) (back-to-indentation))
396 (t (error "unknown buffer position requested: %s" position))
397 )
398 (prog1
399 (point)
400 (goto-char here))))
401
402(defsubst py-highlight-line (from to file line)
403 (cond
404 ((fboundp 'make-extent)
405 ;; XEmacs
406 (let ((e (make-extent from to)))
407 (set-extent-property e 'mouse-face 'highlight)
408 (set-extent-property e 'py-exc-info (cons file line))
409 (set-extent-property e 'keymap py-mode-output-map)))
410 (t
411 ;; Emacs -- Please port this!
412 )
413 ))
414
Barry Warsawc72c11c1997-08-09 06:42:08 +0000415
416;; Major mode boilerplate
417
Barry Warsaw7ae77681994-12-12 20:38:05 +0000418;; define a mode-specific abbrev table for those who use such things
419(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000420 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000421(define-abbrev-table 'python-mode-abbrev-table nil)
422
Barry Warsaw7ae77681994-12-12 20:38:05 +0000423(defvar python-mode-hook nil
424 "*Hook called by `python-mode'.")
425
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000426;; in previous version of python-mode.el, the hook was incorrectly
427;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000428(and (fboundp 'make-obsolete-variable)
429 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
430
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000431(defvar py-mode-map ()
432 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000433(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000434 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000435 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000436 ;; electric keys
437 (define-key py-mode-map ":" 'py-electric-colon)
438 ;; indentation level modifiers
439 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
440 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
441 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
442 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
443 ;; subprocess commands
444 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
445 (define-key py-mode-map "\C-c|" 'py-execute-region)
446 (define-key py-mode-map "\C-c!" 'py-shell)
447 ;; Caution! Enter here at your own risk. We are trying to support
448 ;; several behaviors and it gets disgusting. :-( This logic ripped
449 ;; largely from CC Mode.
450 ;;
451 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
452 ;; backwards deletion behavior to DEL, which both Delete and
453 ;; Backspace get translated to. There's no way to separate this
454 ;; behavior in a clean way, so deal with it! Besides, it's been
455 ;; this way since the dawn of time.
456 (if (not (boundp 'delete-key-deletes-forward))
457 (define-key py-mode-map "\177" 'py-electric-backspace)
458 ;; However, XEmacs 20 actually achieved enlightenment. It is
459 ;; possible to sanely define both backward and forward deletion
460 ;; behavior under X separately (TTYs are forever beyond hope, but
461 ;; who cares? XEmacs 20 does the right thing with these too).
462 (define-key py-mode-map [delete] 'py-electric-delete)
463 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw2518c671997-11-05 00:51:08 +0000464 ;; marking interesting locations
465 (define-key py-mode-map "\C-c\C-m" 'py-mark-def-or-class)
466 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000467 ;; Miscellaneous
468 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
469 (define-key py-mode-map "\C-c\t" 'py-indent-region)
470 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
471 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
472 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000473 (define-key py-mode-map "\C-c#" 'py-comment-region)
474 (define-key py-mode-map "\C-c?" 'py-describe-mode)
475 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
476 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
477 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000478 (define-key py-mode-map "\C-c-" 'py-up-exception)
479 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000480 ;; information
481 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
482 (define-key py-mode-map "\C-c\C-v" 'py-version)
483 ;; py-newline-and-indent mappings
484 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000485 ;; shadow global bindings for newline-and-indent w/ the py- version.
486 ;; BAW - this is extremely bad form, but I'm not going to change it
487 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000488 (mapcar #'(lambda (key)
489 (define-key py-mode-map key 'py-newline-and-indent))
490 (where-is-internal 'newline-and-indent))
491 )
492
493(defvar py-mode-output-map nil
494 "Keymap used in *Python Output* buffers*")
495(if py-mode-output-map
496 nil
497 (setq py-mode-output-map (make-sparse-keymap))
498 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
499 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
500 ;; TBD: Disable all self-inserting keys. This is bogus, we should
501 ;; really implement this as *Python Output* buffer being read-only
502 (mapcar #' (lambda (key)
503 (define-key py-mode-output-map key
504 #'(lambda () (interactive) (beep))))
505 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000506 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000507
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000508(defvar py-mode-syntax-table nil
509 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000510(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000511 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000512 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000513 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
514 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
515 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
516 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
517 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
518 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
519 ;; Add operator symbols misassigned in the std table
520 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
521 (modify-syntax-entry ?\% "." py-mode-syntax-table)
522 (modify-syntax-entry ?\& "." py-mode-syntax-table)
523 (modify-syntax-entry ?\* "." py-mode-syntax-table)
524 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
525 (modify-syntax-entry ?\- "." py-mode-syntax-table)
526 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
527 (modify-syntax-entry ?\< "." py-mode-syntax-table)
528 (modify-syntax-entry ?\= "." py-mode-syntax-table)
529 (modify-syntax-entry ?\> "." py-mode-syntax-table)
530 (modify-syntax-entry ?\| "." py-mode-syntax-table)
531 ;; For historical reasons, underscore is word class instead of
532 ;; symbol class. GNU conventions say it should be symbol class, but
533 ;; there's a natural conflict between what major mode authors want
534 ;; and what users expect from `forward-word' and `backward-word'.
535 ;; Guido and I have hashed this out and have decided to keep
536 ;; underscore in word class. If you're tempted to change it, try
537 ;; binding M-f and M-b to py-forward-into-nomenclature and
538 ;; py-backward-into-nomenclature instead.
539 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
540 ;; Both single quote and double quote are string delimiters
541 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
542 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
543 ;; backquote is open and close paren
544 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
545 ;; comment delimiters
546 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
547 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
548 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549
Barry Warsawb3e81d51996-09-04 15:12:42 +0000550
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000551
Barry Warsaw42f707f1996-07-29 21:05:05 +0000552;; Menu definitions, only relevent if you have the easymenu.el package
553;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000554(defvar py-menu nil
555 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000556This menu will get created automatically if you have the `easymenu'
557package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000558
Barry Warsawc72c11c1997-08-09 06:42:08 +0000559(and (py-safe (require 'easymenu) t)
560 (easy-menu-define
561 py-menu py-mode-map "Python Mode menu"
562 '("Python"
563 ["Comment Out Region" py-comment-region (mark)]
564 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
565 "-"
566 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000567 ["Mark current def" py-mark-def-or-class t]
568 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000569 "-"
570 ["Shift region left" py-shift-region-left (mark)]
571 ["Shift region right" py-shift-region-right (mark)]
572 "-"
573 ["Execute buffer" py-execute-buffer t]
574 ["Execute region" py-execute-region (mark)]
575 ["Start interpreter..." py-shell t]
576 "-"
577 ["Go to start of block" py-goto-block-up t]
578 ["Go to start of class" (beginning-of-python-def-or-class t) t]
579 ["Move to end of class" (end-of-python-def-or-class t) t]
580 ["Move to start of def" beginning-of-python-def-or-class t]
581 ["Move to end of def" end-of-python-def-or-class t]
582 "-"
583 ["Describe mode" py-describe-mode t]
584 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000585
Barry Warsaw81437461996-08-01 19:48:02 +0000586
587
588;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
589(defvar imenu-example--python-class-regexp
590 (concat ; <<classes>>
591 "\\(" ;
592 "^[ \t]*" ; newline and maybe whitespace
593 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
594 ; possibly multiple superclasses
595 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
596 "[ \t]*:" ; and the final :
597 "\\)" ; >>classes<<
598 )
599 "Regexp for Python classes for use with the imenu package."
600 )
601
602(defvar imenu-example--python-method-regexp
603 (concat ; <<methods and functions>>
604 "\\(" ;
605 "^[ \t]*" ; new line and maybe whitespace
606 "\\(def[ \t]+" ; function definitions start with def
607 "\\([a-zA-Z0-9_]+\\)" ; name is here
608 ; function arguments...
609 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
610 "\\)" ; end of def
611 "[ \t]*:" ; and then the :
612 "\\)" ; >>methods and functions<<
613 )
614 "Regexp for Python methods/functions for use with the imenu package."
615 )
616
617(defvar imenu-example--python-method-no-arg-parens '(2 8)
618 "Indicies into groups of the Python regexp for use with imenu.
619
620Using these values will result in smaller imenu lists, as arguments to
621functions are not listed.
622
623See the variable `imenu-example--python-show-method-args-p' for more
624information.")
625
626(defvar imenu-example--python-method-arg-parens '(2 7)
627 "Indicies into groups of the Python regexp for use with imenu.
628Using these values will result in large imenu lists, as arguments to
629functions are listed.
630
631See the variable `imenu-example--python-show-method-args-p' for more
632information.")
633
634;; Note that in this format, this variable can still be used with the
635;; imenu--generic-function. Otherwise, there is no real reason to have
636;; it.
637(defvar imenu-example--generic-python-expression
638 (cons
639 (concat
640 imenu-example--python-class-regexp
641 "\\|" ; or...
642 imenu-example--python-method-regexp
643 )
644 imenu-example--python-method-no-arg-parens)
645 "Generic Python expression which may be used directly with imenu.
646Used by setting the variable `imenu-generic-expression' to this value.
647Also, see the function \\[imenu-example--create-python-index] for a
648better alternative for finding the index.")
649
650;; These next two variables are used when searching for the python
651;; class/definitions. Just saving some time in accessing the
652;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000653(defvar imenu-example--python-generic-regexp nil)
654(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000655
656
657;;;###autoload
658(eval-when-compile
659 ;; Imenu isn't used in XEmacs, so just ignore load errors
660 (condition-case ()
661 (progn
662 (require 'cl)
663 (require 'imenu))
664 (error nil)))
665
666(defun imenu-example--create-python-index ()
667 "Python interface function for imenu package.
668Finds all python classes and functions/methods. Calls function
669\\[imenu-example--create-python-index-engine]. See that function for
670the details of how this works."
671 (setq imenu-example--python-generic-regexp
672 (car imenu-example--generic-python-expression))
673 (setq imenu-example--python-generic-parens
674 (if imenu-example--python-show-method-args-p
675 imenu-example--python-method-arg-parens
676 imenu-example--python-method-no-arg-parens))
677 (goto-char (point-min))
678 (imenu-example--create-python-index-engine nil))
679
680(defun imenu-example--create-python-index-engine (&optional start-indent)
681 "Function for finding imenu definitions in Python.
682
683Finds all definitions (classes, methods, or functions) in a Python
684file for the imenu package.
685
686Returns a possibly nested alist of the form
687
688 (INDEX-NAME . INDEX-POSITION)
689
690The second element of the alist may be an alist, producing a nested
691list as in
692
693 (INDEX-NAME . INDEX-ALIST)
694
695This function should not be called directly, as it calls itself
696recursively and requires some setup. Rather this is the engine for
697the function \\[imenu-example--create-python-index].
698
699It works recursively by looking for all definitions at the current
700indention level. When it finds one, it adds it to the alist. If it
701finds a definition at a greater indentation level, it removes the
702previous definition from the alist. In it's place it adds all
703definitions found at the next indentation level. When it finds a
704definition that is less indented then the current level, it retuns the
705alist it has created thus far.
706
707The optional argument START-INDENT indicates the starting indentation
708at which to continue looking for Python classes, methods, or
709functions. If this is not supplied, the function uses the indentation
710of the first definition found."
711 (let ((index-alist '())
712 (sub-method-alist '())
713 looking-p
714 def-name prev-name
715 cur-indent def-pos
716 (class-paren (first imenu-example--python-generic-parens))
717 (def-paren (second imenu-example--python-generic-parens)))
718 (setq looking-p
719 (re-search-forward imenu-example--python-generic-regexp
720 (point-max) t))
721 (while looking-p
722 (save-excursion
723 ;; used to set def-name to this value but generic-extract-name is
724 ;; new to imenu-1.14. this way it still works with imenu-1.11
725 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
726 (let ((cur-paren (if (match-beginning class-paren)
727 class-paren def-paren)))
728 (setq def-name
729 (buffer-substring (match-beginning cur-paren)
730 (match-end cur-paren))))
731 (beginning-of-line)
732 (setq cur-indent (current-indentation)))
733
734 ;; HACK: want to go to the next correct definition location. we
735 ;; explicitly list them here. would be better to have them in a
736 ;; list.
737 (setq def-pos
738 (or (match-beginning class-paren)
739 (match-beginning def-paren)))
740
741 ;; if we don't have a starting indent level, take this one
742 (or start-indent
743 (setq start-indent cur-indent))
744
745 ;; if we don't have class name yet, take this one
746 (or prev-name
747 (setq prev-name def-name))
748
749 ;; what level is the next definition on? must be same, deeper
750 ;; or shallower indentation
751 (cond
752 ;; at the same indent level, add it to the list...
753 ((= start-indent cur-indent)
754
755 ;; if we don't have push, use the following...
756 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
757 (push (cons def-name def-pos) index-alist))
758
759 ;; deeper indented expression, recur...
760 ((< start-indent cur-indent)
761
762 ;; the point is currently on the expression we're supposed to
763 ;; start on, so go back to the last expression. The recursive
764 ;; call will find this place again and add it to the correct
765 ;; list
766 (re-search-backward imenu-example--python-generic-regexp
767 (point-min) 'move)
768 (setq sub-method-alist (imenu-example--create-python-index-engine
769 cur-indent))
770
771 (if sub-method-alist
772 ;; we put the last element on the index-alist on the start
773 ;; of the submethod alist so the user can still get to it.
774 (let ((save-elmt (pop index-alist)))
775 (push (cons (imenu-create-submenu-name prev-name)
776 (cons save-elmt sub-method-alist))
777 index-alist))))
778
779 ;; found less indented expression, we're done.
780 (t
781 (setq looking-p nil)
782 (re-search-backward imenu-example--python-generic-regexp
783 (point-min) t)))
784 (setq prev-name def-name)
785 (and looking-p
786 (setq looking-p
787 (re-search-forward imenu-example--python-generic-regexp
788 (point-max) 'move))))
789 (nreverse index-alist)))
790
Barry Warsaw42f707f1996-07-29 21:05:05 +0000791
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000792;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000793(defun python-mode ()
794 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000795To submit a problem report, enter `\\[py-submit-bug-report]' from a
796`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
797documentation. To see what version of `python-mode' you are running,
798enter `\\[py-version]'.
799
800This mode knows about Python indentation, tokens, comments and
801continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000802
803COMMANDS
804\\{py-mode-map}
805VARIABLES
806
Barry Warsaw42f707f1996-07-29 21:05:05 +0000807py-indent-offset\t\tindentation increment
808py-block-comment-prefix\t\tcomment string used by comment-region
809py-python-command\t\tshell command to invoke Python interpreter
810py-scroll-process-buffer\t\talways scroll Python process buffer
811py-temp-directory\t\tdirectory used for temp files (if needed)
812py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000813 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000814 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000815 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000816 (make-local-variable 'font-lock-defaults)
817 (make-local-variable 'paragraph-separate)
818 (make-local-variable 'paragraph-start)
819 (make-local-variable 'require-final-newline)
820 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000821 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000822 (make-local-variable 'comment-start-skip)
823 (make-local-variable 'comment-column)
824 (make-local-variable 'indent-region-function)
825 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000826 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000827 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000828 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000829 (setq major-mode 'python-mode
830 mode-name "Python"
831 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000832 paragraph-separate "^[ \t]*$"
833 paragraph-start "^[ \t]*$"
834 require-final-newline t
835 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000836 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000837 comment-start-skip "# *"
838 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000839 indent-region-function 'py-indent-region
840 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000841 ;; tell add-log.el how to find the current function/method/variable
842 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000843 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000844 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000845 ;; add the menu
846 (if py-menu
847 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000848 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000849 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000850 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000851 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000852 ;;
853 ;; not sure where the magic comment has to be; to save time
854 ;; searching for a rarity, we give up if it's not found prior to the
855 ;; first executable statement.
856 ;;
857 ;; BAW - on first glance, this seems like complete hackery. Why was
858 ;; this necessary, and is it still necessary?
859 (let ((case-fold-search nil)
860 (start (point))
861 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000862 (if (re-search-forward
863 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
864 (prog2 (py-next-statement 1) (point) (goto-char 1))
865 t)
866 (progn
867 (setq new-tab-width
868 (string-to-int
869 (buffer-substring (match-beginning 1) (match-end 1))))
870 (if (= tab-width new-tab-width)
871 nil
872 (setq tab-width new-tab-width)
873 (message "Caution: tab-width changed to %d" new-tab-width)
874 (if py-beep-if-tab-change (beep)))))
875 (goto-char start))
876
Barry Warsaw755c6711996-08-01 20:02:55 +0000877 ;; install imenu
878 (setq imenu-create-index-function
879 (function imenu-example--create-python-index))
880 (if (fboundp 'imenu-add-to-menubar)
881 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
882
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000883 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000884 (if python-mode-hook
885 (run-hooks 'python-mode-hook)
886 (run-hooks 'py-mode-hook)))
887
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000888
Barry Warsawb91b7431995-03-14 15:55:20 +0000889;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000890(defun py-outdent-p ()
891 ;; returns non-nil if the current line should outdent one level
892 (save-excursion
893 (and (progn (back-to-indentation)
894 (looking-at py-outdent-re))
895 (progn (backward-to-indentation 1)
896 (while (or (looking-at py-blank-or-comment-re)
897 (bobp))
898 (backward-to-indentation 1))
899 (not (looking-at py-no-outdent-re)))
900 )))
901
Barry Warsawb91b7431995-03-14 15:55:20 +0000902(defun py-electric-colon (arg)
903 "Insert a colon.
904In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000905argument is provided, that many colons are inserted non-electrically.
906Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000907 (interactive "P")
908 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000909 ;; are we in a string or comment?
910 (if (save-excursion
911 (let ((pps (parse-partial-sexp (save-excursion
912 (beginning-of-python-def-or-class)
913 (point))
914 (point))))
915 (not (or (nth 3 pps) (nth 4 pps)))))
916 (save-excursion
917 (let ((here (point))
918 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000919 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000920 (if (and (not arg)
921 (py-outdent-p)
922 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000923 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000924 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000925 )
926 (setq outdent py-indent-offset))
927 ;; Don't indent, only outdent. This assumes that any lines that
928 ;; are already outdented relative to py-compute-indentation were
929 ;; put there on purpose. Its highly annoying to have `:' indent
930 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
931 ;; there a better way to determine this???
932 (if (< (current-indentation) indent) nil
933 (goto-char here)
934 (beginning-of-line)
935 (delete-horizontal-space)
936 (indent-to (- indent outdent))
937 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000938
939
Barry Warsawa97a3f31997-11-04 18:47:06 +0000940;; Python subprocess utilities and filters
941(defun py-execute-file (proc filename)
942 ;; Send a properly formatted execfile('FILENAME') to the underlying
943 ;; Python interpreter process FILENAME. Make that process's buffer
944 ;; visible and force display. Also make comint believe the user
945 ;; typed this string so that kill-output-from-shell does The Right
946 ;; Thing.
947 (let ((curbuf (current-buffer))
948 (procbuf (process-buffer proc))
949 (comint-scroll-to-bottom-on-output t)
950 (msg (format "## working on region in file %s...\n" filename))
951 (cmd (format "execfile('%s')\n" filename)))
952 (unwind-protect
953 (progn
954 (set-buffer procbuf)
955 (goto-char (point-max))
956 (move-marker (process-mark proc) (point))
957 (funcall (process-filter proc) proc msg))
958 (set-buffer curbuf))
959 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
961(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000962 (let ((curbuf (current-buffer))
963 (pbuf (process-buffer pyproc))
964 (pmark (process-mark pyproc))
965 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966 ;; make sure we switch to a different buffer at least once. if we
967 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000968 ;; window, and point is before the end, and lots of output is
969 ;; coming at a fast pace, then (a) simple cursor-movement commands
970 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
971 ;; to have a visible effect (the window just doesn't get updated,
972 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
973 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000974 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000975 ;; #b makes no sense to me at all. #a almost makes sense: unless
976 ;; we actually change buffers, set_buffer_internal in buffer.c
977 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
978 ;; seems to make the Emacs command loop reluctant to update the
979 ;; display. Perhaps the default process filter in process.c's
980 ;; read_process_output has update_mode_lines++ for a similar
981 ;; reason? beats me ...
982
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000983 (unwind-protect
984 ;; make sure current buffer is restored
985 ;; BAW - we want to check to see if this still applies
986 (progn
987 ;; mysterious ugly hack
988 (if (eq curbuf pbuf)
989 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000990
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000991 (set-buffer pbuf)
992 (let* ((start (point))
993 (goback (< start pmark))
994 (goend (and (not goback) (= start (point-max))))
995 (buffer-read-only nil))
996 (goto-char pmark)
997 (insert string)
998 (move-marker pmark (point))
999 (setq file-finished
1000 (and py-file-queue
1001 (equal ">>> "
1002 (buffer-substring
1003 (prog2 (beginning-of-line) (point)
1004 (goto-char pmark))
1005 (point)))))
1006 (if goback (goto-char start)
1007 ;; else
1008 (if py-scroll-process-buffer
1009 (let* ((pop-up-windows t)
1010 (pwin (display-buffer pbuf)))
1011 (set-window-point pwin (point)))))
1012 (set-buffer curbuf)
1013 (if file-finished
1014 (progn
1015 (py-delete-file-silently (car py-file-queue))
1016 (setq py-file-queue (cdr py-file-queue))
1017 (if py-file-queue
1018 (py-execute-file pyproc (car py-file-queue)))))
1019 (and goend
1020 (progn (set-buffer pbuf)
1021 (goto-char (point-max))))
1022 ))
1023 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001024
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001025(defun py-postprocess-output-buffer (buf)
1026 (save-excursion
1027 (set-buffer buf)
1028 (beginning-of-buffer)
1029 (while (re-search-forward py-traceback-line-re nil t)
1030 (let ((file (match-string 1))
1031 (line (string-to-int (match-string 2))))
1032 (py-highlight-line (py-point 'bol) (py-point 'eol) file line))
1033 )))
1034
Barry Warsawa97a3f31997-11-04 18:47:06 +00001035
1036;;; Subprocess commands
1037
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001038;; only used when (memq 'broken-temp-names py-emacs-features)
1039(defvar py-serial-number 0)
1040(defvar py-exception-buffer nil)
1041(defconst py-output-buffer "*Python Output*")
1042
Barry Warsawa97a3f31997-11-04 18:47:06 +00001043;;;###autoload
1044(defun py-shell ()
1045 "Start an interactive Python interpreter in another window.
1046This is like Shell mode, except that Python is running in the window
1047instead of a shell. See the `Interactive Shell' and `Shell Mode'
1048sections of the Emacs manual for details, especially for the key
1049bindings active in the `*Python*' buffer.
1050
1051See the docs for variable `py-scroll-buffer' for info on scrolling
1052behavior in the process window.
1053
1054Warning: Don't use an interactive Python if you change sys.ps1 or
1055sys.ps2 from their default values, or if you're running code that
1056prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1057distinguish your output from Python's output, and assumes that `>>> '
1058at the start of a line is a prompt from Python. Similarly, the Emacs
1059Shell mode code assumes that both `>>> ' and `... ' at the start of a
1060line are Python prompts. Bad things can happen if you fool either
1061mode.
1062
1063Warning: If you do any editing *in* the process buffer *while* the
1064buffer is accepting output from Python, do NOT attempt to `undo' the
1065changes. Some of the output (nowhere near the parts you changed!) may
1066be lost if you do. This appears to be an Emacs bug, an unfortunate
1067interaction between undo and process filters; the same problem exists in
1068non-Python process buffers using the default (Emacs-supplied) process
1069filter."
1070 ;; BAW - should undo be disabled in the python process buffer, if
1071 ;; this bug still exists?
1072 (interactive)
1073 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001074 (switch-to-buffer-other-window
1075 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001076 (make-local-variable 'comint-prompt-regexp)
1077 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1078 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1079 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001080 ;; set up keybindings for this subshell
1081 (local-set-key [tab] 'self-insert-command)
1082 (local-set-key "\C-c-" 'py-up-exception)
1083 (local-set-key "\C-c=" 'py-down-exception)
1084 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001085
Barry Warsawa97a3f31997-11-04 18:47:06 +00001086(defun py-clear-queue ()
1087 "Clear the queue of temporary files waiting to execute."
1088 (interactive)
1089 (let ((n (length py-file-queue)))
1090 (mapcar 'delete-file py-file-queue)
1091 (setq py-file-queue nil)
1092 (message "%d pending files de-queued." n)))
1093
1094(defun py-execute-region (start end &optional async)
1095 "Execute the the region in a Python interpreter.
1096The region is first copied into a temporary file (in the directory
1097`py-temp-directory'). If there is no Python interpreter shell
1098running, this file is executed synchronously using
1099`shell-command-on-region'. If the program is long running, use an
1100optional \\[universal-argument] to run the command asynchronously in
1101its own buffer.
1102
1103If the Python interpreter shell is running, the region is execfile()'d
1104in that shell. If you try to execute regions too quickly,
1105`python-mode' will queue them up and execute them one at a time when
1106it sees a `>>> ' prompt from Python. Each time this happens, the
1107process buffer is popped into a window (if it's not already in some
1108window) so you can see it, and a comment of the form
1109
1110 \t## working on region in file <name>...
1111
1112is inserted at the end. See also the command `py-clear-queue'."
1113 (interactive "r\nP")
1114 (or (< start end)
1115 (error "Region is empty"))
1116 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001117 (temp (if (memq 'broken-temp-names py-emacs-features)
1118 (prog1
1119 (format "python-%d" py-serial-number)
1120 (setq py-serial-number (1+ py-serial-number)))
1121 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001122 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001123 (write-region start end file nil 'nomsg)
1124 (cond
1125 ;; always run the code in it's own asynchronous subprocess
1126 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001127 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001128 (start-process "Python" buf py-python-command "-u" file)
1129 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001130 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001131 ))
1132 ;; if the Python interpreter shell is running, queue it up for
1133 ;; execution there.
1134 (proc
1135 ;; use the existing python shell
1136 (if (not py-file-queue)
1137 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001138 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001139 (push file py-file-queue)
1140 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001141 (t
1142 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001143 (shell-command-on-region start end py-python-command py-output-buffer)
1144 (setq py-exception-buffer (current-buffer))
1145 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001146 ))))
1147
1148;; Code execution command
1149(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150 "Send the contents of the buffer to a Python interpreter.
1151If there is a *Python* process buffer it is used. If a clipping
1152restriction is in effect, only the accessible portion of the buffer is
1153sent. A trailing newline will be supplied if needed.
1154
1155See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001156 (interactive "P")
1157 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001158
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001159
1160
1161(defun py-jump-to-exception (file line)
1162 (let ((buffer (cond ((string-equal file "<stdin>")
1163 py-exception-buffer)
1164 ((and (consp py-exception-buffer)
1165 (string-equal file (car py-exception-buffer)))
1166 (cdr py-exception-buffer))
1167 ((py-safe (find-file-noselect file)))
1168 ;; could not figure out what file the exception
1169 ;; is pointing to, so prompt for it
1170 (t (find-file (read-file-name "Exception file: "
1171 nil
1172 file t))))))
1173 (pop-to-buffer buffer)
1174 (goto-line line)
1175 (message "Jumping to exception in file %s on line %d" file line)))
1176
1177(defun py-mouseto-exception (event)
1178 (interactive "e")
1179 (cond
1180 ((fboundp 'event-point)
1181 ;; XEmacs
1182 (let* ((point (event-point event))
1183 (buffer (event-buffer event))
1184 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1185 (info (and e (extent-property e 'py-exc-info))))
1186 (message "Event point: %d, info: %s" point info)
1187 (and info
1188 (py-jump-to-exception (car info) (cdr info)))
1189 ))
1190 ;; Emacs -- Please port this!
1191 ))
1192
1193(defun py-goto-exception ()
1194 "Go to the line indicated by the traceback."
1195 (interactive)
1196 (let (file line)
1197 (save-excursion
1198 (beginning-of-line)
1199 (if (looking-at py-traceback-line-re)
1200 (setq file (match-string 1)
1201 line (string-to-int (match-string 2)))))
1202 (if (not file)
1203 (error "Not on a traceback line."))
1204 (py-jump-to-exception file line)))
1205
1206(defun py-find-next-exception (start buffer searchdir errwhere)
1207 ;; Go to start position in buffer, search in the specified
1208 ;; direction, and jump to the exception found. If at the end of the
1209 ;; exception, print error message
1210 (let (file line)
1211 (save-excursion
1212 (set-buffer buffer)
1213 (goto-char (py-point start))
1214 (if (funcall searchdir py-traceback-line-re nil t)
1215 (setq file (match-string 1)
1216 line (string-to-int (match-string 2)))))
1217 (if (and file line)
1218 (py-jump-to-exception file line)
1219 (error "%s of traceback" errwhere))))
1220
1221(defun py-down-exception (&optional bottom)
1222 "Go to the next line down in the traceback.
1223With optional \\[universal-argument], jump to the bottom (innermost)
1224exception in the exception stack."
1225 (interactive "P")
1226 (let* ((proc (get-process "Python"))
1227 (buffer (if proc "*Python*" py-output-buffer)))
1228 (if bottom
1229 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1230 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1231
1232(defun py-up-exception (&optional top)
1233 "Go to the previous line up in the traceback.
1234With optional \\[universal-argument], jump to the top (outermost)
1235exception in the exception stack."
1236 (interactive "P")
1237 (let* ((proc (get-process "Python"))
1238 (buffer (if proc "*Python*" py-output-buffer)))
1239 (if top
1240 (py-find-next-exception 'bob buffer 're-search-forward "Top")
1241 (py-find-next-exception 'boi buffer 're-search-backward "Top"))))
1242
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001243
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001244;; Electric deletion
1245(defun py-electric-backspace (arg)
1246 "Deletes preceding character or levels of indentation.
1247Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001248with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001249
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001250If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001251
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001252Otherwise, if point is at the leftmost non-whitespace character of a
1253line that is neither a continuation line nor a non-indenting comment
1254line, or if point is at the end of a blank line, this command reduces
1255the indentation to match that of the line that opened the current
1256block of code. The line that opened the block is displayed in the
1257echo area to help you keep track of where you are. With numeric arg,
1258outdents that many blocks (but not past column zero).
1259
1260Otherwise the preceding character is deleted, converting a tab to
1261spaces if needed so that only a single column position is deleted.
1262Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001263 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001264 (if (or (/= (current-indentation) (current-column))
1265 (bolp)
1266 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001267 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001268 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001269 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001270 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001271 ;; force non-blank so py-goto-block-up doesn't ignore it
1272 (insert-char ?* 1)
1273 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001274 (let ((base-indent 0) ; indentation of base line
1275 (base-text "") ; and text of base line
1276 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001277 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001278 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001279 (condition-case nil ; in case no enclosing block
1280 (progn
1281 (py-goto-block-up 'no-mark)
1282 (setq base-indent (current-indentation)
1283 base-text (py-suck-up-leading-text)
1284 base-found-p t))
1285 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001286 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001287 (delete-char 1) ; toss the dummy character
1288 (delete-horizontal-space)
1289 (indent-to base-indent)
1290 (if base-found-p
1291 (message "Closes block: %s" base-text)))))
1292
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001293
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001294(defun py-electric-delete (arg)
1295 "Deletes preceding or following character or levels of whitespace.
1296
1297The behavior of this function depends on the variable
1298`delete-key-deletes-forward'. If this variable is nil (or does not
1299exist, as in older Emacsen), then this function behaves identical to
1300\\[c-electric-backspace].
1301
1302If `delete-key-deletes-forward' is non-nil and is supported in your
1303Emacs, then deletion occurs in the forward direction, by calling the
1304function in `py-delete-function'."
1305 (interactive "*p")
1306 (if (and (boundp 'delete-key-deletes-forward)
1307 delete-key-deletes-forward)
1308 (funcall py-delete-function arg)
1309 ;; else
1310 (py-electric-backspace arg)))
1311
1312;; required for pending-del and delsel modes
1313(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1314(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1315(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1316(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1317
1318
1319
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001320(defun py-indent-line (&optional arg)
1321 "Fix the indentation of the current line according to Python rules.
1322With \\[universal-argument], ignore outdenting rules for block
1323closing statements (e.g. return, raise, break, continue, pass)
1324
1325This function is normally bound to `indent-line-function' so
1326\\[indent-for-tab-command] will call it."
1327 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001328 (let* ((ci (current-indentation))
1329 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001330 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001331 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001332 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001333 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001334 (if (/= ci need)
1335 (save-excursion
1336 (beginning-of-line)
1337 (delete-horizontal-space)
1338 (indent-to need)))
1339 (if move-to-indentation-p (back-to-indentation))))
1340
1341(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001342 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001343This is just `strives to' because correct indentation can't be computed
1344from scratch for Python code. In general, deletes the whitespace before
1345point, inserts a newline, and takes an educated guess as to how you want
1346the new line indented."
1347 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001349 (if (< ci (current-column)) ; if point beyond indentation
1350 (newline-and-indent)
1351 ;; else try to act like newline-and-indent "normally" acts
1352 (beginning-of-line)
1353 (insert-char ?\n 1)
1354 (move-to-column ci))))
1355
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001356(defun py-compute-indentation (honor-block-close-p)
1357 ;; implements all the rules for indentation computation. when
1358 ;; honor-block-close-p is non-nil, statements such as return, raise,
1359 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001360 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001361 (let* ((bod (py-point 'bod))
1362 (pps (parse-partial-sexp bod (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001363 (beginning-of-line)
1364 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001365 ;; are we inside a multi-line string or comment?
1366 ((or (and (nth 3 pps)
1367 (nth 3 (parse-partial-sexp bod (py-point 'boi))))
1368 (nth 4 pps))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001369 (save-excursion
1370 (if (not py-align-multiline-strings-p) 0
1371 ;; skip back over blank & non-indenting comment lines
1372 ;; note: will skip a blank or non-indenting comment line
1373 ;; that happens to be a continuation line too
1374 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1375 (back-to-indentation)
1376 (current-column))))
1377 ;; are we on a continuation line?
1378 ((py-continuation-line-p)
1379 (let ((startpos (point))
1380 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001381 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001382 (if open-bracket-pos
1383 (progn
1384 ;; align with first item in list; else a normal
1385 ;; indent beyond the line with the open bracket
1386 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1387 ;; is the first list item on the same line?
1388 (skip-chars-forward " \t")
1389 (if (null (memq (following-char) '(?\n ?# ?\\)))
1390 ; yes, so line up with it
1391 (current-column)
1392 ;; first list item on another line, or doesn't exist yet
1393 (forward-line 1)
1394 (while (and (< (point) startpos)
1395 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1396 (forward-line 1))
1397 (if (< (point) startpos)
1398 ;; again mimic the first list item
1399 (current-indentation)
1400 ;; else they're about to enter the first item
1401 (goto-char open-bracket-pos)
1402 (+ (current-indentation) py-indent-offset))))
1403
1404 ;; else on backslash continuation line
1405 (forward-line -1)
1406 (if (py-continuation-line-p) ; on at least 3rd line in block
1407 (current-indentation) ; so just continue the pattern
1408 ;; else started on 2nd line in block, so indent more.
1409 ;; if base line is an assignment with a start on a RHS,
1410 ;; indent to 2 beyond the leftmost "="; else skip first
1411 ;; chunk of non-whitespace characters on base line, + 1 more
1412 ;; column
1413 (end-of-line)
1414 (setq endpos (point) searching t)
1415 (back-to-indentation)
1416 (setq startpos (point))
1417 ;; look at all "=" from left to right, stopping at first
1418 ;; one not nested in a list or string
1419 (while searching
1420 (skip-chars-forward "^=" endpos)
1421 (if (= (point) endpos)
1422 (setq searching nil)
1423 (forward-char 1)
1424 (setq state (parse-partial-sexp startpos (point)))
1425 (if (and (zerop (car state)) ; not in a bracket
1426 (null (nth 3 state))) ; & not in a string
1427 (progn
1428 (setq searching nil) ; done searching in any case
1429 (setq found
1430 (not (or
1431 (eq (following-char) ?=)
1432 (memq (char-after (- (point) 2))
1433 '(?< ?> ?!)))))))))
1434 (if (or (not found) ; not an assignment
1435 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1436 (progn
1437 (goto-char startpos)
1438 (skip-chars-forward "^ \t\n")))
1439 (1+ (current-column))))))
1440
1441 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001442 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001443
Barry Warsawa7891711996-08-01 15:53:09 +00001444 ;; Dfn: "Indenting comment line". A line containing only a
1445 ;; comment, but which is treated like a statement for
1446 ;; indentation calculation purposes. Such lines are only
1447 ;; treated specially by the mode; they are not treated
1448 ;; specially by the Python interpreter.
1449
1450 ;; The rules for indenting comment lines are a line where:
1451 ;; - the first non-whitespace character is `#', and
1452 ;; - the character following the `#' is whitespace, and
1453 ;; - the line is outdented with respect to (i.e. to the left
1454 ;; of) the indentation of the preceding non-blank line.
1455
1456 ;; The first non-blank line following an indenting comment
1457 ;; line is given the same amount of indentation as the
1458 ;; indenting comment line.
1459
1460 ;; All other comment-only lines are ignored for indentation
1461 ;; purposes.
1462
1463 ;; Are we looking at a comment-only line which is *not* an
1464 ;; indenting comment line? If so, we assume that its been
1465 ;; placed at the desired indentation, so leave it alone.
1466 ;; Indenting comment lines are aligned as statements down
1467 ;; below.
1468 ((and (looking-at "[ \t]*#[^ \t\n]")
1469 ;; NOTE: this test will not be performed in older Emacsen
1470 (fboundp 'forward-comment)
1471 (<= (current-indentation)
1472 (save-excursion
1473 (forward-comment (- (point-max)))
1474 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001475 (current-indentation))
1476
1477 ;; else indentation based on that of the statement that
1478 ;; precedes us; use the first line of that statement to
1479 ;; establish the base, in case the user forced a non-std
1480 ;; indentation for the continuation lines (if any)
1481 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001482 ;; skip back over blank & non-indenting comment lines note:
1483 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001484 ;; happens to be a continuation line too. use fast Emacs 19
1485 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001486 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001487 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001488 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001489 (let (done)
1490 (while (not done)
1491 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1492 nil 'move)
1493 (setq done (or (eq py-honor-comment-indentation t)
1494 (bobp)
1495 (/= (following-char) ?#)
1496 (not (zerop (current-column)))))
1497 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001498 ;; if we landed inside a string, go to the beginning of that
1499 ;; string. this handles triple quoted, multi-line spanning
1500 ;; strings.
1501 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001502 (+ (current-indentation)
1503 (if (py-statement-opens-block-p)
1504 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001505 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001506 (- py-indent-offset)
1507 0)))
1508 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001509
1510(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001511 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001512By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001513`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001514Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001515`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001516their own buffer-local copy), both those currently existing and those
1517created later in the Emacs session.
1518
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001519Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001520There's no excuse for such foolishness, but sometimes you have to deal
1521with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001522`py-indent-offset' to what it thinks it was when they created the
1523mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001524
1525Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001526looking for a line that opens a block of code. `py-indent-offset' is
1527set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001528statement following it. If the search doesn't succeed going forward,
1529it's tried again going backward."
1530 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531 (let (new-value
1532 (start (point))
1533 restart
1534 (found nil)
1535 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536 (py-goto-initial-line)
1537 (while (not (or found (eobp)))
1538 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1539 (progn
1540 (setq restart (point))
1541 (py-goto-initial-line)
1542 (if (py-statement-opens-block-p)
1543 (setq found t)
1544 (goto-char restart)))))
1545 (if found
1546 ()
1547 (goto-char start)
1548 (py-goto-initial-line)
1549 (while (not (or found (bobp)))
1550 (setq found
1551 (and
1552 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1553 (or (py-goto-initial-line) t) ; always true -- side effect
1554 (py-statement-opens-block-p)))))
1555 (setq colon-indent (current-indentation)
1556 found (and found (zerop (py-next-statement 1)))
1557 new-value (- (current-indentation) colon-indent))
1558 (goto-char start)
1559 (if found
1560 (progn
1561 (funcall (if global 'kill-local-variable 'make-local-variable)
1562 'py-indent-offset)
1563 (setq py-indent-offset new-value)
1564 (message "%s value of py-indent-offset set to %d"
1565 (if global "Global" "Local")
1566 py-indent-offset))
1567 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1568
1569(defun py-shift-region (start end count)
1570 (save-excursion
1571 (goto-char end) (beginning-of-line) (setq end (point))
1572 (goto-char start) (beginning-of-line) (setq start (point))
1573 (indent-rigidly start end count)))
1574
1575(defun py-shift-region-left (start end &optional count)
1576 "Shift region of Python code to the left.
1577The lines from the line containing the start of the current region up
1578to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001580
1581If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001582many columns. With no active region, outdent only the current line.
1583You cannot outdent the region if any line is already at column zero."
1584 (interactive
1585 (let ((p (point))
1586 (m (mark))
1587 (arg current-prefix-arg))
1588 (if m
1589 (list (min p m) (max p m) arg)
1590 (list p (save-excursion (forward-line 1) (point)) arg))))
1591 ;; if any line is at column zero, don't shift the region
1592 (save-excursion
1593 (goto-char start)
1594 (while (< (point) end)
1595 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001596 (if (and (zerop (current-column))
1597 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001598 (error "Region is at left edge."))
1599 (forward-line 1)))
1600 (py-shift-region start end (- (prefix-numeric-value
1601 (or count py-indent-offset))))
1602 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001603
1604(defun py-shift-region-right (start end &optional count)
1605 "Shift region of Python code to the right.
1606The lines from the line containing the start of the current region up
1607to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001608shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001609
1610If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001611many columns. With no active region, indent only the current line."
1612 (interactive
1613 (let ((p (point))
1614 (m (mark))
1615 (arg current-prefix-arg))
1616 (if m
1617 (list (min p m) (max p m) arg)
1618 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001619 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001620 (or count py-indent-offset)))
1621 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001622
1623(defun py-indent-region (start end &optional indent-offset)
1624 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001625
Barry Warsaw7ae77681994-12-12 20:38:05 +00001626The lines from the line containing the start of the current region up
1627to (but not including) the line containing the end of the region are
1628reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001629character in the first column, the first line is left alone and the
1630rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001631region is reindented with respect to the (closest code or indenting
1632comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001633
1634This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001635control structures are introduced or removed, or to reformat code
1636using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637
1638If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001639the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001640used.
1641
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001642Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001643is called! This function does not compute proper indentation from
1644scratch (that's impossible in Python), it merely adjusts the existing
1645indentation to be correct in context.
1646
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001647Warning: This function really has no idea what to do with
1648non-indenting comment lines, and shifts them as if they were indenting
1649comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001650
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001651Special cases: whitespace is deleted from blank lines; continuation
1652lines are shifted by the same amount their initial line was shifted,
1653in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001655 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656 (save-excursion
1657 (goto-char end) (beginning-of-line) (setq end (point-marker))
1658 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659 (let ((py-indent-offset (prefix-numeric-value
1660 (or indent-offset py-indent-offset)))
1661 (indents '(-1)) ; stack of active indent levels
1662 (target-column 0) ; column to which to indent
1663 (base-shifted-by 0) ; amount last base line was shifted
1664 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001665 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666 0))
1667 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001668 (while (< (point) end)
1669 (setq ci (current-indentation))
1670 ;; figure out appropriate target column
1671 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001672 ((or (eq (following-char) ?#) ; comment in column 1
1673 (looking-at "[ \t]*$")) ; entirely blank
1674 (setq target-column 0))
1675 ((py-continuation-line-p) ; shift relative to base line
1676 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001677 (t ; new base line
1678 (if (> ci (car indents)) ; going deeper; push it
1679 (setq indents (cons ci indents))
1680 ;; else we should have seen this indent before
1681 (setq indents (memq ci indents)) ; pop deeper indents
1682 (if (null indents)
1683 (error "Bad indentation in region, at line %d"
1684 (save-restriction
1685 (widen)
1686 (1+ (count-lines 1 (point)))))))
1687 (setq target-column (+ indent-base
1688 (* py-indent-offset
1689 (- (length indents) 2))))
1690 (setq base-shifted-by (- target-column ci))))
1691 ;; shift as needed
1692 (if (/= ci target-column)
1693 (progn
1694 (delete-horizontal-space)
1695 (indent-to target-column)))
1696 (forward-line 1))))
1697 (set-marker end nil))
1698
Barry Warsawa7891711996-08-01 15:53:09 +00001699(defun py-comment-region (beg end &optional arg)
1700 "Like `comment-region' but uses double hash (`#') comment starter."
1701 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001702 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001703 (comment-region beg end arg)))
1704
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001705
1706;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001707(defun py-previous-statement (count)
1708 "Go to the start of previous Python statement.
1709If the statement at point is the i'th Python statement, goes to the
1710start of statement i-COUNT. If there is no such statement, goes to the
1711first statement. Returns count of statements left to move.
1712`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001713 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001714 (if (< count 0) (py-next-statement (- count))
1715 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001716 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001717 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001718 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001719 (> count 0)
1720 (zerop (forward-line -1))
1721 (py-goto-statement-at-or-above))
1722 (setq count (1- count)))
1723 (if (> count 0) (goto-char start)))
1724 count))
1725
1726(defun py-next-statement (count)
1727 "Go to the start of next Python statement.
1728If the statement at point is the i'th Python statement, goes to the
1729start of statement i+COUNT. If there is no such statement, goes to the
1730last statement. Returns count of statements left to move. `Statements'
1731do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001732 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001733 (if (< count 0) (py-previous-statement (- count))
1734 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001735 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001736 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001737 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738 (> count 0)
1739 (py-goto-statement-below))
1740 (setq count (1- count)))
1741 (if (> count 0) (goto-char start)))
1742 count))
1743
1744(defun py-goto-block-up (&optional nomark)
1745 "Move up to start of current block.
1746Go to the statement that starts the smallest enclosing block; roughly
1747speaking, this will be the closest preceding statement that ends with a
1748colon and is indented less than the statement you started on. If
1749successful, also sets the mark to the starting point.
1750
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751`\\[py-mark-block]' can be used afterward to mark the whole code
1752block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001753
1754If called from a program, the mark will not be set if optional argument
1755NOMARK is not nil."
1756 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757 (let ((start (point))
1758 (found nil)
1759 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760 (py-goto-initial-line)
1761 ;; if on blank or non-indenting comment line, use the preceding stmt
1762 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1763 (progn
1764 (py-goto-statement-at-or-above)
1765 (setq found (py-statement-opens-block-p))))
1766 ;; search back for colon line indented less
1767 (setq initial-indent (current-indentation))
1768 (if (zerop initial-indent)
1769 ;; force fast exit
1770 (goto-char (point-min)))
1771 (while (not (or found (bobp)))
1772 (setq found
1773 (and
1774 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1775 (or (py-goto-initial-line) t) ; always true -- side effect
1776 (< (current-indentation) initial-indent)
1777 (py-statement-opens-block-p))))
1778 (if found
1779 (progn
1780 (or nomark (push-mark start))
1781 (back-to-indentation))
1782 (goto-char start)
1783 (error "Enclosing block not found"))))
1784
1785(defun beginning-of-python-def-or-class (&optional class)
1786 "Move point to start of def (or class, with prefix arg).
1787
1788Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789arg, looks for a `class' instead. The docs assume the `def' case;
1790just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792If point is in a def statement already, and after the `d', simply
1793moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001794
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001795Else (point is not in a def statement, or at or before the `d' of a
1796def statement), searches for the closest preceding def statement, and
1797leaves point at its start. If no such statement can be found, leaves
1798point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001799
1800Returns t iff a def statement is found by these rules.
1801
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001802Note that doing this command repeatedly will take you closer to the
1803start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001804
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001805If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001806`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001807 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001808 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1809 (start-of-line (progn (beginning-of-line) (point)))
1810 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811 (if (or (/= start-of-stmt start-of-line)
1812 (not at-or-before-p))
1813 (end-of-line)) ; OK to match on this line
1814 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001816
1817(defun end-of-python-def-or-class (&optional class)
1818 "Move point beyond end of def (or class, with prefix arg) body.
1819
1820By default, looks for an appropriate `def'. If you supply a prefix arg,
1821looks for a `class' instead. The docs assume the `def' case; just
1822substitute `class' for `def' for the other case.
1823
1824If point is in a def statement already, this is the def we use.
1825
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001826Else if the def found by `\\[beginning-of-python-def-or-class]'
1827contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828
1829Else we search forward for the closest following def, and use that.
1830
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001831If a def can be found by these rules, point is moved to the start of
1832the line immediately following the def block, and the position of the
1833start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
1835Else point is moved to the end of the buffer, and nil is returned.
1836
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837Note that doing this command repeatedly will take you closer to the
1838end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001841`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843 (let ((start (progn (py-goto-initial-line) (point)))
1844 (which (if class "class" "def"))
1845 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846 ;; move point to start of appropriate def/class
1847 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1848 (setq state 'at-beginning)
1849 ;; else see if beginning-of-python-def-or-class hits container
1850 (if (and (beginning-of-python-def-or-class class)
1851 (progn (py-goto-beyond-block)
1852 (> (point) start)))
1853 (setq state 'at-end)
1854 ;; else search forward
1855 (goto-char start)
1856 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1857 (progn (setq state 'at-beginning)
1858 (beginning-of-line)))))
1859 (cond
1860 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1861 ((eq state 'at-end) t)
1862 ((eq state 'not-found) nil)
1863 (t (error "internal error in end-of-python-def-or-class")))))
1864
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865
1866;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001867(defun py-mark-block (&optional extend just-move)
1868 "Mark following block of lines. With prefix arg, mark structure.
1869Easier to use than explain. It sets the region to an `interesting'
1870block of succeeding lines. If point is on a blank line, it goes down to
1871the next non-blank line. That will be the start of the region. The end
1872of the region depends on the kind of line at the start:
1873
1874 - If a comment, the region will include all succeeding comment lines up
1875 to (but not including) the next non-comment line (if any).
1876
1877 - Else if a prefix arg is given, and the line begins one of these
1878 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001879
1880 if elif else try except finally for while def class
1881
Barry Warsaw7ae77681994-12-12 20:38:05 +00001882 the region will be set to the body of the structure, including
1883 following blocks that `belong' to it, but excluding trailing blank
1884 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885 and all (if any) of the following `except' and `finally' blocks
1886 that belong to the `try' structure will be in the region. Ditto
1887 for if/elif/else, for/else and while/else structures, and (a bit
1888 degenerate, since they're always one-block structures) def and
1889 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001890
1891 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892 block (see list above), and the block is not a `one-liner' (i.e.,
1893 the statement ends with a colon, not with code), the region will
1894 include all succeeding lines up to (but not including) the next
1895 code statement (if any) that's indented no more than the starting
1896 line, except that trailing blank and comment lines are excluded.
1897 E.g., if the starting line begins a multi-statement `def'
1898 structure, the region will be set to the full function definition,
1899 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001900
1901 - Else the region will include all succeeding lines up to (but not
1902 including) the next blank line, or code or indenting-comment line
1903 indented strictly less than the starting line. Trailing indenting
1904 comment lines are included in this case, but not trailing blank
1905 lines.
1906
1907A msg identifying the location of the mark is displayed in the echo
1908area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1909
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001910If called from a program, optional argument EXTEND plays the role of
1911the prefix arg, and if optional argument JUST-MOVE is not nil, just
1912moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001913 (interactive "P") ; raw prefix arg
1914 (py-goto-initial-line)
1915 ;; skip over blank lines
1916 (while (and
1917 (looking-at "[ \t]*$") ; while blank line
1918 (not (eobp))) ; & somewhere to go
1919 (forward-line 1))
1920 (if (eobp)
1921 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001922 (let ((initial-pos (point))
1923 (initial-indent (current-indentation))
1924 last-pos ; position of last stmt in region
1925 (followers
1926 '((if elif else) (elif elif else) (else)
1927 (try except finally) (except except) (finally)
1928 (for else) (while else)
1929 (def) (class) ) )
1930 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001931
1932 (cond
1933 ;; if comment line, suck up the following comment lines
1934 ((looking-at "[ \t]*#")
1935 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1936 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1937 (setq last-pos (point)))
1938
1939 ;; else if line is a block line and EXTEND given, suck up
1940 ;; the whole structure
1941 ((and extend
1942 (setq first-symbol (py-suck-up-first-keyword) )
1943 (assq first-symbol followers))
1944 (while (and
1945 (or (py-goto-beyond-block) t) ; side effect
1946 (forward-line -1) ; side effect
1947 (setq last-pos (point)) ; side effect
1948 (py-goto-statement-below)
1949 (= (current-indentation) initial-indent)
1950 (setq next-symbol (py-suck-up-first-keyword))
1951 (memq next-symbol (cdr (assq first-symbol followers))))
1952 (setq first-symbol next-symbol)))
1953
1954 ;; else if line *opens* a block, search for next stmt indented <=
1955 ((py-statement-opens-block-p)
1956 (while (and
1957 (setq last-pos (point)) ; always true -- side effect
1958 (py-goto-statement-below)
1959 (> (current-indentation) initial-indent))
1960 nil))
1961
1962 ;; else plain code line; stop at next blank line, or stmt or
1963 ;; indenting comment line indented <
1964 (t
1965 (while (and
1966 (setq last-pos (point)) ; always true -- side effect
1967 (or (py-goto-beyond-final-line) t)
1968 (not (looking-at "[ \t]*$")) ; stop at blank line
1969 (or
1970 (>= (current-indentation) initial-indent)
1971 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1972 nil)))
1973
1974 ;; skip to end of last stmt
1975 (goto-char last-pos)
1976 (py-goto-beyond-final-line)
1977
1978 ;; set mark & display
1979 (if just-move
1980 () ; just return
1981 (push-mark (point) 'no-msg)
1982 (forward-line -1)
1983 (message "Mark set after: %s" (py-suck-up-leading-text))
1984 (goto-char initial-pos))))
1985
Barry Warsaw2518c671997-11-05 00:51:08 +00001986(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001987 "Set region to body of def (or class, with prefix arg) enclosing point.
1988Pushes the current mark, then point, on the mark ring (all language
1989modes do this, but although it's handy it's never documented ...).
1990
1991In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001992hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1993`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001994
1995And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996Turned out that was more confusing than useful: the `goto start' and
1997`goto end' commands are usually used to search through a file, and
1998people expect them to act a lot like `search backward' and `search
1999forward' string-search commands. But because Python `def' and `class'
2000can nest to arbitrary levels, finding the smallest def containing
2001point cannot be done via a simple backward search: the def containing
2002point may not be the closest preceding def, or even the closest
2003preceding def that's indented less. The fancy algorithm required is
2004appropriate for the usual uses of this `mark' command, but not for the
2005`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002006
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002007So the def marked by this command may not be the one either of the
2008`goto' commands find: If point is on a blank or non-indenting comment
2009line, moves back to start of the closest preceding code statement or
2010indenting comment line. If this is a `def' statement, that's the def
2011we use. Else searches for the smallest enclosing `def' block and uses
2012that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014When an enclosing def is found: The mark is left immediately beyond
2015the last line of the def block. Point is left at the start of the
2016def, except that: if the def is preceded by a number of comment lines
2017followed by (at most) one optional blank line, point is left at the
2018start of the comments; else if the def is preceded by a blank line,
2019point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020
2021The intent is to mark the containing def/class and its associated
2022documentation, to make moving and duplicating functions and classes
2023pleasant."
2024 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002025 (let ((start (point))
2026 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (push-mark start)
2028 (if (not (py-go-up-tree-to-keyword which))
2029 (progn (goto-char start)
2030 (error "Enclosing %s not found" which))
2031 ;; else enclosing def/class found
2032 (setq start (point))
2033 (py-goto-beyond-block)
2034 (push-mark (point))
2035 (goto-char start)
2036 (if (zerop (forward-line -1)) ; if there is a preceding line
2037 (progn
2038 (if (looking-at "[ \t]*$") ; it's blank
2039 (setq start (point)) ; so reset start point
2040 (goto-char start)) ; else try again
2041 (if (zerop (forward-line -1))
2042 (if (looking-at "[ \t]*#") ; a comment
2043 ;; look back for non-comment line
2044 ;; tricky: note that the regexp matches a blank
2045 ;; line, cuz \n is in the 2nd character class
2046 (and
2047 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2048 (forward-line 1))
2049 ;; no comment, so go back
2050 (goto-char start))))))))
2051
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002052;; ripped from cc-mode
2053(defun py-forward-into-nomenclature (&optional arg)
2054 "Move forward to end of a nomenclature section or word.
2055With arg, to it arg times.
2056
2057A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2058 (interactive "p")
2059 (let ((case-fold-search nil))
2060 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002061 (re-search-forward
2062 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2063 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002064 (while (and (< arg 0)
2065 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002066 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002067 (point-min) 0))
2068 (forward-char 1)
2069 (setq arg (1+ arg)))))
2070 (py-keep-region-active))
2071
2072(defun py-backward-into-nomenclature (&optional arg)
2073 "Move backward to beginning of a nomenclature section or word.
2074With optional ARG, move that many times. If ARG is negative, move
2075forward.
2076
2077A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2078 (interactive "p")
2079 (py-forward-into-nomenclature (- arg))
2080 (py-keep-region-active))
2081
2082
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002083
2084;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002085
2086;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002087;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2088;; out of the right places, along with the keys they're on & current
2089;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002090(defun py-dump-help-string (str)
2091 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002092 (let ((locals (buffer-local-variables))
2093 funckind funcname func funcdoc
2094 (start 0) mstart end
2095 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002096 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2097 (setq mstart (match-beginning 0) end (match-end 0)
2098 funckind (substring str (match-beginning 1) (match-end 1))
2099 funcname (substring str (match-beginning 2) (match-end 2))
2100 func (intern funcname))
2101 (princ (substitute-command-keys (substring str start mstart)))
2102 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002103 ((equal funckind "c") ; command
2104 (setq funcdoc (documentation func)
2105 keys (concat
2106 "Key(s): "
2107 (mapconcat 'key-description
2108 (where-is-internal func py-mode-map)
2109 ", "))))
2110 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002111 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002112 keys (if (assq func locals)
2113 (concat
2114 "Local/Global values: "
2115 (prin1-to-string (symbol-value func))
2116 " / "
2117 (prin1-to-string (default-value func)))
2118 (concat
2119 "Value: "
2120 (prin1-to-string (symbol-value func))))))
2121 (t ; unexpected
2122 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002123 (princ (format "\n-> %s:\t%s\t%s\n\n"
2124 (if (equal funckind "c") "Command" "Variable")
2125 funcname keys))
2126 (princ funcdoc)
2127 (terpri)
2128 (setq start end))
2129 (princ (substitute-command-keys (substring str start))))
2130 (print-help-return-message)))
2131
2132(defun py-describe-mode ()
2133 "Dump long form of Python-mode docs."
2134 (interactive)
2135 (py-dump-help-string "Major mode for editing Python files.
2136Knows about Python indentation, tokens, comments and continuation lines.
2137Paragraphs are separated by blank lines only.
2138
2139Major sections below begin with the string `@'; specific function and
2140variable docs begin with `->'.
2141
2142@EXECUTING PYTHON CODE
2143
2144\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2145\\[py-execute-region]\tsends the current region
2146\\[py-shell]\tstarts a Python interpreter window; this will be used by
2147\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2148%c:py-execute-buffer
2149%c:py-execute-region
2150%c:py-shell
2151
2152@VARIABLES
2153
2154py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002155py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156
2157py-python-command\tshell command to invoke Python interpreter
2158py-scroll-process-buffer\talways scroll Python process buffer
2159py-temp-directory\tdirectory used for temp files (if needed)
2160
2161py-beep-if-tab-change\tring the bell if tab-width is changed
2162%v:py-indent-offset
2163%v:py-block-comment-prefix
2164%v:py-python-command
2165%v:py-scroll-process-buffer
2166%v:py-temp-directory
2167%v:py-beep-if-tab-change
2168
2169@KINDS OF LINES
2170
2171Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002172preceding line ends with a backslash that's not part of a comment, or
2173the paren/bracket/brace nesting level at the start of the line is
2174non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002175
2176An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002177possibly blanks or tabs), a `comment line' (leftmost non-blank
2178character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002179
2180Comment Lines
2181
2182Although all comment lines are treated alike by Python, Python mode
2183recognizes two kinds that act differently with respect to indentation.
2184
2185An `indenting comment line' is a comment line with a blank, tab or
2186nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002187treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002188indenting comment line will be indented like the comment line. All
2189other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002190following the initial `#') are `non-indenting comment lines', and
2191their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002192
2193Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002194whenever possible. Non-indenting comment lines are useful in cases
2195like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002196
2197\ta = b # a very wordy single-line comment that ends up being
2198\t #... continued onto another line
2199
2200\tif a == b:
2201##\t\tprint 'panic!' # old code we've `commented out'
2202\t\treturn a
2203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204Since the `#...' and `##' comment lines have a non-whitespace
2205character following the initial `#', Python mode ignores them when
2206computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002207
2208Continuation Lines and Statements
2209
2210The Python-mode commands generally work on statements instead of on
2211individual lines, where a `statement' is a comment or blank line, or a
2212code line and all of its following continuation lines (if any)
2213considered as a single logical unit. The commands in this mode
2214generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002215statement containing point, even if point happens to be in the middle
2216of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002217
2218
2219@INDENTATION
2220
2221Primarily for entering new code:
2222\t\\[indent-for-tab-command]\t indent line appropriately
2223\t\\[py-newline-and-indent]\t insert newline, then indent
2224\t\\[py-delete-char]\t reduce indentation, or delete single character
2225
2226Primarily for reindenting existing code:
2227\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2228\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2229
2230\t\\[py-indent-region]\t reindent region to match its context
2231\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2232\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2233
2234Unlike most programming languages, Python uses indentation, and only
2235indentation, to specify block structure. Hence the indentation supplied
2236automatically by Python-mode is just an educated guess: only you know
2237the block structure you intend, so only you can supply correct
2238indentation.
2239
2240The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2241the indentation of preceding statements. E.g., assuming
2242py-indent-offset is 4, after you enter
2243\tif a > 0: \\[py-newline-and-indent]
2244the cursor will be moved to the position of the `_' (_ is not a
2245character in the file, it's just used here to indicate the location of
2246the cursor):
2247\tif a > 0:
2248\t _
2249If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2250to
2251\tif a > 0:
2252\t c = d
2253\t _
2254Python-mode cannot know whether that's what you intended, or whether
2255\tif a > 0:
2256\t c = d
2257\t_
2258was your intent. In general, Python-mode either reproduces the
2259indentation of the (closest code or indenting-comment) preceding
2260statement, or adds an extra py-indent-offset blanks if the preceding
2261statement has `:' as its last significant (non-whitespace and non-
2262comment) character. If the suggested indentation is too much, use
2263\\[py-delete-char] to reduce it.
2264
2265Continuation lines are given extra indentation. If you don't like the
2266suggested indentation, change it to something you do like, and Python-
2267mode will strive to indent later lines of the statement in the same way.
2268
2269If a line is a continuation line by virtue of being in an unclosed
2270paren/bracket/brace structure (`list', for short), the suggested
2271indentation depends on whether the current line contains the first item
2272in the list. If it does, it's indented py-indent-offset columns beyond
2273the indentation of the line containing the open bracket. If you don't
2274like that, change it by hand. The remaining items in the list will mimic
2275whatever indentation you give to the first item.
2276
2277If a line is a continuation line because the line preceding it ends with
2278a backslash, the third and following lines of the statement inherit their
2279indentation from the line preceding them. The indentation of the second
2280line in the statement depends on the form of the first (base) line: if
2281the base line is an assignment statement with anything more interesting
2282than the backslash following the leftmost assigning `=', the second line
2283is indented two columns beyond that `='. Else it's indented to two
2284columns beyond the leftmost solid chunk of non-whitespace characters on
2285the base line.
2286
2287Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2288repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2289structure you intend.
2290%c:indent-for-tab-command
2291%c:py-newline-and-indent
2292%c:py-delete-char
2293
2294
2295The next function may be handy when editing code you didn't write:
2296%c:py-guess-indent-offset
2297
2298
2299The remaining `indent' functions apply to a region of Python code. They
2300assume the block structure (equals indentation, in Python) of the region
2301is correct, and alter the indentation in various ways while preserving
2302the block structure:
2303%c:py-indent-region
2304%c:py-shift-region-left
2305%c:py-shift-region-right
2306
2307@MARKING & MANIPULATING REGIONS OF CODE
2308
2309\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002310\\[py-mark-def-or-class]\t mark smallest enclosing def
2311\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002312\\[comment-region]\t comment out region of code
2313\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002314%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002315%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002316%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002317
2318@MOVING POINT
2319
2320\\[py-previous-statement]\t move to statement preceding point
2321\\[py-next-statement]\t move to statement following point
2322\\[py-goto-block-up]\t move up to start of current block
2323\\[beginning-of-python-def-or-class]\t move to start of def
2324\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2325\\[end-of-python-def-or-class]\t move to end of def
2326\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2327
2328The first two move to one statement beyond the statement that contains
2329point. A numeric prefix argument tells them to move that many
2330statements instead. Blank lines, comment lines, and continuation lines
2331do not count as `statements' for these commands. So, e.g., you can go
2332to the first code statement in a file by entering
2333\t\\[beginning-of-buffer]\t to move to the top of the file
2334\t\\[py-next-statement]\t to skip over initial comments and blank lines
2335Or do `\\[py-previous-statement]' with a huge prefix argument.
2336%c:py-previous-statement
2337%c:py-next-statement
2338%c:py-goto-block-up
2339%c:beginning-of-python-def-or-class
2340%c:end-of-python-def-or-class
2341
2342@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2343
2344`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2345
2346`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2347overall class and def structure of a module.
2348
2349`\\[back-to-indentation]' moves point to a line's first non-blank character.
2350
2351`\\[indent-relative]' is handy for creating odd indentation.
2352
2353@OTHER EMACS HINTS
2354
2355If you don't like the default value of a variable, change its value to
2356whatever you do like by putting a `setq' line in your .emacs file.
2357E.g., to set the indentation increment to 4, put this line in your
2358.emacs:
2359\t(setq py-indent-offset 4)
2360To see the value of a variable, do `\\[describe-variable]' and enter the variable
2361name at the prompt.
2362
2363When entering a key sequence like `C-c C-n', it is not necessary to
2364release the CONTROL key after doing the `C-c' part -- it suffices to
2365press the CONTROL key, press and release `c' (while still holding down
2366CONTROL), press and release `n' (while still holding down CONTROL), &
2367then release CONTROL.
2368
2369Entering Python mode calls with no arguments the value of the variable
2370`python-mode-hook', if that value exists and is not nil; for backward
2371compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2372the Elisp manual for details.
2373
2374Obscure: When python-mode is first loaded, it looks for all bindings
2375to newline-and-indent in the global keymap, and shadows them with
2376local bindings to py-newline-and-indent."))
2377
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002378
2379;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002380(defvar py-parse-state-re
2381 (concat
2382 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2383 "\\|"
2384 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002385
Barry Warsaw7ae77681994-12-12 20:38:05 +00002386;; returns the parse state at point (see parse-partial-sexp docs)
2387(defun py-parse-state ()
2388 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002389 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002390 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002391 (while (not done)
2392 ;; back up to the first preceding line (if any; else start of
2393 ;; buffer) that begins with a popular Python keyword, or a
2394 ;; non- whitespace and non-comment character. These are good
2395 ;; places to start parsing to see whether where we started is
2396 ;; at a non-zero nesting level. It may be slow for people who
2397 ;; write huge code blocks or huge lists ... tough beans.
2398 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002399 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002400 (beginning-of-line)
2401 (save-excursion
2402 (setq pps (parse-partial-sexp (point) here)))
2403 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002404 (setq done (or (zerop ci)
2405 (not (nth 3 pps))
2406 (bobp)))
2407 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002408 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002409
2410;; if point is at a non-zero nesting level, returns the number of the
2411;; character that opens the smallest enclosing unclosed list; else
2412;; returns nil.
2413(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002414 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002415 (if (zerop (car status))
2416 nil ; not in a nest
2417 (car (cdr status))))) ; char# of open bracket
2418
2419;; t iff preceding line ends with backslash that's not in a comment
2420(defun py-backslash-continuation-line-p ()
2421 (save-excursion
2422 (beginning-of-line)
2423 (and
2424 ;; use a cheap test first to avoid the regexp if possible
2425 ;; use 'eq' because char-after may return nil
2426 (eq (char-after (- (point) 2)) ?\\ )
2427 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002428 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002429 (looking-at py-continued-re))))
2430
2431;; t iff current line is a continuation line
2432(defun py-continuation-line-p ()
2433 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002434 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002435 (or (py-backslash-continuation-line-p)
2436 (py-nesting-level))))
2437
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002438;; go to initial line of current statement; usually this is the line
2439;; we're on, but if we're on the 2nd or following lines of a
2440;; continuation block, we need to go up to the first line of the
2441;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002442;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002443;; Tricky: We want to avoid quadratic-time behavior for long continued
2444;; blocks, whether of the backslash or open-bracket varieties, or a
2445;; mix of the two. The following manages to do that in the usual
2446;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002447(defun py-goto-initial-line ()
2448 (let ( open-bracket-pos )
2449 (while (py-continuation-line-p)
2450 (beginning-of-line)
2451 (if (py-backslash-continuation-line-p)
2452 (while (py-backslash-continuation-line-p)
2453 (forward-line -1))
2454 ;; else zip out of nested brackets/braces/parens
2455 (while (setq open-bracket-pos (py-nesting-level))
2456 (goto-char open-bracket-pos)))))
2457 (beginning-of-line))
2458
2459;; go to point right beyond final line of current statement; usually
2460;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002461;; statement we need to skip over the continuation lines. Tricky:
2462;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002463(defun py-goto-beyond-final-line ()
2464 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002465 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002466 (while (and (py-continuation-line-p)
2467 (not (eobp)))
2468 ;; skip over the backslash flavor
2469 (while (and (py-backslash-continuation-line-p)
2470 (not (eobp)))
2471 (forward-line 1))
2472 ;; if in nest, zip to the end of the nest
2473 (setq state (py-parse-state))
2474 (if (and (not (zerop (car state)))
2475 (not (eobp)))
2476 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002477 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002478 (forward-line 1))))))
2479
2480;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002481;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002482(defun py-statement-opens-block-p ()
2483 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002484 (let ((start (point))
2485 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2486 (searching t)
2487 (answer nil)
2488 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002489 (goto-char start)
2490 (while searching
2491 ;; look for a colon with nothing after it except whitespace, and
2492 ;; maybe a comment
2493 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2494 finish t)
2495 (if (eq (point) finish) ; note: no `else' clause; just
2496 ; keep searching if we're not at
2497 ; the end yet
2498 ;; sure looks like it opens a block -- but it might
2499 ;; be in a comment
2500 (progn
2501 (setq searching nil) ; search is done either way
2502 (setq state (parse-partial-sexp start
2503 (match-beginning 0)))
2504 (setq answer (not (nth 4 state)))))
2505 ;; search failed: couldn't find another interesting colon
2506 (setq searching nil)))
2507 answer)))
2508
Barry Warsawf831d811996-07-31 20:42:59 +00002509(defun py-statement-closes-block-p ()
2510 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002511 ;; starts with `return', `raise', `break', `continue', and `pass'.
2512 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002513 (let ((here (point)))
2514 (back-to-indentation)
2515 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002516 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002517 (goto-char here))))
2518
Barry Warsaw7ae77681994-12-12 20:38:05 +00002519;; go to point right beyond final line of block begun by the current
2520;; line. This is the same as where py-goto-beyond-final-line goes
2521;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002522;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523(defun py-goto-beyond-block ()
2524 (if (py-statement-opens-block-p)
2525 (py-mark-block nil 'just-move)
2526 (py-goto-beyond-final-line)))
2527
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002528;; go to start of first statement (not blank or comment or
2529;; continuation line) at or preceding point. returns t if there is
2530;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531(defun py-goto-statement-at-or-above ()
2532 (py-goto-initial-line)
2533 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002534 ;; skip back over blank & comment lines
2535 ;; note: will skip a blank or comment line that happens to be
2536 ;; a continuation line too
2537 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2538 (progn (py-goto-initial-line) t)
2539 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002540 t))
2541
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002542;; go to start of first statement (not blank or comment or
2543;; continuation line) following the statement containing point returns
2544;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002545(defun py-goto-statement-below ()
2546 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002547 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002548 (py-goto-beyond-final-line)
2549 (while (and
2550 (looking-at py-blank-or-comment-re)
2551 (not (eobp)))
2552 (forward-line 1))
2553 (if (eobp)
2554 (progn (goto-char start) nil)
2555 t)))
2556
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002557;; go to start of statement, at or preceding point, starting with
2558;; keyword KEY. Skips blank lines and non-indenting comments upward
2559;; first. If that statement starts with KEY, done, else go back to
2560;; first enclosing block starting with KEY. If successful, leaves
2561;; point at the start of the KEY line & returns t. Else leaves point
2562;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002563(defun py-go-up-tree-to-keyword (key)
2564 ;; skip blanks and non-indenting #
2565 (py-goto-initial-line)
2566 (while (and
2567 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2568 (zerop (forward-line -1))) ; go back
2569 nil)
2570 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002571 (let* ((re (concat "[ \t]*" key "\\b"))
2572 (case-fold-search nil) ; let* so looking-at sees this
2573 (found (looking-at re))
2574 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002575 (while (not (or found dead))
2576 (condition-case nil ; in case no enclosing block
2577 (py-goto-block-up 'no-mark)
2578 (error (setq dead t)))
2579 (or dead (setq found (looking-at re))))
2580 (beginning-of-line)
2581 found))
2582
2583;; return string in buffer from start of indentation to end of line;
2584;; prefix "..." if leading whitespace was skipped
2585(defun py-suck-up-leading-text ()
2586 (save-excursion
2587 (back-to-indentation)
2588 (concat
2589 (if (bolp) "" "...")
2590 (buffer-substring (point) (progn (end-of-line) (point))))))
2591
2592;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2593;; as a Lisp symbol; return nil if none
2594(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002595 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002596 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2597 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2598 nil)))
2599
Barry Warsawb3e81d51996-09-04 15:12:42 +00002600(defun py-current-defun ()
2601 ;; tell add-log.el how to find the current function/method/variable
2602 (save-excursion
2603 (if (re-search-backward py-defun-start-re nil t)
2604 (or (match-string 3)
2605 (let ((method (match-string 2)))
2606 (if (and (not (zerop (length (match-string 1))))
2607 (re-search-backward py-class-start-re nil t))
2608 (concat (match-string 1) "." method)
2609 method)))
2610 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002611
2612
Barry Warsawfec75d61995-07-05 23:26:15 +00002613(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002614 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002615
Barry Warsaw850437a1995-03-08 21:50:28 +00002616(defun py-version ()
2617 "Echo the current version of `python-mode' in the minibuffer."
2618 (interactive)
2619 (message "Using `python-mode' version %s" py-version)
2620 (py-keep-region-active))
2621
2622;; only works under Emacs 19
2623;(eval-when-compile
2624; (require 'reporter))
2625
2626(defun py-submit-bug-report (enhancement-p)
2627 "Submit via mail a bug report on `python-mode'.
2628With \\[universal-argument] just submit an enhancement request."
2629 (interactive
2630 (list (not (y-or-n-p
2631 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002632 (let ((reporter-prompt-for-summary-p (if enhancement-p
2633 "(Very) brief summary: "
2634 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002635 (require 'reporter)
2636 (reporter-submit-bug-report
2637 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002638 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002639 ;; varlist
2640 (if enhancement-p nil
2641 '(py-python-command
2642 py-indent-offset
2643 py-block-comment-prefix
2644 py-scroll-process-buffer
2645 py-temp-directory
2646 py-beep-if-tab-change))
2647 nil ;pre-hooks
2648 nil ;post-hooks
2649 "Dear Barry,") ;salutation
2650 (if enhancement-p nil
2651 (set-mark (point))
2652 (insert
2653"Please replace this text with a sufficiently large code sample\n\
2654and an exact recipe so that I can reproduce your problem. Failure\n\
2655to do so may mean a greater delay in fixing your bug.\n\n")
2656 (exchange-point-and-mark)
2657 (py-keep-region-active))))
2658
2659
Barry Warsaw47384781997-11-26 05:27:45 +00002660(defun py-kill-emacs-hook ()
2661 (mapcar #'(lambda (filename)
2662 (py-safe (delete-file filename)))
2663 py-file-queue))
2664
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002665;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002666(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002667
2668
2669
2670(provide 'python-mode)
2671;;; python-mode.el ends here