blob: f6aa2e32e5a9017292a676013e9afd8a56907983 [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 Warsawc72c11c1997-08-09 06:42:08 +000011(defconst py-version "3.0"
12 "`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,
30;; you may need to acquire the Custom library.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
Barry Warsawaffc0ca1997-11-03 16:59:38 +000032;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
33;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000034;; but it is compatible with 19.34 and the current 20 series Emacsen.
35;; By default, in XEmacs when you visit a .py file, it is put in
36;; Python mode. In Emacs, you need to add the following to your
37;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000039;; (autoload 'python-mode "python-mode" "Python editing mode." t)
40;; (setq auto-mode-alist
41;; (cons '("\\.py$" . python-mode) auto-mode-alist))
42;; (setq interpreter-mode-alist
43;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000044;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000045;; Assuming python-mode.el is on your load-path, it will be invoked
46;; when you visit a .py file, or a file with a first line that looks
47;; like:
48;;
49;; #! /usr/bin/env python
50
Barry Warsaw44b72201996-07-05 20:11:35 +000051;; If you want font-lock support for Python source code (a.k.a. syntax
52;; coloring, highlighting), add this to your .emacs file:
53;;
54;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000055;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000056;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000057
Barry Warsawaffc0ca1997-11-03 16:59:38 +000058;; To submit bug reports, use C-c C-b. Please include a complete, but
59;; concise code sample and a recipe for reproducing the bug. Send
60;; suggestions and other comments to python-mode@python.org.
61
62;; When in a Python mode buffer, do a C-h m for more help. It's
63;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; Here's a brief to do list:
66;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000067;; - Better integration with gud-mode for debugging.
68;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000069;; - possibly force indent-tabs-mode == nil, and add a
70;; write-file-hooks that runs untabify on the whole buffer (to work
71;; around potential tab/space mismatch problems). In practice this
72;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000073;; - have py-execute-region on indented code act as if the region is
74;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000075;; - Add a py-goto-error or some such that would scan an exception in
76;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsaw7b0f5681995-03-08 21:33:04 +000078;;; Code:
79
Barry Warsawc72c11c1997-08-09 06:42:08 +000080(require 'custom)
81
Barry Warsaw7b0f5681995-03-08 21:33:04 +000082
83;; user definable variables
84;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000085
Barry Warsawc72c11c1997-08-09 06:42:08 +000086(defgroup python nil
87 "Support for the Python programming language, <http://www.python.org/>"
88 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000089
Barry Warsawc72c11c1997-08-09 06:42:08 +000090(defcustom py-python-command "python"
91 "*Shell command used to start Python interpreter."
92 :type 'string
93 :group 'python)
94
95(defcustom py-indent-offset 4
96 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +000098when you're editing someone else's Python code."
99 :type 'integer
100 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000101
Barry Warsawc72c11c1997-08-09 06:42:08 +0000102(defcustom py-align-multiline-strings-p t
103 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000104When this flag is non-nil, continuation lines are lined up under the
105preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000106lines are aligned to column zero."
107 :type '(choice (const :tag "Align under preceding line" t)
108 (const :tag "Align to column zero" nil))
109 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000110
Barry Warsawc72c11c1997-08-09 06:42:08 +0000111(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000112 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000113This should follow the convention for non-indenting comment lines so
114that the indentation commands won't get confused (i.e., the string
115should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000116`...' is arbitrary)."
117 :type 'string
118 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000119
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000121 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000122
Barry Warsaw6d627751996-03-06 18:41:38 +0000123When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000125
126When t, lines that begin with a single `#' are a hint to subsequent
127line indentation. If the previous line is such a comment line (as
128opposed to one that starts with `py-block-comment-prefix'), then it's
129indentation is used as a hint for this line's indentation. Lines that
130begin with `py-block-comment-prefix' are ignored for indentation
131purposes.
132
133When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000134indentation hints, unless the comment character is in column zero."
135 :type '(choice
136 (const :tag "Skip all comment lines (fast)" nil)
137 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000138 (const :tag "Single # `sets' indentation except at column zero"
139 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140 )
141 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000142
Barry Warsawc72c11c1997-08-09 06:42:08 +0000143(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000144 "*Scroll Python process buffer as output arrives.
145If nil, the Python process buffer acts, with respect to scrolling, like
146Shell-mode buffers normally act. This is surprisingly complicated and
147so won't be explained here; in fact, you can't get the whole story
148without studying the Emacs C code.
149
150If non-nil, the behavior is different in two respects (which are
151slightly inaccurate in the interest of brevity):
152
153 - If the buffer is in a window, and you left point at its end, the
154 window will scroll as new output arrives, and point will move to the
155 buffer's end, even if the window is not the selected window (that
156 being the one the cursor is in). The usual behavior for shell-mode
157 windows is not to scroll, and to leave point where it was, if the
158 buffer is in a window other than the selected window.
159
160 - If the buffer is not visible in any window, and you left point at
161 its end, the buffer will be popped into a window as soon as more
162 output arrives. This is handy if you have a long-running
163 computation and don't want to tie up screen area waiting for the
164 output. The usual behavior for a shell-mode buffer is to stay
165 invisible until you explicitly visit it.
166
167Note the `and if you left point at its end' clauses in both of the
168above: you can `turn off' the special behaviors while output is in
169progress, by visiting the Python buffer and moving point to anywhere
170besides the end. Then the buffer won't scroll, point will remain where
171you leave it, and if you hide the buffer it will stay hidden until you
172visit it again. You can enable and disable the special behaviors as
173often as you like, while output is in progress, by (respectively) moving
174point to, or away from, the end of the buffer.
175
176Warning: If you expect a large amount of output, you'll probably be
177happier setting this option to nil.
178
179Obscure: `End of buffer' above should really say `at or beyond the
180process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000181told <grin>."
182 :type 'boolean
183 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000184
Barry Warsaw516b6201997-08-09 06:43:20 +0000185(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000186 (let ((ok '(lambda (x)
187 (and x
188 (setq x (expand-file-name x)) ; always true
189 (file-directory-p x)
190 (file-writable-p x)
191 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000192 (or (funcall ok (getenv "TMPDIR"))
193 (funcall ok "/usr/tmp")
194 (funcall ok "/tmp")
195 (funcall ok ".")
196 (error
197 "Couldn't find a usable temp directory -- set py-temp-directory")))
198 "*Directory used for temp files created by a *Python* process.
199By default, the first directory from this list that exists and that you
200can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201/usr/tmp, /tmp, or the current directory."
202 :type 'string
203 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000204
Barry Warsaw516b6201997-08-09 06:43:20 +0000205(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000206 "*Ring the bell if tab-width is changed.
207If a comment of the form
208
209 \t# vi:set tabsize=<number>:
210
211is found before the first code line when the file is entered, and the
212current value of (the general Emacs variable) `tab-width' does not
213equal <number>, `tab-width' is set to <number>, a message saying so is
214displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000215the Emacs bell is also rung as a warning."
216 :type 'boolean
217 :group 'python)
218
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000219(defcustom py-backspace-function 'backward-delete-char-untabify
220 "*Function called by `py-electric-backspace' when deleting backwards."
221 :type 'function
222 :group 'python)
223
224(defcustom py-delete-function 'delete-char
225 "*Function called by `py-electric-delete' when deleting forwards."
226 :type 'function
227 :group 'python)
228
229
Barry Warsawc72c11c1997-08-09 06:42:08 +0000230
231;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
232;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
233
Barry Warsawc12c62e1997-09-04 04:18:07 +0000234(defconst py-emacs-features ()
235 "A list of features extant in the Emacs you are using.
236There are many flavors of Emacs out there, each with different
237features supporting those needed by CC Mode. Here's the current
238supported list, along with the values for this variable:
239
240 XEmacs 19: ()
241 XEmacs 20: ()
242 Emacs 19: ()
243")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000244
Barry Warsawfb07f401997-02-24 03:37:22 +0000245(defvar python-font-lock-keywords
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000246 (let* ((keywords '("and" "assert" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000247 "continue" "def" "del" "elif"
248 "else:" "except" "except:" "exec"
249 "finally:" "for" "from" "global"
250 "if" "import" "in" "is"
251 "lambda" "not" "or" "pass"
252 "print" "raise" "return" "try:"
253 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000254 ))
255 (kwregex (mapconcat 'identity keywords "\\|")))
256 (list
257 ;; keywords not at beginning of line
258 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
259 ;; keywords at beginning of line. i don't think regexps are
260 ;; powerful enough to handle these two cases in one regexp.
261 ;; prove me wrong!
262 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
263 ;; classes
264 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
265 1 font-lock-type-face)
266 ;; functions
267 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
268 1 font-lock-function-name-face)
269 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000270 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000271(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
272
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000273
Barry Warsaw81437461996-08-01 19:48:02 +0000274(defvar imenu-example--python-show-method-args-p nil
275 "*Controls echoing of arguments of functions & methods in the imenu buffer.
276When non-nil, arguments are printed.")
277
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000278(make-variable-buffer-local 'py-indent-offset)
279
Barry Warsaw7ae77681994-12-12 20:38:05 +0000280;; have to bind py-file-queue before installing the kill-emacs hook
281(defvar py-file-queue nil
282 "Queue of Python temp files awaiting execution.
283Currently-active file is at the head of the list.")
284
Barry Warsawc72c11c1997-08-09 06:42:08 +0000285
286;; Constants
287
288;; Regexp matching a Python string literal
289(defconst py-stringlit-re
290 (concat
291 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
292 "\\|" ; or
293 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
294
295;; Regexp matching Python lines that are continued via backslash.
296;; This is tricky because a trailing backslash does not mean
297;; continuation if it's in a comment
298(defconst py-continued-re
299 (concat
300 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
301 "\\\\$"))
302
303;; Regexp matching blank or comment lines.
304(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
305
306;; Regexp matching clauses to be outdented one level.
307(defconst py-outdent-re
308 (concat "\\(" (mapconcat 'identity
309 '("else:"
310 "except\\(\\s +.*\\)?:"
311 "finally:"
312 "elif\\s +.*:")
313 "\\|")
314 "\\)"))
315
316
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000317;; Regexp matching keywords which typically close a block
318(defconst py-block-closing-keywords-re
319 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
320
Barry Warsawc72c11c1997-08-09 06:42:08 +0000321;; Regexp matching lines to not outdent after.
322(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000323 (concat
324 "\\("
325 (mapconcat 'identity
326 (list "try:"
327 "except\\(\\s +.*\\)?:"
328 "while\\s +.*:"
329 "for\\s +.*:"
330 "if\\s +.*:"
331 "elif\\s +.*:"
332 (concat py-block-closing-keywords-re "[ \t\n]")
333 )
334 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000335 "\\)"))
336
337;; Regexp matching a function, method or variable assignment. If you
338;; change this, you probably have to change `py-current-defun' as
339;; well. This is only used by `py-current-defun' to find the name for
340;; add-log.el.
341(defvar py-defun-start-re
342 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
343
344;; Regexp for finding a class name. If you change this, you probably
345;; have to change `py-current-defun' as well. This is only used by
346;; `py-current-defun' to find the name for add-log.el.
347(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
348
349
350
351;; Utilities
352
353(defmacro py-safe (&rest body)
354 ;; safely execute BODY, return nil if an error occurred
355 (` (condition-case nil
356 (progn (,@ body))
357 (error nil))))
358
359(defsubst py-keep-region-active ()
360 ;; Do whatever is necessary to keep the region active in XEmacs.
361 ;; Ignore byte-compiler warnings you might see. Also note that
362 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
363 ;; to take explicit action.
364 (and (boundp 'zmacs-region-stays)
365 (setq zmacs-region-stays t)))
366
367
368;; Major mode boilerplate
369
Barry Warsaw7ae77681994-12-12 20:38:05 +0000370;; define a mode-specific abbrev table for those who use such things
371(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000372 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000373(define-abbrev-table 'python-mode-abbrev-table nil)
374
Barry Warsaw7ae77681994-12-12 20:38:05 +0000375(defvar python-mode-hook nil
376 "*Hook called by `python-mode'.")
377
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378;; in previous version of python-mode.el, the hook was incorrectly
379;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000380(and (fboundp 'make-obsolete-variable)
381 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
382
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000383(defvar py-mode-map ()
384 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000385(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000386 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000388 ;; electric keys
389 (define-key py-mode-map ":" 'py-electric-colon)
390 ;; indentation level modifiers
391 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
392 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
393 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
394 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
395 ;; subprocess commands
396 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
397 (define-key py-mode-map "\C-c|" 'py-execute-region)
398 (define-key py-mode-map "\C-c!" 'py-shell)
399 ;; Caution! Enter here at your own risk. We are trying to support
400 ;; several behaviors and it gets disgusting. :-( This logic ripped
401 ;; largely from CC Mode.
402 ;;
403 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
404 ;; backwards deletion behavior to DEL, which both Delete and
405 ;; Backspace get translated to. There's no way to separate this
406 ;; behavior in a clean way, so deal with it! Besides, it's been
407 ;; this way since the dawn of time.
408 (if (not (boundp 'delete-key-deletes-forward))
409 (define-key py-mode-map "\177" 'py-electric-backspace)
410 ;; However, XEmacs 20 actually achieved enlightenment. It is
411 ;; possible to sanely define both backward and forward deletion
412 ;; behavior under X separately (TTYs are forever beyond hope, but
413 ;; who cares? XEmacs 20 does the right thing with these too).
414 (define-key py-mode-map [delete] 'py-electric-delete)
415 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw2518c671997-11-05 00:51:08 +0000416 ;; marking interesting locations
417 (define-key py-mode-map "\C-c\C-m" 'py-mark-def-or-class)
418 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000419 ;; Miscellaneous
420 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
421 (define-key py-mode-map "\C-c\t" 'py-indent-region)
422 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
423 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
424 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000425 (define-key py-mode-map "\C-c#" 'py-comment-region)
426 (define-key py-mode-map "\C-c?" 'py-describe-mode)
427 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
428 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
429 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000430 ;; information
431 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
432 (define-key py-mode-map "\C-c\C-v" 'py-version)
433 ;; py-newline-and-indent mappings
434 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000435 ;; shadow global bindings for newline-and-indent w/ the py- version.
436 ;; BAW - this is extremely bad form, but I'm not going to change it
437 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000438 (mapcar (function (lambda (key)
439 (define-key
440 py-mode-map key 'py-newline-and-indent)))
441 (where-is-internal 'newline-and-indent))
Barry Warsaw850437a1995-03-08 21:50:28 +0000442 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000443
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000444(defvar py-mode-syntax-table nil
445 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000446(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000447 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000448 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000449 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
450 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
451 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
452 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
453 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
454 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
455 ;; Add operator symbols misassigned in the std table
456 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
457 (modify-syntax-entry ?\% "." py-mode-syntax-table)
458 (modify-syntax-entry ?\& "." py-mode-syntax-table)
459 (modify-syntax-entry ?\* "." py-mode-syntax-table)
460 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
461 (modify-syntax-entry ?\- "." py-mode-syntax-table)
462 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
463 (modify-syntax-entry ?\< "." py-mode-syntax-table)
464 (modify-syntax-entry ?\= "." py-mode-syntax-table)
465 (modify-syntax-entry ?\> "." py-mode-syntax-table)
466 (modify-syntax-entry ?\| "." py-mode-syntax-table)
467 ;; For historical reasons, underscore is word class instead of
468 ;; symbol class. GNU conventions say it should be symbol class, but
469 ;; there's a natural conflict between what major mode authors want
470 ;; and what users expect from `forward-word' and `backward-word'.
471 ;; Guido and I have hashed this out and have decided to keep
472 ;; underscore in word class. If you're tempted to change it, try
473 ;; binding M-f and M-b to py-forward-into-nomenclature and
474 ;; py-backward-into-nomenclature instead.
475 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
476 ;; Both single quote and double quote are string delimiters
477 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
478 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
479 ;; backquote is open and close paren
480 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
481 ;; comment delimiters
482 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
483 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
484 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000485
Barry Warsawb3e81d51996-09-04 15:12:42 +0000486
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000487
Barry Warsaw42f707f1996-07-29 21:05:05 +0000488;; Menu definitions, only relevent if you have the easymenu.el package
489;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000490(defvar py-menu nil
491 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000492This menu will get created automatically if you have the `easymenu'
493package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000494
Barry Warsawc72c11c1997-08-09 06:42:08 +0000495(and (py-safe (require 'easymenu) t)
496 (easy-menu-define
497 py-menu py-mode-map "Python Mode menu"
498 '("Python"
499 ["Comment Out Region" py-comment-region (mark)]
500 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
501 "-"
502 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000503 ["Mark current def" py-mark-def-or-class t]
504 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000505 "-"
506 ["Shift region left" py-shift-region-left (mark)]
507 ["Shift region right" py-shift-region-right (mark)]
508 "-"
509 ["Execute buffer" py-execute-buffer t]
510 ["Execute region" py-execute-region (mark)]
511 ["Start interpreter..." py-shell t]
512 "-"
513 ["Go to start of block" py-goto-block-up t]
514 ["Go to start of class" (beginning-of-python-def-or-class t) t]
515 ["Move to end of class" (end-of-python-def-or-class t) t]
516 ["Move to start of def" beginning-of-python-def-or-class t]
517 ["Move to end of def" end-of-python-def-or-class t]
518 "-"
519 ["Describe mode" py-describe-mode t]
520 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000521
Barry Warsaw81437461996-08-01 19:48:02 +0000522
523
524;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
525(defvar imenu-example--python-class-regexp
526 (concat ; <<classes>>
527 "\\(" ;
528 "^[ \t]*" ; newline and maybe whitespace
529 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
530 ; possibly multiple superclasses
531 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
532 "[ \t]*:" ; and the final :
533 "\\)" ; >>classes<<
534 )
535 "Regexp for Python classes for use with the imenu package."
536 )
537
538(defvar imenu-example--python-method-regexp
539 (concat ; <<methods and functions>>
540 "\\(" ;
541 "^[ \t]*" ; new line and maybe whitespace
542 "\\(def[ \t]+" ; function definitions start with def
543 "\\([a-zA-Z0-9_]+\\)" ; name is here
544 ; function arguments...
545 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
546 "\\)" ; end of def
547 "[ \t]*:" ; and then the :
548 "\\)" ; >>methods and functions<<
549 )
550 "Regexp for Python methods/functions for use with the imenu package."
551 )
552
553(defvar imenu-example--python-method-no-arg-parens '(2 8)
554 "Indicies into groups of the Python regexp for use with imenu.
555
556Using these values will result in smaller imenu lists, as arguments to
557functions are not listed.
558
559See the variable `imenu-example--python-show-method-args-p' for more
560information.")
561
562(defvar imenu-example--python-method-arg-parens '(2 7)
563 "Indicies into groups of the Python regexp for use with imenu.
564Using these values will result in large imenu lists, as arguments to
565functions are listed.
566
567See the variable `imenu-example--python-show-method-args-p' for more
568information.")
569
570;; Note that in this format, this variable can still be used with the
571;; imenu--generic-function. Otherwise, there is no real reason to have
572;; it.
573(defvar imenu-example--generic-python-expression
574 (cons
575 (concat
576 imenu-example--python-class-regexp
577 "\\|" ; or...
578 imenu-example--python-method-regexp
579 )
580 imenu-example--python-method-no-arg-parens)
581 "Generic Python expression which may be used directly with imenu.
582Used by setting the variable `imenu-generic-expression' to this value.
583Also, see the function \\[imenu-example--create-python-index] for a
584better alternative for finding the index.")
585
586;; These next two variables are used when searching for the python
587;; class/definitions. Just saving some time in accessing the
588;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000589(defvar imenu-example--python-generic-regexp nil)
590(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000591
592
593;;;###autoload
594(eval-when-compile
595 ;; Imenu isn't used in XEmacs, so just ignore load errors
596 (condition-case ()
597 (progn
598 (require 'cl)
599 (require 'imenu))
600 (error nil)))
601
602(defun imenu-example--create-python-index ()
603 "Python interface function for imenu package.
604Finds all python classes and functions/methods. Calls function
605\\[imenu-example--create-python-index-engine]. See that function for
606the details of how this works."
607 (setq imenu-example--python-generic-regexp
608 (car imenu-example--generic-python-expression))
609 (setq imenu-example--python-generic-parens
610 (if imenu-example--python-show-method-args-p
611 imenu-example--python-method-arg-parens
612 imenu-example--python-method-no-arg-parens))
613 (goto-char (point-min))
614 (imenu-example--create-python-index-engine nil))
615
616(defun imenu-example--create-python-index-engine (&optional start-indent)
617 "Function for finding imenu definitions in Python.
618
619Finds all definitions (classes, methods, or functions) in a Python
620file for the imenu package.
621
622Returns a possibly nested alist of the form
623
624 (INDEX-NAME . INDEX-POSITION)
625
626The second element of the alist may be an alist, producing a nested
627list as in
628
629 (INDEX-NAME . INDEX-ALIST)
630
631This function should not be called directly, as it calls itself
632recursively and requires some setup. Rather this is the engine for
633the function \\[imenu-example--create-python-index].
634
635It works recursively by looking for all definitions at the current
636indention level. When it finds one, it adds it to the alist. If it
637finds a definition at a greater indentation level, it removes the
638previous definition from the alist. In it's place it adds all
639definitions found at the next indentation level. When it finds a
640definition that is less indented then the current level, it retuns the
641alist it has created thus far.
642
643The optional argument START-INDENT indicates the starting indentation
644at which to continue looking for Python classes, methods, or
645functions. If this is not supplied, the function uses the indentation
646of the first definition found."
647 (let ((index-alist '())
648 (sub-method-alist '())
649 looking-p
650 def-name prev-name
651 cur-indent def-pos
652 (class-paren (first imenu-example--python-generic-parens))
653 (def-paren (second imenu-example--python-generic-parens)))
654 (setq looking-p
655 (re-search-forward imenu-example--python-generic-regexp
656 (point-max) t))
657 (while looking-p
658 (save-excursion
659 ;; used to set def-name to this value but generic-extract-name is
660 ;; new to imenu-1.14. this way it still works with imenu-1.11
661 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
662 (let ((cur-paren (if (match-beginning class-paren)
663 class-paren def-paren)))
664 (setq def-name
665 (buffer-substring (match-beginning cur-paren)
666 (match-end cur-paren))))
667 (beginning-of-line)
668 (setq cur-indent (current-indentation)))
669
670 ;; HACK: want to go to the next correct definition location. we
671 ;; explicitly list them here. would be better to have them in a
672 ;; list.
673 (setq def-pos
674 (or (match-beginning class-paren)
675 (match-beginning def-paren)))
676
677 ;; if we don't have a starting indent level, take this one
678 (or start-indent
679 (setq start-indent cur-indent))
680
681 ;; if we don't have class name yet, take this one
682 (or prev-name
683 (setq prev-name def-name))
684
685 ;; what level is the next definition on? must be same, deeper
686 ;; or shallower indentation
687 (cond
688 ;; at the same indent level, add it to the list...
689 ((= start-indent cur-indent)
690
691 ;; if we don't have push, use the following...
692 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
693 (push (cons def-name def-pos) index-alist))
694
695 ;; deeper indented expression, recur...
696 ((< start-indent cur-indent)
697
698 ;; the point is currently on the expression we're supposed to
699 ;; start on, so go back to the last expression. The recursive
700 ;; call will find this place again and add it to the correct
701 ;; list
702 (re-search-backward imenu-example--python-generic-regexp
703 (point-min) 'move)
704 (setq sub-method-alist (imenu-example--create-python-index-engine
705 cur-indent))
706
707 (if sub-method-alist
708 ;; we put the last element on the index-alist on the start
709 ;; of the submethod alist so the user can still get to it.
710 (let ((save-elmt (pop index-alist)))
711 (push (cons (imenu-create-submenu-name prev-name)
712 (cons save-elmt sub-method-alist))
713 index-alist))))
714
715 ;; found less indented expression, we're done.
716 (t
717 (setq looking-p nil)
718 (re-search-backward imenu-example--python-generic-regexp
719 (point-min) t)))
720 (setq prev-name def-name)
721 (and looking-p
722 (setq looking-p
723 (re-search-forward imenu-example--python-generic-regexp
724 (point-max) 'move))))
725 (nreverse index-alist)))
726
Barry Warsaw42f707f1996-07-29 21:05:05 +0000727
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000728;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000729(defun python-mode ()
730 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000731To submit a problem report, enter `\\[py-submit-bug-report]' from a
732`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
733documentation. To see what version of `python-mode' you are running,
734enter `\\[py-version]'.
735
736This mode knows about Python indentation, tokens, comments and
737continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738
739COMMANDS
740\\{py-mode-map}
741VARIABLES
742
Barry Warsaw42f707f1996-07-29 21:05:05 +0000743py-indent-offset\t\tindentation increment
744py-block-comment-prefix\t\tcomment string used by comment-region
745py-python-command\t\tshell command to invoke Python interpreter
746py-scroll-process-buffer\t\talways scroll Python process buffer
747py-temp-directory\t\tdirectory used for temp files (if needed)
748py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000749 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000750 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000751 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000752 (make-local-variable 'font-lock-defaults)
753 (make-local-variable 'paragraph-separate)
754 (make-local-variable 'paragraph-start)
755 (make-local-variable 'require-final-newline)
756 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000757 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000758 (make-local-variable 'comment-start-skip)
759 (make-local-variable 'comment-column)
760 (make-local-variable 'indent-region-function)
761 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000762 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000763 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000764 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000765 (setq major-mode 'python-mode
766 mode-name "Python"
767 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000768 paragraph-separate "^[ \t]*$"
769 paragraph-start "^[ \t]*$"
770 require-final-newline t
771 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000772 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000773 comment-start-skip "# *"
774 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000775 indent-region-function 'py-indent-region
776 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000777 ;; tell add-log.el how to find the current function/method/variable
778 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000779 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000780 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000781 ;; add the menu
782 (if py-menu
783 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000784 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000785 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000786 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000787 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000788 ;;
789 ;; not sure where the magic comment has to be; to save time
790 ;; searching for a rarity, we give up if it's not found prior to the
791 ;; first executable statement.
792 ;;
793 ;; BAW - on first glance, this seems like complete hackery. Why was
794 ;; this necessary, and is it still necessary?
795 (let ((case-fold-search nil)
796 (start (point))
797 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000798 (if (re-search-forward
799 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
800 (prog2 (py-next-statement 1) (point) (goto-char 1))
801 t)
802 (progn
803 (setq new-tab-width
804 (string-to-int
805 (buffer-substring (match-beginning 1) (match-end 1))))
806 (if (= tab-width new-tab-width)
807 nil
808 (setq tab-width new-tab-width)
809 (message "Caution: tab-width changed to %d" new-tab-width)
810 (if py-beep-if-tab-change (beep)))))
811 (goto-char start))
812
Barry Warsaw755c6711996-08-01 20:02:55 +0000813 ;; install imenu
814 (setq imenu-create-index-function
815 (function imenu-example--create-python-index))
816 (if (fboundp 'imenu-add-to-menubar)
817 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
818
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000819 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000820 (if python-mode-hook
821 (run-hooks 'python-mode-hook)
822 (run-hooks 'py-mode-hook)))
823
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000824
Barry Warsawb91b7431995-03-14 15:55:20 +0000825;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000826(defun py-outdent-p ()
827 ;; returns non-nil if the current line should outdent one level
828 (save-excursion
829 (and (progn (back-to-indentation)
830 (looking-at py-outdent-re))
831 (progn (backward-to-indentation 1)
832 (while (or (looking-at py-blank-or-comment-re)
833 (bobp))
834 (backward-to-indentation 1))
835 (not (looking-at py-no-outdent-re)))
836 )))
837
Barry Warsawb91b7431995-03-14 15:55:20 +0000838(defun py-electric-colon (arg)
839 "Insert a colon.
840In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000841argument is provided, that many colons are inserted non-electrically.
842Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000843 (interactive "P")
844 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000845 ;; are we in a string or comment?
846 (if (save-excursion
847 (let ((pps (parse-partial-sexp (save-excursion
848 (beginning-of-python-def-or-class)
849 (point))
850 (point))))
851 (not (or (nth 3 pps) (nth 4 pps)))))
852 (save-excursion
853 (let ((here (point))
854 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000855 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000856 (if (and (not arg)
857 (py-outdent-p)
858 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000859 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000860 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000861 )
862 (setq outdent py-indent-offset))
863 ;; Don't indent, only outdent. This assumes that any lines that
864 ;; are already outdented relative to py-compute-indentation were
865 ;; put there on purpose. Its highly annoying to have `:' indent
866 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
867 ;; there a better way to determine this???
868 (if (< (current-indentation) indent) nil
869 (goto-char here)
870 (beginning-of-line)
871 (delete-horizontal-space)
872 (indent-to (- indent outdent))
873 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000874
875
Barry Warsawa97a3f31997-11-04 18:47:06 +0000876;; Python subprocess utilities and filters
877(defun py-execute-file (proc filename)
878 ;; Send a properly formatted execfile('FILENAME') to the underlying
879 ;; Python interpreter process FILENAME. Make that process's buffer
880 ;; visible and force display. Also make comint believe the user
881 ;; typed this string so that kill-output-from-shell does The Right
882 ;; Thing.
883 (let ((curbuf (current-buffer))
884 (procbuf (process-buffer proc))
885 (comint-scroll-to-bottom-on-output t)
886 (msg (format "## working on region in file %s...\n" filename))
887 (cmd (format "execfile('%s')\n" filename)))
888 (unwind-protect
889 (progn
890 (set-buffer procbuf)
891 (goto-char (point-max))
892 (move-marker (process-mark proc) (point))
893 (funcall (process-filter proc) proc msg))
894 (set-buffer curbuf))
895 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896
897(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000898 (let ((curbuf (current-buffer))
899 (pbuf (process-buffer pyproc))
900 (pmark (process-mark pyproc))
901 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000902 ;; make sure we switch to a different buffer at least once. if we
903 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904 ;; window, and point is before the end, and lots of output is
905 ;; coming at a fast pace, then (a) simple cursor-movement commands
906 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
907 ;; to have a visible effect (the window just doesn't get updated,
908 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
909 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000910 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000911 ;; #b makes no sense to me at all. #a almost makes sense: unless
912 ;; we actually change buffers, set_buffer_internal in buffer.c
913 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
914 ;; seems to make the Emacs command loop reluctant to update the
915 ;; display. Perhaps the default process filter in process.c's
916 ;; read_process_output has update_mode_lines++ for a similar
917 ;; reason? beats me ...
918
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000919 (unwind-protect
920 ;; make sure current buffer is restored
921 ;; BAW - we want to check to see if this still applies
922 (progn
923 ;; mysterious ugly hack
924 (if (eq curbuf pbuf)
925 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000926
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000927 (set-buffer pbuf)
928 (let* ((start (point))
929 (goback (< start pmark))
930 (goend (and (not goback) (= start (point-max))))
931 (buffer-read-only nil))
932 (goto-char pmark)
933 (insert string)
934 (move-marker pmark (point))
935 (setq file-finished
936 (and py-file-queue
937 (equal ">>> "
938 (buffer-substring
939 (prog2 (beginning-of-line) (point)
940 (goto-char pmark))
941 (point)))))
942 (if goback (goto-char start)
943 ;; else
944 (if py-scroll-process-buffer
945 (let* ((pop-up-windows t)
946 (pwin (display-buffer pbuf)))
947 (set-window-point pwin (point)))))
948 (set-buffer curbuf)
949 (if file-finished
950 (progn
951 (py-delete-file-silently (car py-file-queue))
952 (setq py-file-queue (cdr py-file-queue))
953 (if py-file-queue
954 (py-execute-file pyproc (car py-file-queue)))))
955 (and goend
956 (progn (set-buffer pbuf)
957 (goto-char (point-max))))
958 ))
959 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
Barry Warsawa97a3f31997-11-04 18:47:06 +0000961
962;;; Subprocess commands
963
964;;;###autoload
965(defun py-shell ()
966 "Start an interactive Python interpreter in another window.
967This is like Shell mode, except that Python is running in the window
968instead of a shell. See the `Interactive Shell' and `Shell Mode'
969sections of the Emacs manual for details, especially for the key
970bindings active in the `*Python*' buffer.
971
972See the docs for variable `py-scroll-buffer' for info on scrolling
973behavior in the process window.
974
975Warning: Don't use an interactive Python if you change sys.ps1 or
976sys.ps2 from their default values, or if you're running code that
977prints `>>> ' or `... ' at the start of a line. `python-mode' can't
978distinguish your output from Python's output, and assumes that `>>> '
979at the start of a line is a prompt from Python. Similarly, the Emacs
980Shell mode code assumes that both `>>> ' and `... ' at the start of a
981line are Python prompts. Bad things can happen if you fool either
982mode.
983
984Warning: If you do any editing *in* the process buffer *while* the
985buffer is accepting output from Python, do NOT attempt to `undo' the
986changes. Some of the output (nowhere near the parts you changed!) may
987be lost if you do. This appears to be an Emacs bug, an unfortunate
988interaction between undo and process filters; the same problem exists in
989non-Python process buffers using the default (Emacs-supplied) process
990filter."
991 ;; BAW - should undo be disabled in the python process buffer, if
992 ;; this bug still exists?
993 (interactive)
994 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +0000995 (switch-to-buffer-other-window
996 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +0000997 (make-local-variable 'comint-prompt-regexp)
998 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
999 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1000 (set-syntax-table py-mode-syntax-table)
1001 (local-set-key [tab] 'self-insert-command))
1002
1003
1004(defun py-clear-queue ()
1005 "Clear the queue of temporary files waiting to execute."
1006 (interactive)
1007 (let ((n (length py-file-queue)))
1008 (mapcar 'delete-file py-file-queue)
1009 (setq py-file-queue nil)
1010 (message "%d pending files de-queued." n)))
1011
1012(defun py-execute-region (start end &optional async)
1013 "Execute the the region in a Python interpreter.
1014The region is first copied into a temporary file (in the directory
1015`py-temp-directory'). If there is no Python interpreter shell
1016running, this file is executed synchronously using
1017`shell-command-on-region'. If the program is long running, use an
1018optional \\[universal-argument] to run the command asynchronously in
1019its own buffer.
1020
1021If the Python interpreter shell is running, the region is execfile()'d
1022in that shell. If you try to execute regions too quickly,
1023`python-mode' will queue them up and execute them one at a time when
1024it sees a `>>> ' prompt from Python. Each time this happens, the
1025process buffer is popped into a window (if it's not already in some
1026window) so you can see it, and a comment of the form
1027
1028 \t## working on region in file <name>...
1029
1030is inserted at the end. See also the command `py-clear-queue'."
1031 (interactive "r\nP")
1032 (or (< start end)
1033 (error "Region is empty"))
1034 (let* ((proc (get-process "Python"))
1035 (temp (make-temp-name "python"))
1036 (file (concat (file-name-as-directory py-temp-directory) temp))
1037 (outbuf "*Python Output*"))
1038 (write-region start end file nil 'nomsg)
1039 (cond
1040 ;; always run the code in it's own asynchronous subprocess
1041 (async
1042 (let* ((buf (generate-new-buffer-name "*Python Output*")))
1043 (start-process "Python" buf py-python-command "-u" file)
1044 (pop-to-buffer buf)
1045 ))
1046 ;; if the Python interpreter shell is running, queue it up for
1047 ;; execution there.
1048 (proc
1049 ;; use the existing python shell
1050 (if (not py-file-queue)
1051 (py-execute-file proc file)
1052 (push file py-file-queue)
1053 (message "File %s queued for execution" file))
1054 )
1055 (t
1056 ;; otherwise either run it synchronously in a subprocess
1057 (shell-command-on-region start end py-python-command outbuf)
1058 ))))
1059
1060;; Code execution command
1061(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001062 "Send the contents of the buffer to a Python interpreter.
1063If there is a *Python* process buffer it is used. If a clipping
1064restriction is in effect, only the accessible portion of the buffer is
1065sent. A trailing newline will be supplied if needed.
1066
1067See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001068 (interactive "P")
1069 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001071
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001072;; Electric deletion
1073(defun py-electric-backspace (arg)
1074 "Deletes preceding character or levels of indentation.
1075Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001076with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001077
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001078If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001079
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001080Otherwise, if point is at the leftmost non-whitespace character of a
1081line that is neither a continuation line nor a non-indenting comment
1082line, or if point is at the end of a blank line, this command reduces
1083the indentation to match that of the line that opened the current
1084block of code. The line that opened the block is displayed in the
1085echo area to help you keep track of where you are. With numeric arg,
1086outdents that many blocks (but not past column zero).
1087
1088Otherwise the preceding character is deleted, converting a tab to
1089spaces if needed so that only a single column position is deleted.
1090Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001091 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 (if (or (/= (current-indentation) (current-column))
1093 (bolp)
1094 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001095 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001096 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001097 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001098 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001099 ;; force non-blank so py-goto-block-up doesn't ignore it
1100 (insert-char ?* 1)
1101 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001102 (let ((base-indent 0) ; indentation of base line
1103 (base-text "") ; and text of base line
1104 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001105 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001106 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001107 (condition-case nil ; in case no enclosing block
1108 (progn
1109 (py-goto-block-up 'no-mark)
1110 (setq base-indent (current-indentation)
1111 base-text (py-suck-up-leading-text)
1112 base-found-p t))
1113 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001114 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115 (delete-char 1) ; toss the dummy character
1116 (delete-horizontal-space)
1117 (indent-to base-indent)
1118 (if base-found-p
1119 (message "Closes block: %s" base-text)))))
1120
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001121
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001122(defun py-electric-delete (arg)
1123 "Deletes preceding or following character or levels of whitespace.
1124
1125The behavior of this function depends on the variable
1126`delete-key-deletes-forward'. If this variable is nil (or does not
1127exist, as in older Emacsen), then this function behaves identical to
1128\\[c-electric-backspace].
1129
1130If `delete-key-deletes-forward' is non-nil and is supported in your
1131Emacs, then deletion occurs in the forward direction, by calling the
1132function in `py-delete-function'."
1133 (interactive "*p")
1134 (if (and (boundp 'delete-key-deletes-forward)
1135 delete-key-deletes-forward)
1136 (funcall py-delete-function arg)
1137 ;; else
1138 (py-electric-backspace arg)))
1139
1140;; required for pending-del and delsel modes
1141(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1142(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1143(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1144(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1145
1146
1147
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001148(defun py-indent-line (&optional arg)
1149 "Fix the indentation of the current line according to Python rules.
1150With \\[universal-argument], ignore outdenting rules for block
1151closing statements (e.g. return, raise, break, continue, pass)
1152
1153This function is normally bound to `indent-line-function' so
1154\\[indent-for-tab-command] will call it."
1155 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001156 (let* ((ci (current-indentation))
1157 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001158 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001159 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001160 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001161 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162 (if (/= ci need)
1163 (save-excursion
1164 (beginning-of-line)
1165 (delete-horizontal-space)
1166 (indent-to need)))
1167 (if move-to-indentation-p (back-to-indentation))))
1168
1169(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001170 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001171This is just `strives to' because correct indentation can't be computed
1172from scratch for Python code. In general, deletes the whitespace before
1173point, inserts a newline, and takes an educated guess as to how you want
1174the new line indented."
1175 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001176 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001177 (if (< ci (current-column)) ; if point beyond indentation
1178 (newline-and-indent)
1179 ;; else try to act like newline-and-indent "normally" acts
1180 (beginning-of-line)
1181 (insert-char ?\n 1)
1182 (move-to-column ci))))
1183
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001184(defun py-compute-indentation (honor-block-close-p)
1185 ;; implements all the rules for indentation computation. when
1186 ;; honor-block-close-p is non-nil, statements such as return, raise,
1187 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001188 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001189 (let ((pps (parse-partial-sexp (save-excursion
1190 (beginning-of-python-def-or-class)
1191 (point))
1192 (point))))
1193 (beginning-of-line)
1194 (cond
1195 ;; are we inside a string or comment?
1196 ((or (nth 3 pps) (nth 4 pps))
1197 (save-excursion
1198 (if (not py-align-multiline-strings-p) 0
1199 ;; skip back over blank & non-indenting comment lines
1200 ;; note: will skip a blank or non-indenting comment line
1201 ;; that happens to be a continuation line too
1202 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1203 (back-to-indentation)
1204 (current-column))))
1205 ;; are we on a continuation line?
1206 ((py-continuation-line-p)
1207 (let ((startpos (point))
1208 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001209 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001210 (if open-bracket-pos
1211 (progn
1212 ;; align with first item in list; else a normal
1213 ;; indent beyond the line with the open bracket
1214 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1215 ;; is the first list item on the same line?
1216 (skip-chars-forward " \t")
1217 (if (null (memq (following-char) '(?\n ?# ?\\)))
1218 ; yes, so line up with it
1219 (current-column)
1220 ;; first list item on another line, or doesn't exist yet
1221 (forward-line 1)
1222 (while (and (< (point) startpos)
1223 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1224 (forward-line 1))
1225 (if (< (point) startpos)
1226 ;; again mimic the first list item
1227 (current-indentation)
1228 ;; else they're about to enter the first item
1229 (goto-char open-bracket-pos)
1230 (+ (current-indentation) py-indent-offset))))
1231
1232 ;; else on backslash continuation line
1233 (forward-line -1)
1234 (if (py-continuation-line-p) ; on at least 3rd line in block
1235 (current-indentation) ; so just continue the pattern
1236 ;; else started on 2nd line in block, so indent more.
1237 ;; if base line is an assignment with a start on a RHS,
1238 ;; indent to 2 beyond the leftmost "="; else skip first
1239 ;; chunk of non-whitespace characters on base line, + 1 more
1240 ;; column
1241 (end-of-line)
1242 (setq endpos (point) searching t)
1243 (back-to-indentation)
1244 (setq startpos (point))
1245 ;; look at all "=" from left to right, stopping at first
1246 ;; one not nested in a list or string
1247 (while searching
1248 (skip-chars-forward "^=" endpos)
1249 (if (= (point) endpos)
1250 (setq searching nil)
1251 (forward-char 1)
1252 (setq state (parse-partial-sexp startpos (point)))
1253 (if (and (zerop (car state)) ; not in a bracket
1254 (null (nth 3 state))) ; & not in a string
1255 (progn
1256 (setq searching nil) ; done searching in any case
1257 (setq found
1258 (not (or
1259 (eq (following-char) ?=)
1260 (memq (char-after (- (point) 2))
1261 '(?< ?> ?!)))))))))
1262 (if (or (not found) ; not an assignment
1263 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1264 (progn
1265 (goto-char startpos)
1266 (skip-chars-forward "^ \t\n")))
1267 (1+ (current-column))))))
1268
1269 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001270 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001271
Barry Warsawa7891711996-08-01 15:53:09 +00001272 ;; Dfn: "Indenting comment line". A line containing only a
1273 ;; comment, but which is treated like a statement for
1274 ;; indentation calculation purposes. Such lines are only
1275 ;; treated specially by the mode; they are not treated
1276 ;; specially by the Python interpreter.
1277
1278 ;; The rules for indenting comment lines are a line where:
1279 ;; - the first non-whitespace character is `#', and
1280 ;; - the character following the `#' is whitespace, and
1281 ;; - the line is outdented with respect to (i.e. to the left
1282 ;; of) the indentation of the preceding non-blank line.
1283
1284 ;; The first non-blank line following an indenting comment
1285 ;; line is given the same amount of indentation as the
1286 ;; indenting comment line.
1287
1288 ;; All other comment-only lines are ignored for indentation
1289 ;; purposes.
1290
1291 ;; Are we looking at a comment-only line which is *not* an
1292 ;; indenting comment line? If so, we assume that its been
1293 ;; placed at the desired indentation, so leave it alone.
1294 ;; Indenting comment lines are aligned as statements down
1295 ;; below.
1296 ((and (looking-at "[ \t]*#[^ \t\n]")
1297 ;; NOTE: this test will not be performed in older Emacsen
1298 (fboundp 'forward-comment)
1299 (<= (current-indentation)
1300 (save-excursion
1301 (forward-comment (- (point-max)))
1302 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001303 (current-indentation))
1304
1305 ;; else indentation based on that of the statement that
1306 ;; precedes us; use the first line of that statement to
1307 ;; establish the base, in case the user forced a non-std
1308 ;; indentation for the continuation lines (if any)
1309 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001310 ;; skip back over blank & non-indenting comment lines note:
1311 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001312 ;; happens to be a continuation line too. use fast Emacs 19
1313 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001314 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001315 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001316 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001317 (let (done)
1318 (while (not done)
1319 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1320 nil 'move)
1321 (setq done (or (eq py-honor-comment-indentation t)
1322 (bobp)
1323 (/= (following-char) ?#)
1324 (not (zerop (current-column)))))
1325 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001326 ;; if we landed inside a string, go to the beginning of that
1327 ;; string. this handles triple quoted, multi-line spanning
1328 ;; strings.
1329 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001330 (+ (current-indentation)
1331 (if (py-statement-opens-block-p)
1332 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001333 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001334 (- py-indent-offset)
1335 0)))
1336 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001337
1338(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001339 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001341`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001342Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001343`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001344their own buffer-local copy), both those currently existing and those
1345created later in the Emacs session.
1346
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001347Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001348There's no excuse for such foolishness, but sometimes you have to deal
1349with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001350`py-indent-offset' to what it thinks it was when they created the
1351mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
1353Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001354looking for a line that opens a block of code. `py-indent-offset' is
1355set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356statement following it. If the search doesn't succeed going forward,
1357it's tried again going backward."
1358 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359 (let (new-value
1360 (start (point))
1361 restart
1362 (found nil)
1363 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001364 (py-goto-initial-line)
1365 (while (not (or found (eobp)))
1366 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1367 (progn
1368 (setq restart (point))
1369 (py-goto-initial-line)
1370 (if (py-statement-opens-block-p)
1371 (setq found t)
1372 (goto-char restart)))))
1373 (if found
1374 ()
1375 (goto-char start)
1376 (py-goto-initial-line)
1377 (while (not (or found (bobp)))
1378 (setq found
1379 (and
1380 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1381 (or (py-goto-initial-line) t) ; always true -- side effect
1382 (py-statement-opens-block-p)))))
1383 (setq colon-indent (current-indentation)
1384 found (and found (zerop (py-next-statement 1)))
1385 new-value (- (current-indentation) colon-indent))
1386 (goto-char start)
1387 (if found
1388 (progn
1389 (funcall (if global 'kill-local-variable 'make-local-variable)
1390 'py-indent-offset)
1391 (setq py-indent-offset new-value)
1392 (message "%s value of py-indent-offset set to %d"
1393 (if global "Global" "Local")
1394 py-indent-offset))
1395 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1396
1397(defun py-shift-region (start end count)
1398 (save-excursion
1399 (goto-char end) (beginning-of-line) (setq end (point))
1400 (goto-char start) (beginning-of-line) (setq start (point))
1401 (indent-rigidly start end count)))
1402
1403(defun py-shift-region-left (start end &optional count)
1404 "Shift region of Python code to the left.
1405The lines from the line containing the start of the current region up
1406to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001407shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001408
1409If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001410many columns. With no active region, outdent only the current line.
1411You cannot outdent the region if any line is already at column zero."
1412 (interactive
1413 (let ((p (point))
1414 (m (mark))
1415 (arg current-prefix-arg))
1416 (if m
1417 (list (min p m) (max p m) arg)
1418 (list p (save-excursion (forward-line 1) (point)) arg))))
1419 ;; if any line is at column zero, don't shift the region
1420 (save-excursion
1421 (goto-char start)
1422 (while (< (point) end)
1423 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001424 (if (and (zerop (current-column))
1425 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001426 (error "Region is at left edge."))
1427 (forward-line 1)))
1428 (py-shift-region start end (- (prefix-numeric-value
1429 (or count py-indent-offset))))
1430 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001431
1432(defun py-shift-region-right (start end &optional count)
1433 "Shift region of Python code to the right.
1434The lines from the line containing the start of the current region up
1435to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001436shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001437
1438If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001439many columns. With no active region, indent only the current line."
1440 (interactive
1441 (let ((p (point))
1442 (m (mark))
1443 (arg current-prefix-arg))
1444 (if m
1445 (list (min p m) (max p m) arg)
1446 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001447 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001448 (or count py-indent-offset)))
1449 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001450
1451(defun py-indent-region (start end &optional indent-offset)
1452 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001453
Barry Warsaw7ae77681994-12-12 20:38:05 +00001454The lines from the line containing the start of the current region up
1455to (but not including) the line containing the end of the region are
1456reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457character in the first column, the first line is left alone and the
1458rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001459region is reindented with respect to the (closest code or indenting
1460comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461
1462This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001463control structures are introduced or removed, or to reformat code
1464using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001465
1466If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001467the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001468used.
1469
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001470Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001471is called! This function does not compute proper indentation from
1472scratch (that's impossible in Python), it merely adjusts the existing
1473indentation to be correct in context.
1474
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001475Warning: This function really has no idea what to do with
1476non-indenting comment lines, and shifts them as if they were indenting
1477comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001478
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479Special cases: whitespace is deleted from blank lines; continuation
1480lines are shifted by the same amount their initial line was shifted,
1481in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001482initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001483 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001484 (save-excursion
1485 (goto-char end) (beginning-of-line) (setq end (point-marker))
1486 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001487 (let ((py-indent-offset (prefix-numeric-value
1488 (or indent-offset py-indent-offset)))
1489 (indents '(-1)) ; stack of active indent levels
1490 (target-column 0) ; column to which to indent
1491 (base-shifted-by 0) ; amount last base line was shifted
1492 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001493 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001494 0))
1495 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001496 (while (< (point) end)
1497 (setq ci (current-indentation))
1498 ;; figure out appropriate target column
1499 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001500 ((or (eq (following-char) ?#) ; comment in column 1
1501 (looking-at "[ \t]*$")) ; entirely blank
1502 (setq target-column 0))
1503 ((py-continuation-line-p) ; shift relative to base line
1504 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001505 (t ; new base line
1506 (if (> ci (car indents)) ; going deeper; push it
1507 (setq indents (cons ci indents))
1508 ;; else we should have seen this indent before
1509 (setq indents (memq ci indents)) ; pop deeper indents
1510 (if (null indents)
1511 (error "Bad indentation in region, at line %d"
1512 (save-restriction
1513 (widen)
1514 (1+ (count-lines 1 (point)))))))
1515 (setq target-column (+ indent-base
1516 (* py-indent-offset
1517 (- (length indents) 2))))
1518 (setq base-shifted-by (- target-column ci))))
1519 ;; shift as needed
1520 (if (/= ci target-column)
1521 (progn
1522 (delete-horizontal-space)
1523 (indent-to target-column)))
1524 (forward-line 1))))
1525 (set-marker end nil))
1526
Barry Warsawa7891711996-08-01 15:53:09 +00001527(defun py-comment-region (beg end &optional arg)
1528 "Like `comment-region' but uses double hash (`#') comment starter."
1529 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001530 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001531 (comment-region beg end arg)))
1532
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001533
1534;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001535(defun py-previous-statement (count)
1536 "Go to the start of previous Python statement.
1537If the statement at point is the i'th Python statement, goes to the
1538start of statement i-COUNT. If there is no such statement, goes to the
1539first statement. Returns count of statements left to move.
1540`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001542 (if (< count 0) (py-next-statement (- count))
1543 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001544 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547 (> count 0)
1548 (zerop (forward-line -1))
1549 (py-goto-statement-at-or-above))
1550 (setq count (1- count)))
1551 (if (> count 0) (goto-char start)))
1552 count))
1553
1554(defun py-next-statement (count)
1555 "Go to the start of next Python statement.
1556If the statement at point is the i'th Python statement, goes to the
1557start of statement i+COUNT. If there is no such statement, goes to the
1558last statement. Returns count of statements left to move. `Statements'
1559do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001561 (if (< count 0) (py-previous-statement (- count))
1562 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001563 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001565 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566 (> count 0)
1567 (py-goto-statement-below))
1568 (setq count (1- count)))
1569 (if (> count 0) (goto-char start)))
1570 count))
1571
1572(defun py-goto-block-up (&optional nomark)
1573 "Move up to start of current block.
1574Go to the statement that starts the smallest enclosing block; roughly
1575speaking, this will be the closest preceding statement that ends with a
1576colon and is indented less than the statement you started on. If
1577successful, also sets the mark to the starting point.
1578
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579`\\[py-mark-block]' can be used afterward to mark the whole code
1580block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581
1582If called from a program, the mark will not be set if optional argument
1583NOMARK is not nil."
1584 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001585 (let ((start (point))
1586 (found nil)
1587 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588 (py-goto-initial-line)
1589 ;; if on blank or non-indenting comment line, use the preceding stmt
1590 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1591 (progn
1592 (py-goto-statement-at-or-above)
1593 (setq found (py-statement-opens-block-p))))
1594 ;; search back for colon line indented less
1595 (setq initial-indent (current-indentation))
1596 (if (zerop initial-indent)
1597 ;; force fast exit
1598 (goto-char (point-min)))
1599 (while (not (or found (bobp)))
1600 (setq found
1601 (and
1602 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1603 (or (py-goto-initial-line) t) ; always true -- side effect
1604 (< (current-indentation) initial-indent)
1605 (py-statement-opens-block-p))))
1606 (if found
1607 (progn
1608 (or nomark (push-mark start))
1609 (back-to-indentation))
1610 (goto-char start)
1611 (error "Enclosing block not found"))))
1612
1613(defun beginning-of-python-def-or-class (&optional class)
1614 "Move point to start of def (or class, with prefix arg).
1615
1616Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001617arg, looks for a `class' instead. The docs assume the `def' case;
1618just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001619
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001620If point is in a def statement already, and after the `d', simply
1621moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001622
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001623Else (point is not in a def statement, or at or before the `d' of a
1624def statement), searches for the closest preceding def statement, and
1625leaves point at its start. If no such statement can be found, leaves
1626point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001627
1628Returns t iff a def statement is found by these rules.
1629
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001630Note that doing this command repeatedly will take you closer to the
1631start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001633If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001634`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001635 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001636 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1637 (start-of-line (progn (beginning-of-line) (point)))
1638 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001639 (if (or (/= start-of-stmt start-of-line)
1640 (not at-or-before-p))
1641 (end-of-line)) ; OK to match on this line
1642 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001643 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001644
1645(defun end-of-python-def-or-class (&optional class)
1646 "Move point beyond end of def (or class, with prefix arg) body.
1647
1648By default, looks for an appropriate `def'. If you supply a prefix arg,
1649looks for a `class' instead. The docs assume the `def' case; just
1650substitute `class' for `def' for the other case.
1651
1652If point is in a def statement already, this is the def we use.
1653
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001654Else if the def found by `\\[beginning-of-python-def-or-class]'
1655contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
1657Else we search forward for the closest following def, and use that.
1658
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659If a def can be found by these rules, point is moved to the start of
1660the line immediately following the def block, and the position of the
1661start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001662
1663Else point is moved to the end of the buffer, and nil is returned.
1664
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001665Note that doing this command repeatedly will take you closer to the
1666end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001668If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001669`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001670 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671 (let ((start (progn (py-goto-initial-line) (point)))
1672 (which (if class "class" "def"))
1673 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674 ;; move point to start of appropriate def/class
1675 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1676 (setq state 'at-beginning)
1677 ;; else see if beginning-of-python-def-or-class hits container
1678 (if (and (beginning-of-python-def-or-class class)
1679 (progn (py-goto-beyond-block)
1680 (> (point) start)))
1681 (setq state 'at-end)
1682 ;; else search forward
1683 (goto-char start)
1684 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1685 (progn (setq state 'at-beginning)
1686 (beginning-of-line)))))
1687 (cond
1688 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1689 ((eq state 'at-end) t)
1690 ((eq state 'not-found) nil)
1691 (t (error "internal error in end-of-python-def-or-class")))))
1692
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001693
1694;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001695(defun py-mark-block (&optional extend just-move)
1696 "Mark following block of lines. With prefix arg, mark structure.
1697Easier to use than explain. It sets the region to an `interesting'
1698block of succeeding lines. If point is on a blank line, it goes down to
1699the next non-blank line. That will be the start of the region. The end
1700of the region depends on the kind of line at the start:
1701
1702 - If a comment, the region will include all succeeding comment lines up
1703 to (but not including) the next non-comment line (if any).
1704
1705 - Else if a prefix arg is given, and the line begins one of these
1706 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001707
1708 if elif else try except finally for while def class
1709
Barry Warsaw7ae77681994-12-12 20:38:05 +00001710 the region will be set to the body of the structure, including
1711 following blocks that `belong' to it, but excluding trailing blank
1712 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001713 and all (if any) of the following `except' and `finally' blocks
1714 that belong to the `try' structure will be in the region. Ditto
1715 for if/elif/else, for/else and while/else structures, and (a bit
1716 degenerate, since they're always one-block structures) def and
1717 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718
1719 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001720 block (see list above), and the block is not a `one-liner' (i.e.,
1721 the statement ends with a colon, not with code), the region will
1722 include all succeeding lines up to (but not including) the next
1723 code statement (if any) that's indented no more than the starting
1724 line, except that trailing blank and comment lines are excluded.
1725 E.g., if the starting line begins a multi-statement `def'
1726 structure, the region will be set to the full function definition,
1727 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001728
1729 - Else the region will include all succeeding lines up to (but not
1730 including) the next blank line, or code or indenting-comment line
1731 indented strictly less than the starting line. Trailing indenting
1732 comment lines are included in this case, but not trailing blank
1733 lines.
1734
1735A msg identifying the location of the mark is displayed in the echo
1736area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1737
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738If called from a program, optional argument EXTEND plays the role of
1739the prefix arg, and if optional argument JUST-MOVE is not nil, just
1740moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001741 (interactive "P") ; raw prefix arg
1742 (py-goto-initial-line)
1743 ;; skip over blank lines
1744 (while (and
1745 (looking-at "[ \t]*$") ; while blank line
1746 (not (eobp))) ; & somewhere to go
1747 (forward-line 1))
1748 (if (eobp)
1749 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001750 (let ((initial-pos (point))
1751 (initial-indent (current-indentation))
1752 last-pos ; position of last stmt in region
1753 (followers
1754 '((if elif else) (elif elif else) (else)
1755 (try except finally) (except except) (finally)
1756 (for else) (while else)
1757 (def) (class) ) )
1758 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001759
1760 (cond
1761 ;; if comment line, suck up the following comment lines
1762 ((looking-at "[ \t]*#")
1763 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1764 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1765 (setq last-pos (point)))
1766
1767 ;; else if line is a block line and EXTEND given, suck up
1768 ;; the whole structure
1769 ((and extend
1770 (setq first-symbol (py-suck-up-first-keyword) )
1771 (assq first-symbol followers))
1772 (while (and
1773 (or (py-goto-beyond-block) t) ; side effect
1774 (forward-line -1) ; side effect
1775 (setq last-pos (point)) ; side effect
1776 (py-goto-statement-below)
1777 (= (current-indentation) initial-indent)
1778 (setq next-symbol (py-suck-up-first-keyword))
1779 (memq next-symbol (cdr (assq first-symbol followers))))
1780 (setq first-symbol next-symbol)))
1781
1782 ;; else if line *opens* a block, search for next stmt indented <=
1783 ((py-statement-opens-block-p)
1784 (while (and
1785 (setq last-pos (point)) ; always true -- side effect
1786 (py-goto-statement-below)
1787 (> (current-indentation) initial-indent))
1788 nil))
1789
1790 ;; else plain code line; stop at next blank line, or stmt or
1791 ;; indenting comment line indented <
1792 (t
1793 (while (and
1794 (setq last-pos (point)) ; always true -- side effect
1795 (or (py-goto-beyond-final-line) t)
1796 (not (looking-at "[ \t]*$")) ; stop at blank line
1797 (or
1798 (>= (current-indentation) initial-indent)
1799 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1800 nil)))
1801
1802 ;; skip to end of last stmt
1803 (goto-char last-pos)
1804 (py-goto-beyond-final-line)
1805
1806 ;; set mark & display
1807 (if just-move
1808 () ; just return
1809 (push-mark (point) 'no-msg)
1810 (forward-line -1)
1811 (message "Mark set after: %s" (py-suck-up-leading-text))
1812 (goto-char initial-pos))))
1813
Barry Warsaw2518c671997-11-05 00:51:08 +00001814(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001815 "Set region to body of def (or class, with prefix arg) enclosing point.
1816Pushes the current mark, then point, on the mark ring (all language
1817modes do this, but although it's handy it's never documented ...).
1818
1819In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001820hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1821`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822
1823And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001824Turned out that was more confusing than useful: the `goto start' and
1825`goto end' commands are usually used to search through a file, and
1826people expect them to act a lot like `search backward' and `search
1827forward' string-search commands. But because Python `def' and `class'
1828can nest to arbitrary levels, finding the smallest def containing
1829point cannot be done via a simple backward search: the def containing
1830point may not be the closest preceding def, or even the closest
1831preceding def that's indented less. The fancy algorithm required is
1832appropriate for the usual uses of this `mark' command, but not for the
1833`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001835So the def marked by this command may not be the one either of the
1836`goto' commands find: If point is on a blank or non-indenting comment
1837line, moves back to start of the closest preceding code statement or
1838indenting comment line. If this is a `def' statement, that's the def
1839we use. Else searches for the smallest enclosing `def' block and uses
1840that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001841
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001842When an enclosing def is found: The mark is left immediately beyond
1843the last line of the def block. Point is left at the start of the
1844def, except that: if the def is preceded by a number of comment lines
1845followed by (at most) one optional blank line, point is left at the
1846start of the comments; else if the def is preceded by a blank line,
1847point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848
1849The intent is to mark the containing def/class and its associated
1850documentation, to make moving and duplicating functions and classes
1851pleasant."
1852 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853 (let ((start (point))
1854 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855 (push-mark start)
1856 (if (not (py-go-up-tree-to-keyword which))
1857 (progn (goto-char start)
1858 (error "Enclosing %s not found" which))
1859 ;; else enclosing def/class found
1860 (setq start (point))
1861 (py-goto-beyond-block)
1862 (push-mark (point))
1863 (goto-char start)
1864 (if (zerop (forward-line -1)) ; if there is a preceding line
1865 (progn
1866 (if (looking-at "[ \t]*$") ; it's blank
1867 (setq start (point)) ; so reset start point
1868 (goto-char start)) ; else try again
1869 (if (zerop (forward-line -1))
1870 (if (looking-at "[ \t]*#") ; a comment
1871 ;; look back for non-comment line
1872 ;; tricky: note that the regexp matches a blank
1873 ;; line, cuz \n is in the 2nd character class
1874 (and
1875 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1876 (forward-line 1))
1877 ;; no comment, so go back
1878 (goto-char start))))))))
1879
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001880;; ripped from cc-mode
1881(defun py-forward-into-nomenclature (&optional arg)
1882 "Move forward to end of a nomenclature section or word.
1883With arg, to it arg times.
1884
1885A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1886 (interactive "p")
1887 (let ((case-fold-search nil))
1888 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001889 (re-search-forward
1890 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1891 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001892 (while (and (< arg 0)
1893 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001894 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001895 (point-min) 0))
1896 (forward-char 1)
1897 (setq arg (1+ arg)))))
1898 (py-keep-region-active))
1899
1900(defun py-backward-into-nomenclature (&optional arg)
1901 "Move backward to beginning of a nomenclature section or word.
1902With optional ARG, move that many times. If ARG is negative, move
1903forward.
1904
1905A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1906 (interactive "p")
1907 (py-forward-into-nomenclature (- arg))
1908 (py-keep-region-active))
1909
1910
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001911
1912;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001913
1914;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001915;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1916;; out of the right places, along with the keys they're on & current
1917;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918(defun py-dump-help-string (str)
1919 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001920 (let ((locals (buffer-local-variables))
1921 funckind funcname func funcdoc
1922 (start 0) mstart end
1923 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001924 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1925 (setq mstart (match-beginning 0) end (match-end 0)
1926 funckind (substring str (match-beginning 1) (match-end 1))
1927 funcname (substring str (match-beginning 2) (match-end 2))
1928 func (intern funcname))
1929 (princ (substitute-command-keys (substring str start mstart)))
1930 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001931 ((equal funckind "c") ; command
1932 (setq funcdoc (documentation func)
1933 keys (concat
1934 "Key(s): "
1935 (mapconcat 'key-description
1936 (where-is-internal func py-mode-map)
1937 ", "))))
1938 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001939 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940 keys (if (assq func locals)
1941 (concat
1942 "Local/Global values: "
1943 (prin1-to-string (symbol-value func))
1944 " / "
1945 (prin1-to-string (default-value func)))
1946 (concat
1947 "Value: "
1948 (prin1-to-string (symbol-value func))))))
1949 (t ; unexpected
1950 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (princ (format "\n-> %s:\t%s\t%s\n\n"
1952 (if (equal funckind "c") "Command" "Variable")
1953 funcname keys))
1954 (princ funcdoc)
1955 (terpri)
1956 (setq start end))
1957 (princ (substitute-command-keys (substring str start))))
1958 (print-help-return-message)))
1959
1960(defun py-describe-mode ()
1961 "Dump long form of Python-mode docs."
1962 (interactive)
1963 (py-dump-help-string "Major mode for editing Python files.
1964Knows about Python indentation, tokens, comments and continuation lines.
1965Paragraphs are separated by blank lines only.
1966
1967Major sections below begin with the string `@'; specific function and
1968variable docs begin with `->'.
1969
1970@EXECUTING PYTHON CODE
1971
1972\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1973\\[py-execute-region]\tsends the current region
1974\\[py-shell]\tstarts a Python interpreter window; this will be used by
1975\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1976%c:py-execute-buffer
1977%c:py-execute-region
1978%c:py-shell
1979
1980@VARIABLES
1981
1982py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001983py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001984
1985py-python-command\tshell command to invoke Python interpreter
1986py-scroll-process-buffer\talways scroll Python process buffer
1987py-temp-directory\tdirectory used for temp files (if needed)
1988
1989py-beep-if-tab-change\tring the bell if tab-width is changed
1990%v:py-indent-offset
1991%v:py-block-comment-prefix
1992%v:py-python-command
1993%v:py-scroll-process-buffer
1994%v:py-temp-directory
1995%v:py-beep-if-tab-change
1996
1997@KINDS OF LINES
1998
1999Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000preceding line ends with a backslash that's not part of a comment, or
2001the paren/bracket/brace nesting level at the start of the line is
2002non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002003
2004An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002005possibly blanks or tabs), a `comment line' (leftmost non-blank
2006character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002007
2008Comment Lines
2009
2010Although all comment lines are treated alike by Python, Python mode
2011recognizes two kinds that act differently with respect to indentation.
2012
2013An `indenting comment line' is a comment line with a blank, tab or
2014nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002015treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002016indenting comment line will be indented like the comment line. All
2017other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002018following the initial `#') are `non-indenting comment lines', and
2019their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020
2021Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002022whenever possible. Non-indenting comment lines are useful in cases
2023like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002024
2025\ta = b # a very wordy single-line comment that ends up being
2026\t #... continued onto another line
2027
2028\tif a == b:
2029##\t\tprint 'panic!' # old code we've `commented out'
2030\t\treturn a
2031
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002032Since the `#...' and `##' comment lines have a non-whitespace
2033character following the initial `#', Python mode ignores them when
2034computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002035
2036Continuation Lines and Statements
2037
2038The Python-mode commands generally work on statements instead of on
2039individual lines, where a `statement' is a comment or blank line, or a
2040code line and all of its following continuation lines (if any)
2041considered as a single logical unit. The commands in this mode
2042generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002043statement containing point, even if point happens to be in the middle
2044of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002045
2046
2047@INDENTATION
2048
2049Primarily for entering new code:
2050\t\\[indent-for-tab-command]\t indent line appropriately
2051\t\\[py-newline-and-indent]\t insert newline, then indent
2052\t\\[py-delete-char]\t reduce indentation, or delete single character
2053
2054Primarily for reindenting existing code:
2055\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2056\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2057
2058\t\\[py-indent-region]\t reindent region to match its context
2059\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2060\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2061
2062Unlike most programming languages, Python uses indentation, and only
2063indentation, to specify block structure. Hence the indentation supplied
2064automatically by Python-mode is just an educated guess: only you know
2065the block structure you intend, so only you can supply correct
2066indentation.
2067
2068The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2069the indentation of preceding statements. E.g., assuming
2070py-indent-offset is 4, after you enter
2071\tif a > 0: \\[py-newline-and-indent]
2072the cursor will be moved to the position of the `_' (_ is not a
2073character in the file, it's just used here to indicate the location of
2074the cursor):
2075\tif a > 0:
2076\t _
2077If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2078to
2079\tif a > 0:
2080\t c = d
2081\t _
2082Python-mode cannot know whether that's what you intended, or whether
2083\tif a > 0:
2084\t c = d
2085\t_
2086was your intent. In general, Python-mode either reproduces the
2087indentation of the (closest code or indenting-comment) preceding
2088statement, or adds an extra py-indent-offset blanks if the preceding
2089statement has `:' as its last significant (non-whitespace and non-
2090comment) character. If the suggested indentation is too much, use
2091\\[py-delete-char] to reduce it.
2092
2093Continuation lines are given extra indentation. If you don't like the
2094suggested indentation, change it to something you do like, and Python-
2095mode will strive to indent later lines of the statement in the same way.
2096
2097If a line is a continuation line by virtue of being in an unclosed
2098paren/bracket/brace structure (`list', for short), the suggested
2099indentation depends on whether the current line contains the first item
2100in the list. If it does, it's indented py-indent-offset columns beyond
2101the indentation of the line containing the open bracket. If you don't
2102like that, change it by hand. The remaining items in the list will mimic
2103whatever indentation you give to the first item.
2104
2105If a line is a continuation line because the line preceding it ends with
2106a backslash, the third and following lines of the statement inherit their
2107indentation from the line preceding them. The indentation of the second
2108line in the statement depends on the form of the first (base) line: if
2109the base line is an assignment statement with anything more interesting
2110than the backslash following the leftmost assigning `=', the second line
2111is indented two columns beyond that `='. Else it's indented to two
2112columns beyond the leftmost solid chunk of non-whitespace characters on
2113the base line.
2114
2115Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2116repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2117structure you intend.
2118%c:indent-for-tab-command
2119%c:py-newline-and-indent
2120%c:py-delete-char
2121
2122
2123The next function may be handy when editing code you didn't write:
2124%c:py-guess-indent-offset
2125
2126
2127The remaining `indent' functions apply to a region of Python code. They
2128assume the block structure (equals indentation, in Python) of the region
2129is correct, and alter the indentation in various ways while preserving
2130the block structure:
2131%c:py-indent-region
2132%c:py-shift-region-left
2133%c:py-shift-region-right
2134
2135@MARKING & MANIPULATING REGIONS OF CODE
2136
2137\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002138\\[py-mark-def-or-class]\t mark smallest enclosing def
2139\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002140\\[comment-region]\t comment out region of code
2141\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002142%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002143%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002144%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002145
2146@MOVING POINT
2147
2148\\[py-previous-statement]\t move to statement preceding point
2149\\[py-next-statement]\t move to statement following point
2150\\[py-goto-block-up]\t move up to start of current block
2151\\[beginning-of-python-def-or-class]\t move to start of def
2152\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2153\\[end-of-python-def-or-class]\t move to end of def
2154\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2155
2156The first two move to one statement beyond the statement that contains
2157point. A numeric prefix argument tells them to move that many
2158statements instead. Blank lines, comment lines, and continuation lines
2159do not count as `statements' for these commands. So, e.g., you can go
2160to the first code statement in a file by entering
2161\t\\[beginning-of-buffer]\t to move to the top of the file
2162\t\\[py-next-statement]\t to skip over initial comments and blank lines
2163Or do `\\[py-previous-statement]' with a huge prefix argument.
2164%c:py-previous-statement
2165%c:py-next-statement
2166%c:py-goto-block-up
2167%c:beginning-of-python-def-or-class
2168%c:end-of-python-def-or-class
2169
2170@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2171
2172`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2173
2174`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2175overall class and def structure of a module.
2176
2177`\\[back-to-indentation]' moves point to a line's first non-blank character.
2178
2179`\\[indent-relative]' is handy for creating odd indentation.
2180
2181@OTHER EMACS HINTS
2182
2183If you don't like the default value of a variable, change its value to
2184whatever you do like by putting a `setq' line in your .emacs file.
2185E.g., to set the indentation increment to 4, put this line in your
2186.emacs:
2187\t(setq py-indent-offset 4)
2188To see the value of a variable, do `\\[describe-variable]' and enter the variable
2189name at the prompt.
2190
2191When entering a key sequence like `C-c C-n', it is not necessary to
2192release the CONTROL key after doing the `C-c' part -- it suffices to
2193press the CONTROL key, press and release `c' (while still holding down
2194CONTROL), press and release `n' (while still holding down CONTROL), &
2195then release CONTROL.
2196
2197Entering Python mode calls with no arguments the value of the variable
2198`python-mode-hook', if that value exists and is not nil; for backward
2199compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2200the Elisp manual for details.
2201
2202Obscure: When python-mode is first loaded, it looks for all bindings
2203to newline-and-indent in the global keymap, and shadows them with
2204local bindings to py-newline-and-indent."))
2205
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002206
2207;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002208(defvar py-parse-state-re
2209 (concat
2210 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2211 "\\|"
2212 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002213
Barry Warsaw7ae77681994-12-12 20:38:05 +00002214;; returns the parse state at point (see parse-partial-sexp docs)
2215(defun py-parse-state ()
2216 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002217 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002218 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002219 (while (not done)
2220 ;; back up to the first preceding line (if any; else start of
2221 ;; buffer) that begins with a popular Python keyword, or a
2222 ;; non- whitespace and non-comment character. These are good
2223 ;; places to start parsing to see whether where we started is
2224 ;; at a non-zero nesting level. It may be slow for people who
2225 ;; write huge code blocks or huge lists ... tough beans.
2226 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002227 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002228 (beginning-of-line)
2229 (save-excursion
2230 (setq pps (parse-partial-sexp (point) here)))
2231 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002232 (setq done (or (zerop ci)
2233 (not (nth 3 pps))
2234 (bobp)))
2235 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002236 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002237
2238;; if point is at a non-zero nesting level, returns the number of the
2239;; character that opens the smallest enclosing unclosed list; else
2240;; returns nil.
2241(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002242 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002243 (if (zerop (car status))
2244 nil ; not in a nest
2245 (car (cdr status))))) ; char# of open bracket
2246
2247;; t iff preceding line ends with backslash that's not in a comment
2248(defun py-backslash-continuation-line-p ()
2249 (save-excursion
2250 (beginning-of-line)
2251 (and
2252 ;; use a cheap test first to avoid the regexp if possible
2253 ;; use 'eq' because char-after may return nil
2254 (eq (char-after (- (point) 2)) ?\\ )
2255 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002256 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002257 (looking-at py-continued-re))))
2258
2259;; t iff current line is a continuation line
2260(defun py-continuation-line-p ()
2261 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002262 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002263 (or (py-backslash-continuation-line-p)
2264 (py-nesting-level))))
2265
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002266;; go to initial line of current statement; usually this is the line
2267;; we're on, but if we're on the 2nd or following lines of a
2268;; continuation block, we need to go up to the first line of the
2269;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002270;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002271;; Tricky: We want to avoid quadratic-time behavior for long continued
2272;; blocks, whether of the backslash or open-bracket varieties, or a
2273;; mix of the two. The following manages to do that in the usual
2274;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002275(defun py-goto-initial-line ()
2276 (let ( open-bracket-pos )
2277 (while (py-continuation-line-p)
2278 (beginning-of-line)
2279 (if (py-backslash-continuation-line-p)
2280 (while (py-backslash-continuation-line-p)
2281 (forward-line -1))
2282 ;; else zip out of nested brackets/braces/parens
2283 (while (setq open-bracket-pos (py-nesting-level))
2284 (goto-char open-bracket-pos)))))
2285 (beginning-of-line))
2286
2287;; go to point right beyond final line of current statement; usually
2288;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002289;; statement we need to skip over the continuation lines. Tricky:
2290;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002291(defun py-goto-beyond-final-line ()
2292 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002293 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002294 (while (and (py-continuation-line-p)
2295 (not (eobp)))
2296 ;; skip over the backslash flavor
2297 (while (and (py-backslash-continuation-line-p)
2298 (not (eobp)))
2299 (forward-line 1))
2300 ;; if in nest, zip to the end of the nest
2301 (setq state (py-parse-state))
2302 (if (and (not (zerop (car state)))
2303 (not (eobp)))
2304 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002305 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306 (forward-line 1))))))
2307
2308;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002309;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002310(defun py-statement-opens-block-p ()
2311 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002312 (let ((start (point))
2313 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2314 (searching t)
2315 (answer nil)
2316 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002317 (goto-char start)
2318 (while searching
2319 ;; look for a colon with nothing after it except whitespace, and
2320 ;; maybe a comment
2321 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2322 finish t)
2323 (if (eq (point) finish) ; note: no `else' clause; just
2324 ; keep searching if we're not at
2325 ; the end yet
2326 ;; sure looks like it opens a block -- but it might
2327 ;; be in a comment
2328 (progn
2329 (setq searching nil) ; search is done either way
2330 (setq state (parse-partial-sexp start
2331 (match-beginning 0)))
2332 (setq answer (not (nth 4 state)))))
2333 ;; search failed: couldn't find another interesting colon
2334 (setq searching nil)))
2335 answer)))
2336
Barry Warsawf831d811996-07-31 20:42:59 +00002337(defun py-statement-closes-block-p ()
2338 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002339 ;; starts with `return', `raise', `break', `continue', and `pass'.
2340 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002341 (let ((here (point)))
2342 (back-to-indentation)
2343 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002344 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002345 (goto-char here))))
2346
Barry Warsaw7ae77681994-12-12 20:38:05 +00002347;; go to point right beyond final line of block begun by the current
2348;; line. This is the same as where py-goto-beyond-final-line goes
2349;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002350;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002351(defun py-goto-beyond-block ()
2352 (if (py-statement-opens-block-p)
2353 (py-mark-block nil 'just-move)
2354 (py-goto-beyond-final-line)))
2355
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002356;; go to start of first statement (not blank or comment or
2357;; continuation line) at or preceding point. returns t if there is
2358;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002359(defun py-goto-statement-at-or-above ()
2360 (py-goto-initial-line)
2361 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002362 ;; skip back over blank & comment lines
2363 ;; note: will skip a blank or comment line that happens to be
2364 ;; a continuation line too
2365 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2366 (progn (py-goto-initial-line) t)
2367 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002368 t))
2369
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002370;; go to start of first statement (not blank or comment or
2371;; continuation line) following the statement containing point returns
2372;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002373(defun py-goto-statement-below ()
2374 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002375 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002376 (py-goto-beyond-final-line)
2377 (while (and
2378 (looking-at py-blank-or-comment-re)
2379 (not (eobp)))
2380 (forward-line 1))
2381 (if (eobp)
2382 (progn (goto-char start) nil)
2383 t)))
2384
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002385;; go to start of statement, at or preceding point, starting with
2386;; keyword KEY. Skips blank lines and non-indenting comments upward
2387;; first. If that statement starts with KEY, done, else go back to
2388;; first enclosing block starting with KEY. If successful, leaves
2389;; point at the start of the KEY line & returns t. Else leaves point
2390;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002391(defun py-go-up-tree-to-keyword (key)
2392 ;; skip blanks and non-indenting #
2393 (py-goto-initial-line)
2394 (while (and
2395 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2396 (zerop (forward-line -1))) ; go back
2397 nil)
2398 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002399 (let* ((re (concat "[ \t]*" key "\\b"))
2400 (case-fold-search nil) ; let* so looking-at sees this
2401 (found (looking-at re))
2402 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002403 (while (not (or found dead))
2404 (condition-case nil ; in case no enclosing block
2405 (py-goto-block-up 'no-mark)
2406 (error (setq dead t)))
2407 (or dead (setq found (looking-at re))))
2408 (beginning-of-line)
2409 found))
2410
2411;; return string in buffer from start of indentation to end of line;
2412;; prefix "..." if leading whitespace was skipped
2413(defun py-suck-up-leading-text ()
2414 (save-excursion
2415 (back-to-indentation)
2416 (concat
2417 (if (bolp) "" "...")
2418 (buffer-substring (point) (progn (end-of-line) (point))))))
2419
2420;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2421;; as a Lisp symbol; return nil if none
2422(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002423 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002424 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2425 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2426 nil)))
2427
Barry Warsaw7ae77681994-12-12 20:38:05 +00002428(defun py-delete-file-silently (fname)
2429 (condition-case nil
2430 (delete-file fname)
2431 (error nil)))
2432
2433(defun py-kill-emacs-hook ()
2434 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002435 (py-safe (while py-file-queue
2436 (py-delete-file-silently (car py-file-queue))
2437 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002438
Barry Warsawb3e81d51996-09-04 15:12:42 +00002439(defun py-current-defun ()
2440 ;; tell add-log.el how to find the current function/method/variable
2441 (save-excursion
2442 (if (re-search-backward py-defun-start-re nil t)
2443 (or (match-string 3)
2444 (let ((method (match-string 2)))
2445 (if (and (not (zerop (length (match-string 1))))
2446 (re-search-backward py-class-start-re nil t))
2447 (concat (match-string 1) "." method)
2448 method)))
2449 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002450
2451
Barry Warsawfec75d61995-07-05 23:26:15 +00002452(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002453 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002454
Barry Warsaw850437a1995-03-08 21:50:28 +00002455(defun py-version ()
2456 "Echo the current version of `python-mode' in the minibuffer."
2457 (interactive)
2458 (message "Using `python-mode' version %s" py-version)
2459 (py-keep-region-active))
2460
2461;; only works under Emacs 19
2462;(eval-when-compile
2463; (require 'reporter))
2464
2465(defun py-submit-bug-report (enhancement-p)
2466 "Submit via mail a bug report on `python-mode'.
2467With \\[universal-argument] just submit an enhancement request."
2468 (interactive
2469 (list (not (y-or-n-p
2470 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002471 (let ((reporter-prompt-for-summary-p (if enhancement-p
2472 "(Very) brief summary: "
2473 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002474 (require 'reporter)
2475 (reporter-submit-bug-report
2476 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002477 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002478 ;; varlist
2479 (if enhancement-p nil
2480 '(py-python-command
2481 py-indent-offset
2482 py-block-comment-prefix
2483 py-scroll-process-buffer
2484 py-temp-directory
2485 py-beep-if-tab-change))
2486 nil ;pre-hooks
2487 nil ;post-hooks
2488 "Dear Barry,") ;salutation
2489 (if enhancement-p nil
2490 (set-mark (point))
2491 (insert
2492"Please replace this text with a sufficiently large code sample\n\
2493and an exact recipe so that I can reproduce your problem. Failure\n\
2494to do so may mean a greater delay in fixing your bug.\n\n")
2495 (exchange-point-and-mark)
2496 (py-keep-region-active))))
2497
2498
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002499;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002500(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002501
2502
2503
2504(provide 'python-mode)
2505;;; python-mode.el ends here