blob: ebcb1397a047523b0505969e1609975d7384f601 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5e21cb01997-11-05 18:41:11 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsawaffc0ca1997-11-03 16:59:38 +000027;; Note: this version of python-mode.el is no longer compatible with
28;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
29;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
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 Warsaw5e21cb01997-11-05 18:41:11 +0000234(defconst py-emacs-features
235 (let (features)
236 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
237 ;; the same string.
238 (let ((tmp1 (make-temp-name ""))
239 (tmp2 (make-temp-name "")))
240 (if (string-equal tmp1 tmp2)
241 (push 'broken-temp-names features)))
242 ;; return the features
243 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000244 "A list of features extant in the Emacs you are using.
245There are many flavors of Emacs out there, each with different
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000246features supporting those needed by CC Mode.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000247
Barry Warsawfb07f401997-02-24 03:37:22 +0000248(defvar python-font-lock-keywords
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000249 (let* ((keywords '("and" "assert" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000250 "continue" "def" "del" "elif"
251 "else:" "except" "except:" "exec"
252 "finally:" "for" "from" "global"
253 "if" "import" "in" "is"
254 "lambda" "not" "or" "pass"
255 "print" "raise" "return" "try:"
256 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000257 ))
258 (kwregex (mapconcat 'identity keywords "\\|")))
259 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000260 ;; keywords
261 (cons (concat "\\b\\(" kwregex "\\)\\b[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000262 ;; classes
263 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
264 1 font-lock-type-face)
265 ;; functions
266 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
267 1 font-lock-function-name-face)
268 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000269 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000270(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
271
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000272
Barry Warsaw81437461996-08-01 19:48:02 +0000273(defvar imenu-example--python-show-method-args-p nil
274 "*Controls echoing of arguments of functions & methods in the imenu buffer.
275When non-nil, arguments are printed.")
276
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000277(make-variable-buffer-local 'py-indent-offset)
278
Barry Warsaw7ae77681994-12-12 20:38:05 +0000279;; have to bind py-file-queue before installing the kill-emacs hook
280(defvar py-file-queue nil
281 "Queue of Python temp files awaiting execution.
282Currently-active file is at the head of the list.")
283
Barry Warsawc72c11c1997-08-09 06:42:08 +0000284
285;; Constants
286
287;; Regexp matching a Python string literal
288(defconst py-stringlit-re
289 (concat
290 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
291 "\\|" ; or
292 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
293
294;; Regexp matching Python lines that are continued via backslash.
295;; This is tricky because a trailing backslash does not mean
296;; continuation if it's in a comment
297(defconst py-continued-re
298 (concat
299 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
300 "\\\\$"))
301
302;; Regexp matching blank or comment lines.
303(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
304
305;; Regexp matching clauses to be outdented one level.
306(defconst py-outdent-re
307 (concat "\\(" (mapconcat 'identity
308 '("else:"
309 "except\\(\\s +.*\\)?:"
310 "finally:"
311 "elif\\s +.*:")
312 "\\|")
313 "\\)"))
314
315
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000316;; Regexp matching keywords which typically close a block
317(defconst py-block-closing-keywords-re
318 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
319
Barry Warsawc72c11c1997-08-09 06:42:08 +0000320;; Regexp matching lines to not outdent after.
321(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000322 (concat
323 "\\("
324 (mapconcat 'identity
325 (list "try:"
326 "except\\(\\s +.*\\)?:"
327 "while\\s +.*:"
328 "for\\s +.*:"
329 "if\\s +.*:"
330 "elif\\s +.*:"
331 (concat py-block-closing-keywords-re "[ \t\n]")
332 )
333 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000334 "\\)"))
335
336;; Regexp matching a function, method or variable assignment. If you
337;; change this, you probably have to change `py-current-defun' as
338;; well. This is only used by `py-current-defun' to find the name for
339;; add-log.el.
340(defvar py-defun-start-re
341 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
342
343;; Regexp for finding a class name. If you change this, you probably
344;; have to change `py-current-defun' as well. This is only used by
345;; `py-current-defun' to find the name for add-log.el.
346(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
347
348
349
350;; Utilities
351
352(defmacro py-safe (&rest body)
353 ;; safely execute BODY, return nil if an error occurred
354 (` (condition-case nil
355 (progn (,@ body))
356 (error nil))))
357
358(defsubst py-keep-region-active ()
359 ;; Do whatever is necessary to keep the region active in XEmacs.
360 ;; Ignore byte-compiler warnings you might see. Also note that
361 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
362 ;; to take explicit action.
363 (and (boundp 'zmacs-region-stays)
364 (setq zmacs-region-stays t)))
365
366
367;; Major mode boilerplate
368
Barry Warsaw7ae77681994-12-12 20:38:05 +0000369;; define a mode-specific abbrev table for those who use such things
370(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000371 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000372(define-abbrev-table 'python-mode-abbrev-table nil)
373
Barry Warsaw7ae77681994-12-12 20:38:05 +0000374(defvar python-mode-hook nil
375 "*Hook called by `python-mode'.")
376
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000377;; in previous version of python-mode.el, the hook was incorrectly
378;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000379(and (fboundp 'make-obsolete-variable)
380 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
381
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000382(defvar py-mode-map ()
383 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000384(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000385 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000387 ;; electric keys
388 (define-key py-mode-map ":" 'py-electric-colon)
389 ;; indentation level modifiers
390 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
391 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
392 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
393 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
394 ;; subprocess commands
395 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
396 (define-key py-mode-map "\C-c|" 'py-execute-region)
397 (define-key py-mode-map "\C-c!" 'py-shell)
398 ;; Caution! Enter here at your own risk. We are trying to support
399 ;; several behaviors and it gets disgusting. :-( This logic ripped
400 ;; largely from CC Mode.
401 ;;
402 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
403 ;; backwards deletion behavior to DEL, which both Delete and
404 ;; Backspace get translated to. There's no way to separate this
405 ;; behavior in a clean way, so deal with it! Besides, it's been
406 ;; this way since the dawn of time.
407 (if (not (boundp 'delete-key-deletes-forward))
408 (define-key py-mode-map "\177" 'py-electric-backspace)
409 ;; However, XEmacs 20 actually achieved enlightenment. It is
410 ;; possible to sanely define both backward and forward deletion
411 ;; behavior under X separately (TTYs are forever beyond hope, but
412 ;; who cares? XEmacs 20 does the right thing with these too).
413 (define-key py-mode-map [delete] 'py-electric-delete)
414 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw2518c671997-11-05 00:51:08 +0000415 ;; marking interesting locations
416 (define-key py-mode-map "\C-c\C-m" 'py-mark-def-or-class)
417 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000418 ;; Miscellaneous
419 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
420 (define-key py-mode-map "\C-c\t" 'py-indent-region)
421 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
422 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
423 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000424 (define-key py-mode-map "\C-c#" 'py-comment-region)
425 (define-key py-mode-map "\C-c?" 'py-describe-mode)
426 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
427 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
428 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000429 ;; information
430 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
431 (define-key py-mode-map "\C-c\C-v" 'py-version)
432 ;; py-newline-and-indent mappings
433 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000434 ;; shadow global bindings for newline-and-indent w/ the py- version.
435 ;; BAW - this is extremely bad form, but I'm not going to change it
436 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000437 (mapcar (function (lambda (key)
438 (define-key
439 py-mode-map key 'py-newline-and-indent)))
440 (where-is-internal 'newline-and-indent))
Barry Warsaw850437a1995-03-08 21:50:28 +0000441 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000442
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000443(defvar py-mode-syntax-table nil
444 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000446 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000447 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000448 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
449 (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 ;; Add operator symbols misassigned in the std table
455 (modify-syntax-entry ?\$ "." py-mode-syntax-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 ;; For historical reasons, underscore is word class instead of
467 ;; symbol class. GNU conventions say it should be symbol class, but
468 ;; there's a natural conflict between what major mode authors want
469 ;; and what users expect from `forward-word' and `backward-word'.
470 ;; Guido and I have hashed this out and have decided to keep
471 ;; underscore in word class. If you're tempted to change it, try
472 ;; binding M-f and M-b to py-forward-into-nomenclature and
473 ;; py-backward-into-nomenclature instead.
474 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
475 ;; Both single quote and double quote are string delimiters
476 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
477 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
478 ;; backquote is open and close paren
479 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
480 ;; comment delimiters
481 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
482 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
483 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000484
Barry Warsawb3e81d51996-09-04 15:12:42 +0000485
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000486
Barry Warsaw42f707f1996-07-29 21:05:05 +0000487;; Menu definitions, only relevent if you have the easymenu.el package
488;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000489(defvar py-menu nil
490 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000491This menu will get created automatically if you have the `easymenu'
492package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000493
Barry Warsawc72c11c1997-08-09 06:42:08 +0000494(and (py-safe (require 'easymenu) t)
495 (easy-menu-define
496 py-menu py-mode-map "Python Mode menu"
497 '("Python"
498 ["Comment Out Region" py-comment-region (mark)]
499 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
500 "-"
501 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000502 ["Mark current def" py-mark-def-or-class t]
503 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000504 "-"
505 ["Shift region left" py-shift-region-left (mark)]
506 ["Shift region right" py-shift-region-right (mark)]
507 "-"
508 ["Execute buffer" py-execute-buffer t]
509 ["Execute region" py-execute-region (mark)]
510 ["Start interpreter..." py-shell t]
511 "-"
512 ["Go to start of block" py-goto-block-up t]
513 ["Go to start of class" (beginning-of-python-def-or-class t) t]
514 ["Move to end of class" (end-of-python-def-or-class t) t]
515 ["Move to start of def" beginning-of-python-def-or-class t]
516 ["Move to end of def" end-of-python-def-or-class t]
517 "-"
518 ["Describe mode" py-describe-mode t]
519 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000520
Barry Warsaw81437461996-08-01 19:48:02 +0000521
522
523;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
524(defvar imenu-example--python-class-regexp
525 (concat ; <<classes>>
526 "\\(" ;
527 "^[ \t]*" ; newline and maybe whitespace
528 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
529 ; possibly multiple superclasses
530 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
531 "[ \t]*:" ; and the final :
532 "\\)" ; >>classes<<
533 )
534 "Regexp for Python classes for use with the imenu package."
535 )
536
537(defvar imenu-example--python-method-regexp
538 (concat ; <<methods and functions>>
539 "\\(" ;
540 "^[ \t]*" ; new line and maybe whitespace
541 "\\(def[ \t]+" ; function definitions start with def
542 "\\([a-zA-Z0-9_]+\\)" ; name is here
543 ; function arguments...
544 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
545 "\\)" ; end of def
546 "[ \t]*:" ; and then the :
547 "\\)" ; >>methods and functions<<
548 )
549 "Regexp for Python methods/functions for use with the imenu package."
550 )
551
552(defvar imenu-example--python-method-no-arg-parens '(2 8)
553 "Indicies into groups of the Python regexp for use with imenu.
554
555Using these values will result in smaller imenu lists, as arguments to
556functions are not listed.
557
558See the variable `imenu-example--python-show-method-args-p' for more
559information.")
560
561(defvar imenu-example--python-method-arg-parens '(2 7)
562 "Indicies into groups of the Python regexp for use with imenu.
563Using these values will result in large imenu lists, as arguments to
564functions are listed.
565
566See the variable `imenu-example--python-show-method-args-p' for more
567information.")
568
569;; Note that in this format, this variable can still be used with the
570;; imenu--generic-function. Otherwise, there is no real reason to have
571;; it.
572(defvar imenu-example--generic-python-expression
573 (cons
574 (concat
575 imenu-example--python-class-regexp
576 "\\|" ; or...
577 imenu-example--python-method-regexp
578 )
579 imenu-example--python-method-no-arg-parens)
580 "Generic Python expression which may be used directly with imenu.
581Used by setting the variable `imenu-generic-expression' to this value.
582Also, see the function \\[imenu-example--create-python-index] for a
583better alternative for finding the index.")
584
585;; These next two variables are used when searching for the python
586;; class/definitions. Just saving some time in accessing the
587;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000588(defvar imenu-example--python-generic-regexp nil)
589(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000590
591
592;;;###autoload
593(eval-when-compile
594 ;; Imenu isn't used in XEmacs, so just ignore load errors
595 (condition-case ()
596 (progn
597 (require 'cl)
598 (require 'imenu))
599 (error nil)))
600
601(defun imenu-example--create-python-index ()
602 "Python interface function for imenu package.
603Finds all python classes and functions/methods. Calls function
604\\[imenu-example--create-python-index-engine]. See that function for
605the details of how this works."
606 (setq imenu-example--python-generic-regexp
607 (car imenu-example--generic-python-expression))
608 (setq imenu-example--python-generic-parens
609 (if imenu-example--python-show-method-args-p
610 imenu-example--python-method-arg-parens
611 imenu-example--python-method-no-arg-parens))
612 (goto-char (point-min))
613 (imenu-example--create-python-index-engine nil))
614
615(defun imenu-example--create-python-index-engine (&optional start-indent)
616 "Function for finding imenu definitions in Python.
617
618Finds all definitions (classes, methods, or functions) in a Python
619file for the imenu package.
620
621Returns a possibly nested alist of the form
622
623 (INDEX-NAME . INDEX-POSITION)
624
625The second element of the alist may be an alist, producing a nested
626list as in
627
628 (INDEX-NAME . INDEX-ALIST)
629
630This function should not be called directly, as it calls itself
631recursively and requires some setup. Rather this is the engine for
632the function \\[imenu-example--create-python-index].
633
634It works recursively by looking for all definitions at the current
635indention level. When it finds one, it adds it to the alist. If it
636finds a definition at a greater indentation level, it removes the
637previous definition from the alist. In it's place it adds all
638definitions found at the next indentation level. When it finds a
639definition that is less indented then the current level, it retuns the
640alist it has created thus far.
641
642The optional argument START-INDENT indicates the starting indentation
643at which to continue looking for Python classes, methods, or
644functions. If this is not supplied, the function uses the indentation
645of the first definition found."
646 (let ((index-alist '())
647 (sub-method-alist '())
648 looking-p
649 def-name prev-name
650 cur-indent def-pos
651 (class-paren (first imenu-example--python-generic-parens))
652 (def-paren (second imenu-example--python-generic-parens)))
653 (setq looking-p
654 (re-search-forward imenu-example--python-generic-regexp
655 (point-max) t))
656 (while looking-p
657 (save-excursion
658 ;; used to set def-name to this value but generic-extract-name is
659 ;; new to imenu-1.14. this way it still works with imenu-1.11
660 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
661 (let ((cur-paren (if (match-beginning class-paren)
662 class-paren def-paren)))
663 (setq def-name
664 (buffer-substring (match-beginning cur-paren)
665 (match-end cur-paren))))
666 (beginning-of-line)
667 (setq cur-indent (current-indentation)))
668
669 ;; HACK: want to go to the next correct definition location. we
670 ;; explicitly list them here. would be better to have them in a
671 ;; list.
672 (setq def-pos
673 (or (match-beginning class-paren)
674 (match-beginning def-paren)))
675
676 ;; if we don't have a starting indent level, take this one
677 (or start-indent
678 (setq start-indent cur-indent))
679
680 ;; if we don't have class name yet, take this one
681 (or prev-name
682 (setq prev-name def-name))
683
684 ;; what level is the next definition on? must be same, deeper
685 ;; or shallower indentation
686 (cond
687 ;; at the same indent level, add it to the list...
688 ((= start-indent cur-indent)
689
690 ;; if we don't have push, use the following...
691 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
692 (push (cons def-name def-pos) index-alist))
693
694 ;; deeper indented expression, recur...
695 ((< start-indent cur-indent)
696
697 ;; the point is currently on the expression we're supposed to
698 ;; start on, so go back to the last expression. The recursive
699 ;; call will find this place again and add it to the correct
700 ;; list
701 (re-search-backward imenu-example--python-generic-regexp
702 (point-min) 'move)
703 (setq sub-method-alist (imenu-example--create-python-index-engine
704 cur-indent))
705
706 (if sub-method-alist
707 ;; we put the last element on the index-alist on the start
708 ;; of the submethod alist so the user can still get to it.
709 (let ((save-elmt (pop index-alist)))
710 (push (cons (imenu-create-submenu-name prev-name)
711 (cons save-elmt sub-method-alist))
712 index-alist))))
713
714 ;; found less indented expression, we're done.
715 (t
716 (setq looking-p nil)
717 (re-search-backward imenu-example--python-generic-regexp
718 (point-min) t)))
719 (setq prev-name def-name)
720 (and looking-p
721 (setq looking-p
722 (re-search-forward imenu-example--python-generic-regexp
723 (point-max) 'move))))
724 (nreverse index-alist)))
725
Barry Warsaw42f707f1996-07-29 21:05:05 +0000726
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000727;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000728(defun python-mode ()
729 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000730To submit a problem report, enter `\\[py-submit-bug-report]' from a
731`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
732documentation. To see what version of `python-mode' you are running,
733enter `\\[py-version]'.
734
735This mode knows about Python indentation, tokens, comments and
736continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000737
738COMMANDS
739\\{py-mode-map}
740VARIABLES
741
Barry Warsaw42f707f1996-07-29 21:05:05 +0000742py-indent-offset\t\tindentation increment
743py-block-comment-prefix\t\tcomment string used by comment-region
744py-python-command\t\tshell command to invoke Python interpreter
745py-scroll-process-buffer\t\talways scroll Python process buffer
746py-temp-directory\t\tdirectory used for temp files (if needed)
747py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000749 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000750 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000751 (make-local-variable 'font-lock-defaults)
752 (make-local-variable 'paragraph-separate)
753 (make-local-variable 'paragraph-start)
754 (make-local-variable 'require-final-newline)
755 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000756 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000757 (make-local-variable 'comment-start-skip)
758 (make-local-variable 'comment-column)
759 (make-local-variable 'indent-region-function)
760 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000761 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000762 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000763 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000764 (setq major-mode 'python-mode
765 mode-name "Python"
766 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000767 paragraph-separate "^[ \t]*$"
768 paragraph-start "^[ \t]*$"
769 require-final-newline t
770 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000771 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000772 comment-start-skip "# *"
773 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000774 indent-region-function 'py-indent-region
775 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000776 ;; tell add-log.el how to find the current function/method/variable
777 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000778 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000779 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000780 ;; add the menu
781 (if py-menu
782 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000783 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000784 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000785 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000786 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000787 ;;
788 ;; not sure where the magic comment has to be; to save time
789 ;; searching for a rarity, we give up if it's not found prior to the
790 ;; first executable statement.
791 ;;
792 ;; BAW - on first glance, this seems like complete hackery. Why was
793 ;; this necessary, and is it still necessary?
794 (let ((case-fold-search nil)
795 (start (point))
796 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000797 (if (re-search-forward
798 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
799 (prog2 (py-next-statement 1) (point) (goto-char 1))
800 t)
801 (progn
802 (setq new-tab-width
803 (string-to-int
804 (buffer-substring (match-beginning 1) (match-end 1))))
805 (if (= tab-width new-tab-width)
806 nil
807 (setq tab-width new-tab-width)
808 (message "Caution: tab-width changed to %d" new-tab-width)
809 (if py-beep-if-tab-change (beep)))))
810 (goto-char start))
811
Barry Warsaw755c6711996-08-01 20:02:55 +0000812 ;; install imenu
813 (setq imenu-create-index-function
814 (function imenu-example--create-python-index))
815 (if (fboundp 'imenu-add-to-menubar)
816 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
817
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000818 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000819 (if python-mode-hook
820 (run-hooks 'python-mode-hook)
821 (run-hooks 'py-mode-hook)))
822
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000823
Barry Warsawb91b7431995-03-14 15:55:20 +0000824;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000825(defun py-outdent-p ()
826 ;; returns non-nil if the current line should outdent one level
827 (save-excursion
828 (and (progn (back-to-indentation)
829 (looking-at py-outdent-re))
830 (progn (backward-to-indentation 1)
831 (while (or (looking-at py-blank-or-comment-re)
832 (bobp))
833 (backward-to-indentation 1))
834 (not (looking-at py-no-outdent-re)))
835 )))
836
Barry Warsawb91b7431995-03-14 15:55:20 +0000837(defun py-electric-colon (arg)
838 "Insert a colon.
839In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000840argument is provided, that many colons are inserted non-electrically.
841Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000842 (interactive "P")
843 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000844 ;; are we in a string or comment?
845 (if (save-excursion
846 (let ((pps (parse-partial-sexp (save-excursion
847 (beginning-of-python-def-or-class)
848 (point))
849 (point))))
850 (not (or (nth 3 pps) (nth 4 pps)))))
851 (save-excursion
852 (let ((here (point))
853 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000854 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000855 (if (and (not arg)
856 (py-outdent-p)
857 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000858 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000859 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000860 )
861 (setq outdent py-indent-offset))
862 ;; Don't indent, only outdent. This assumes that any lines that
863 ;; are already outdented relative to py-compute-indentation were
864 ;; put there on purpose. Its highly annoying to have `:' indent
865 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
866 ;; there a better way to determine this???
867 (if (< (current-indentation) indent) nil
868 (goto-char here)
869 (beginning-of-line)
870 (delete-horizontal-space)
871 (indent-to (- indent outdent))
872 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000873
874
Barry Warsawa97a3f31997-11-04 18:47:06 +0000875;; Python subprocess utilities and filters
876(defun py-execute-file (proc filename)
877 ;; Send a properly formatted execfile('FILENAME') to the underlying
878 ;; Python interpreter process FILENAME. Make that process's buffer
879 ;; visible and force display. Also make comint believe the user
880 ;; typed this string so that kill-output-from-shell does The Right
881 ;; Thing.
882 (let ((curbuf (current-buffer))
883 (procbuf (process-buffer proc))
884 (comint-scroll-to-bottom-on-output t)
885 (msg (format "## working on region in file %s...\n" filename))
886 (cmd (format "execfile('%s')\n" filename)))
887 (unwind-protect
888 (progn
889 (set-buffer procbuf)
890 (goto-char (point-max))
891 (move-marker (process-mark proc) (point))
892 (funcall (process-filter proc) proc msg))
893 (set-buffer curbuf))
894 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000895
896(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 (let ((curbuf (current-buffer))
898 (pbuf (process-buffer pyproc))
899 (pmark (process-mark pyproc))
900 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901 ;; make sure we switch to a different buffer at least once. if we
902 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000903 ;; window, and point is before the end, and lots of output is
904 ;; coming at a fast pace, then (a) simple cursor-movement commands
905 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
906 ;; to have a visible effect (the window just doesn't get updated,
907 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
908 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000910 ;; #b makes no sense to me at all. #a almost makes sense: unless
911 ;; we actually change buffers, set_buffer_internal in buffer.c
912 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
913 ;; seems to make the Emacs command loop reluctant to update the
914 ;; display. Perhaps the default process filter in process.c's
915 ;; read_process_output has update_mode_lines++ for a similar
916 ;; reason? beats me ...
917
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000918 (unwind-protect
919 ;; make sure current buffer is restored
920 ;; BAW - we want to check to see if this still applies
921 (progn
922 ;; mysterious ugly hack
923 (if (eq curbuf pbuf)
924 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000926 (set-buffer pbuf)
927 (let* ((start (point))
928 (goback (< start pmark))
929 (goend (and (not goback) (= start (point-max))))
930 (buffer-read-only nil))
931 (goto-char pmark)
932 (insert string)
933 (move-marker pmark (point))
934 (setq file-finished
935 (and py-file-queue
936 (equal ">>> "
937 (buffer-substring
938 (prog2 (beginning-of-line) (point)
939 (goto-char pmark))
940 (point)))))
941 (if goback (goto-char start)
942 ;; else
943 (if py-scroll-process-buffer
944 (let* ((pop-up-windows t)
945 (pwin (display-buffer pbuf)))
946 (set-window-point pwin (point)))))
947 (set-buffer curbuf)
948 (if file-finished
949 (progn
950 (py-delete-file-silently (car py-file-queue))
951 (setq py-file-queue (cdr py-file-queue))
952 (if py-file-queue
953 (py-execute-file pyproc (car py-file-queue)))))
954 (and goend
955 (progn (set-buffer pbuf)
956 (goto-char (point-max))))
957 ))
958 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000959
Barry Warsawa97a3f31997-11-04 18:47:06 +0000960
961;;; Subprocess commands
962
963;;;###autoload
964(defun py-shell ()
965 "Start an interactive Python interpreter in another window.
966This is like Shell mode, except that Python is running in the window
967instead of a shell. See the `Interactive Shell' and `Shell Mode'
968sections of the Emacs manual for details, especially for the key
969bindings active in the `*Python*' buffer.
970
971See the docs for variable `py-scroll-buffer' for info on scrolling
972behavior in the process window.
973
974Warning: Don't use an interactive Python if you change sys.ps1 or
975sys.ps2 from their default values, or if you're running code that
976prints `>>> ' or `... ' at the start of a line. `python-mode' can't
977distinguish your output from Python's output, and assumes that `>>> '
978at the start of a line is a prompt from Python. Similarly, the Emacs
979Shell mode code assumes that both `>>> ' and `... ' at the start of a
980line are Python prompts. Bad things can happen if you fool either
981mode.
982
983Warning: If you do any editing *in* the process buffer *while* the
984buffer is accepting output from Python, do NOT attempt to `undo' the
985changes. Some of the output (nowhere near the parts you changed!) may
986be lost if you do. This appears to be an Emacs bug, an unfortunate
987interaction between undo and process filters; the same problem exists in
988non-Python process buffers using the default (Emacs-supplied) process
989filter."
990 ;; BAW - should undo be disabled in the python process buffer, if
991 ;; this bug still exists?
992 (interactive)
993 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +0000994 (switch-to-buffer-other-window
995 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +0000996 (make-local-variable 'comint-prompt-regexp)
997 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
998 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
999 (set-syntax-table py-mode-syntax-table)
1000 (local-set-key [tab] 'self-insert-command))
1001
1002
1003(defun py-clear-queue ()
1004 "Clear the queue of temporary files waiting to execute."
1005 (interactive)
1006 (let ((n (length py-file-queue)))
1007 (mapcar 'delete-file py-file-queue)
1008 (setq py-file-queue nil)
1009 (message "%d pending files de-queued." n)))
1010
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001011;; only used when (memq 'broken-temp-names py-emacs-features)
1012(defvar py-serial-number 0)
1013
Barry Warsawa97a3f31997-11-04 18:47:06 +00001014(defun py-execute-region (start end &optional async)
1015 "Execute the the region in a Python interpreter.
1016The region is first copied into a temporary file (in the directory
1017`py-temp-directory'). If there is no Python interpreter shell
1018running, this file is executed synchronously using
1019`shell-command-on-region'. If the program is long running, use an
1020optional \\[universal-argument] to run the command asynchronously in
1021its own buffer.
1022
1023If the Python interpreter shell is running, the region is execfile()'d
1024in that shell. If you try to execute regions too quickly,
1025`python-mode' will queue them up and execute them one at a time when
1026it sees a `>>> ' prompt from Python. Each time this happens, the
1027process buffer is popped into a window (if it's not already in some
1028window) so you can see it, and a comment of the form
1029
1030 \t## working on region in file <name>...
1031
1032is inserted at the end. See also the command `py-clear-queue'."
1033 (interactive "r\nP")
1034 (or (< start end)
1035 (error "Region is empty"))
1036 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001037 (temp (if (memq 'broken-temp-names py-emacs-features)
1038 (prog1
1039 (format "python-%d" py-serial-number)
1040 (setq py-serial-number (1+ py-serial-number)))
1041 (make-temp-name "python")))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001042 (file (concat (file-name-as-directory py-temp-directory) temp))
1043 (outbuf "*Python Output*"))
1044 (write-region start end file nil 'nomsg)
1045 (cond
1046 ;; always run the code in it's own asynchronous subprocess
1047 (async
1048 (let* ((buf (generate-new-buffer-name "*Python Output*")))
1049 (start-process "Python" buf py-python-command "-u" file)
1050 (pop-to-buffer buf)
1051 ))
1052 ;; if the Python interpreter shell is running, queue it up for
1053 ;; execution there.
1054 (proc
1055 ;; use the existing python shell
1056 (if (not py-file-queue)
1057 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001058 (message "File %s queued for execution" file))
Barry Warsawa9ce70f1997-11-05 16:56:51 +00001059 (push file py-file-queue))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001060 (t
1061 ;; otherwise either run it synchronously in a subprocess
1062 (shell-command-on-region start end py-python-command outbuf)
1063 ))))
1064
1065;; Code execution command
1066(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001067 "Send the contents of the buffer to a Python interpreter.
1068If there is a *Python* process buffer it is used. If a clipping
1069restriction is in effect, only the accessible portion of the buffer is
1070sent. A trailing newline will be supplied if needed.
1071
1072See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001073 (interactive "P")
1074 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001076
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001077;; Electric deletion
1078(defun py-electric-backspace (arg)
1079 "Deletes preceding character or levels of indentation.
1080Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001081with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001082
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001083If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001085Otherwise, if point is at the leftmost non-whitespace character of a
1086line that is neither a continuation line nor a non-indenting comment
1087line, or if point is at the end of a blank line, this command reduces
1088the indentation to match that of the line that opened the current
1089block of code. The line that opened the block is displayed in the
1090echo area to help you keep track of where you are. With numeric arg,
1091outdents that many blocks (but not past column zero).
1092
1093Otherwise the preceding character is deleted, converting a tab to
1094spaces if needed so that only a single column position is deleted.
1095Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001096 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097 (if (or (/= (current-indentation) (current-column))
1098 (bolp)
1099 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001100 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001101 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001102 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001103 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001104 ;; force non-blank so py-goto-block-up doesn't ignore it
1105 (insert-char ?* 1)
1106 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001107 (let ((base-indent 0) ; indentation of base line
1108 (base-text "") ; and text of base line
1109 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001110 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001111 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001112 (condition-case nil ; in case no enclosing block
1113 (progn
1114 (py-goto-block-up 'no-mark)
1115 (setq base-indent (current-indentation)
1116 base-text (py-suck-up-leading-text)
1117 base-found-p t))
1118 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001119 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001120 (delete-char 1) ; toss the dummy character
1121 (delete-horizontal-space)
1122 (indent-to base-indent)
1123 (if base-found-p
1124 (message "Closes block: %s" base-text)))))
1125
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001126
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001127(defun py-electric-delete (arg)
1128 "Deletes preceding or following character or levels of whitespace.
1129
1130The behavior of this function depends on the variable
1131`delete-key-deletes-forward'. If this variable is nil (or does not
1132exist, as in older Emacsen), then this function behaves identical to
1133\\[c-electric-backspace].
1134
1135If `delete-key-deletes-forward' is non-nil and is supported in your
1136Emacs, then deletion occurs in the forward direction, by calling the
1137function in `py-delete-function'."
1138 (interactive "*p")
1139 (if (and (boundp 'delete-key-deletes-forward)
1140 delete-key-deletes-forward)
1141 (funcall py-delete-function arg)
1142 ;; else
1143 (py-electric-backspace arg)))
1144
1145;; required for pending-del and delsel modes
1146(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1147(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1148(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1149(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1150
1151
1152
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001153(defun py-indent-line (&optional arg)
1154 "Fix the indentation of the current line according to Python rules.
1155With \\[universal-argument], ignore outdenting rules for block
1156closing statements (e.g. return, raise, break, continue, pass)
1157
1158This function is normally bound to `indent-line-function' so
1159\\[indent-for-tab-command] will call it."
1160 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161 (let* ((ci (current-indentation))
1162 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001163 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001164 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001165 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001166 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001167 (if (/= ci need)
1168 (save-excursion
1169 (beginning-of-line)
1170 (delete-horizontal-space)
1171 (indent-to need)))
1172 (if move-to-indentation-p (back-to-indentation))))
1173
1174(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001175 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001176This is just `strives to' because correct indentation can't be computed
1177from scratch for Python code. In general, deletes the whitespace before
1178point, inserts a newline, and takes an educated guess as to how you want
1179the new line indented."
1180 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001181 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001182 (if (< ci (current-column)) ; if point beyond indentation
1183 (newline-and-indent)
1184 ;; else try to act like newline-and-indent "normally" acts
1185 (beginning-of-line)
1186 (insert-char ?\n 1)
1187 (move-to-column ci))))
1188
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001189(defun py-compute-indentation (honor-block-close-p)
1190 ;; implements all the rules for indentation computation. when
1191 ;; honor-block-close-p is non-nil, statements such as return, raise,
1192 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001193 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001194 (let ((pps (parse-partial-sexp (save-excursion
1195 (beginning-of-python-def-or-class)
1196 (point))
1197 (point))))
1198 (beginning-of-line)
1199 (cond
1200 ;; are we inside a string or comment?
1201 ((or (nth 3 pps) (nth 4 pps))
1202 (save-excursion
1203 (if (not py-align-multiline-strings-p) 0
1204 ;; skip back over blank & non-indenting comment lines
1205 ;; note: will skip a blank or non-indenting comment line
1206 ;; that happens to be a continuation line too
1207 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1208 (back-to-indentation)
1209 (current-column))))
1210 ;; are we on a continuation line?
1211 ((py-continuation-line-p)
1212 (let ((startpos (point))
1213 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001214 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001215 (if open-bracket-pos
1216 (progn
1217 ;; align with first item in list; else a normal
1218 ;; indent beyond the line with the open bracket
1219 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1220 ;; is the first list item on the same line?
1221 (skip-chars-forward " \t")
1222 (if (null (memq (following-char) '(?\n ?# ?\\)))
1223 ; yes, so line up with it
1224 (current-column)
1225 ;; first list item on another line, or doesn't exist yet
1226 (forward-line 1)
1227 (while (and (< (point) startpos)
1228 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1229 (forward-line 1))
1230 (if (< (point) startpos)
1231 ;; again mimic the first list item
1232 (current-indentation)
1233 ;; else they're about to enter the first item
1234 (goto-char open-bracket-pos)
1235 (+ (current-indentation) py-indent-offset))))
1236
1237 ;; else on backslash continuation line
1238 (forward-line -1)
1239 (if (py-continuation-line-p) ; on at least 3rd line in block
1240 (current-indentation) ; so just continue the pattern
1241 ;; else started on 2nd line in block, so indent more.
1242 ;; if base line is an assignment with a start on a RHS,
1243 ;; indent to 2 beyond the leftmost "="; else skip first
1244 ;; chunk of non-whitespace characters on base line, + 1 more
1245 ;; column
1246 (end-of-line)
1247 (setq endpos (point) searching t)
1248 (back-to-indentation)
1249 (setq startpos (point))
1250 ;; look at all "=" from left to right, stopping at first
1251 ;; one not nested in a list or string
1252 (while searching
1253 (skip-chars-forward "^=" endpos)
1254 (if (= (point) endpos)
1255 (setq searching nil)
1256 (forward-char 1)
1257 (setq state (parse-partial-sexp startpos (point)))
1258 (if (and (zerop (car state)) ; not in a bracket
1259 (null (nth 3 state))) ; & not in a string
1260 (progn
1261 (setq searching nil) ; done searching in any case
1262 (setq found
1263 (not (or
1264 (eq (following-char) ?=)
1265 (memq (char-after (- (point) 2))
1266 '(?< ?> ?!)))))))))
1267 (if (or (not found) ; not an assignment
1268 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1269 (progn
1270 (goto-char startpos)
1271 (skip-chars-forward "^ \t\n")))
1272 (1+ (current-column))))))
1273
1274 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001275 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001276
Barry Warsawa7891711996-08-01 15:53:09 +00001277 ;; Dfn: "Indenting comment line". A line containing only a
1278 ;; comment, but which is treated like a statement for
1279 ;; indentation calculation purposes. Such lines are only
1280 ;; treated specially by the mode; they are not treated
1281 ;; specially by the Python interpreter.
1282
1283 ;; The rules for indenting comment lines are a line where:
1284 ;; - the first non-whitespace character is `#', and
1285 ;; - the character following the `#' is whitespace, and
1286 ;; - the line is outdented with respect to (i.e. to the left
1287 ;; of) the indentation of the preceding non-blank line.
1288
1289 ;; The first non-blank line following an indenting comment
1290 ;; line is given the same amount of indentation as the
1291 ;; indenting comment line.
1292
1293 ;; All other comment-only lines are ignored for indentation
1294 ;; purposes.
1295
1296 ;; Are we looking at a comment-only line which is *not* an
1297 ;; indenting comment line? If so, we assume that its been
1298 ;; placed at the desired indentation, so leave it alone.
1299 ;; Indenting comment lines are aligned as statements down
1300 ;; below.
1301 ((and (looking-at "[ \t]*#[^ \t\n]")
1302 ;; NOTE: this test will not be performed in older Emacsen
1303 (fboundp 'forward-comment)
1304 (<= (current-indentation)
1305 (save-excursion
1306 (forward-comment (- (point-max)))
1307 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001308 (current-indentation))
1309
1310 ;; else indentation based on that of the statement that
1311 ;; precedes us; use the first line of that statement to
1312 ;; establish the base, in case the user forced a non-std
1313 ;; indentation for the continuation lines (if any)
1314 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001315 ;; skip back over blank & non-indenting comment lines note:
1316 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001317 ;; happens to be a continuation line too. use fast Emacs 19
1318 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001319 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001320 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001321 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001322 (let (done)
1323 (while (not done)
1324 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1325 nil 'move)
1326 (setq done (or (eq py-honor-comment-indentation t)
1327 (bobp)
1328 (/= (following-char) ?#)
1329 (not (zerop (current-column)))))
1330 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001331 ;; if we landed inside a string, go to the beginning of that
1332 ;; string. this handles triple quoted, multi-line spanning
1333 ;; strings.
1334 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001335 (+ (current-indentation)
1336 (if (py-statement-opens-block-p)
1337 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001338 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001339 (- py-indent-offset)
1340 0)))
1341 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001342
1343(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001344 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001345By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001346`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001347Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001349their own buffer-local copy), both those currently existing and those
1350created later in the Emacs session.
1351
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001352Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001353There's no excuse for such foolishness, but sometimes you have to deal
1354with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001355`py-indent-offset' to what it thinks it was when they created the
1356mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001357
1358Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359looking for a line that opens a block of code. `py-indent-offset' is
1360set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361statement following it. If the search doesn't succeed going forward,
1362it's tried again going backward."
1363 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001364 (let (new-value
1365 (start (point))
1366 restart
1367 (found nil)
1368 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369 (py-goto-initial-line)
1370 (while (not (or found (eobp)))
1371 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1372 (progn
1373 (setq restart (point))
1374 (py-goto-initial-line)
1375 (if (py-statement-opens-block-p)
1376 (setq found t)
1377 (goto-char restart)))))
1378 (if found
1379 ()
1380 (goto-char start)
1381 (py-goto-initial-line)
1382 (while (not (or found (bobp)))
1383 (setq found
1384 (and
1385 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1386 (or (py-goto-initial-line) t) ; always true -- side effect
1387 (py-statement-opens-block-p)))))
1388 (setq colon-indent (current-indentation)
1389 found (and found (zerop (py-next-statement 1)))
1390 new-value (- (current-indentation) colon-indent))
1391 (goto-char start)
1392 (if found
1393 (progn
1394 (funcall (if global 'kill-local-variable 'make-local-variable)
1395 'py-indent-offset)
1396 (setq py-indent-offset new-value)
1397 (message "%s value of py-indent-offset set to %d"
1398 (if global "Global" "Local")
1399 py-indent-offset))
1400 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1401
1402(defun py-shift-region (start end count)
1403 (save-excursion
1404 (goto-char end) (beginning-of-line) (setq end (point))
1405 (goto-char start) (beginning-of-line) (setq start (point))
1406 (indent-rigidly start end count)))
1407
1408(defun py-shift-region-left (start end &optional count)
1409 "Shift region of Python code to the left.
1410The lines from the line containing the start of the current region up
1411to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001412shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001413
1414If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001415many columns. With no active region, outdent only the current line.
1416You cannot outdent the region if any line is already at column zero."
1417 (interactive
1418 (let ((p (point))
1419 (m (mark))
1420 (arg current-prefix-arg))
1421 (if m
1422 (list (min p m) (max p m) arg)
1423 (list p (save-excursion (forward-line 1) (point)) arg))))
1424 ;; if any line is at column zero, don't shift the region
1425 (save-excursion
1426 (goto-char start)
1427 (while (< (point) end)
1428 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001429 (if (and (zerop (current-column))
1430 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001431 (error "Region is at left edge."))
1432 (forward-line 1)))
1433 (py-shift-region start end (- (prefix-numeric-value
1434 (or count py-indent-offset))))
1435 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001436
1437(defun py-shift-region-right (start end &optional count)
1438 "Shift region of Python code to the right.
1439The lines from the line containing the start of the current region up
1440to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001441shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001442
1443If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001444many columns. With no active region, indent only the current line."
1445 (interactive
1446 (let ((p (point))
1447 (m (mark))
1448 (arg current-prefix-arg))
1449 (if m
1450 (list (min p m) (max p m) arg)
1451 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001452 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001453 (or count py-indent-offset)))
1454 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455
1456(defun py-indent-region (start end &optional indent-offset)
1457 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001458
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459The lines from the line containing the start of the current region up
1460to (but not including) the line containing the end of the region are
1461reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001462character in the first column, the first line is left alone and the
1463rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001464region is reindented with respect to the (closest code or indenting
1465comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001466
1467This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001468control structures are introduced or removed, or to reformat code
1469using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001470
1471If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001472the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001473used.
1474
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001475Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001476is called! This function does not compute proper indentation from
1477scratch (that's impossible in Python), it merely adjusts the existing
1478indentation to be correct in context.
1479
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001480Warning: This function really has no idea what to do with
1481non-indenting comment lines, and shifts them as if they were indenting
1482comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001483
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001484Special cases: whitespace is deleted from blank lines; continuation
1485lines are shifted by the same amount their initial line was shifted,
1486in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001487initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001488 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001489 (save-excursion
1490 (goto-char end) (beginning-of-line) (setq end (point-marker))
1491 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492 (let ((py-indent-offset (prefix-numeric-value
1493 (or indent-offset py-indent-offset)))
1494 (indents '(-1)) ; stack of active indent levels
1495 (target-column 0) ; column to which to indent
1496 (base-shifted-by 0) ; amount last base line was shifted
1497 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001498 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001499 0))
1500 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001501 (while (< (point) end)
1502 (setq ci (current-indentation))
1503 ;; figure out appropriate target column
1504 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001505 ((or (eq (following-char) ?#) ; comment in column 1
1506 (looking-at "[ \t]*$")) ; entirely blank
1507 (setq target-column 0))
1508 ((py-continuation-line-p) ; shift relative to base line
1509 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001510 (t ; new base line
1511 (if (> ci (car indents)) ; going deeper; push it
1512 (setq indents (cons ci indents))
1513 ;; else we should have seen this indent before
1514 (setq indents (memq ci indents)) ; pop deeper indents
1515 (if (null indents)
1516 (error "Bad indentation in region, at line %d"
1517 (save-restriction
1518 (widen)
1519 (1+ (count-lines 1 (point)))))))
1520 (setq target-column (+ indent-base
1521 (* py-indent-offset
1522 (- (length indents) 2))))
1523 (setq base-shifted-by (- target-column ci))))
1524 ;; shift as needed
1525 (if (/= ci target-column)
1526 (progn
1527 (delete-horizontal-space)
1528 (indent-to target-column)))
1529 (forward-line 1))))
1530 (set-marker end nil))
1531
Barry Warsawa7891711996-08-01 15:53:09 +00001532(defun py-comment-region (beg end &optional arg)
1533 "Like `comment-region' but uses double hash (`#') comment starter."
1534 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001535 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001536 (comment-region beg end arg)))
1537
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001538
1539;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540(defun py-previous-statement (count)
1541 "Go to the start of previous Python statement.
1542If the statement at point is the i'th Python statement, goes to the
1543start of statement i-COUNT. If there is no such statement, goes to the
1544first statement. Returns count of statements left to move.
1545`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547 (if (< count 0) (py-next-statement (- count))
1548 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001549 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001550 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552 (> count 0)
1553 (zerop (forward-line -1))
1554 (py-goto-statement-at-or-above))
1555 (setq count (1- count)))
1556 (if (> count 0) (goto-char start)))
1557 count))
1558
1559(defun py-next-statement (count)
1560 "Go to the start of next Python statement.
1561If the statement at point is the i'th Python statement, goes to the
1562start of statement i+COUNT. If there is no such statement, goes to the
1563last statement. Returns count of statements left to move. `Statements'
1564do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001565 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566 (if (< count 0) (py-previous-statement (- count))
1567 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001571 (> count 0)
1572 (py-goto-statement-below))
1573 (setq count (1- count)))
1574 (if (> count 0) (goto-char start)))
1575 count))
1576
1577(defun py-goto-block-up (&optional nomark)
1578 "Move up to start of current block.
1579Go to the statement that starts the smallest enclosing block; roughly
1580speaking, this will be the closest preceding statement that ends with a
1581colon and is indented less than the statement you started on. If
1582successful, also sets the mark to the starting point.
1583
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001584`\\[py-mark-block]' can be used afterward to mark the whole code
1585block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586
1587If called from a program, the mark will not be set if optional argument
1588NOMARK is not nil."
1589 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001590 (let ((start (point))
1591 (found nil)
1592 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001593 (py-goto-initial-line)
1594 ;; if on blank or non-indenting comment line, use the preceding stmt
1595 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1596 (progn
1597 (py-goto-statement-at-or-above)
1598 (setq found (py-statement-opens-block-p))))
1599 ;; search back for colon line indented less
1600 (setq initial-indent (current-indentation))
1601 (if (zerop initial-indent)
1602 ;; force fast exit
1603 (goto-char (point-min)))
1604 (while (not (or found (bobp)))
1605 (setq found
1606 (and
1607 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1608 (or (py-goto-initial-line) t) ; always true -- side effect
1609 (< (current-indentation) initial-indent)
1610 (py-statement-opens-block-p))))
1611 (if found
1612 (progn
1613 (or nomark (push-mark start))
1614 (back-to-indentation))
1615 (goto-char start)
1616 (error "Enclosing block not found"))))
1617
1618(defun beginning-of-python-def-or-class (&optional class)
1619 "Move point to start of def (or class, with prefix arg).
1620
1621Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001622arg, looks for a `class' instead. The docs assume the `def' case;
1623just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001624
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001625If point is in a def statement already, and after the `d', simply
1626moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001627
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628Else (point is not in a def statement, or at or before the `d' of a
1629def statement), searches for the closest preceding def statement, and
1630leaves point at its start. If no such statement can be found, leaves
1631point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632
1633Returns t iff a def statement is found by these rules.
1634
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001635Note that doing this command repeatedly will take you closer to the
1636start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001638If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001639`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001640 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001641 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1642 (start-of-line (progn (beginning-of-line) (point)))
1643 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001644 (if (or (/= start-of-stmt start-of-line)
1645 (not at-or-before-p))
1646 (end-of-line)) ; OK to match on this line
1647 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001648 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001649
1650(defun end-of-python-def-or-class (&optional class)
1651 "Move point beyond end of def (or class, with prefix arg) body.
1652
1653By default, looks for an appropriate `def'. If you supply a prefix arg,
1654looks for a `class' instead. The docs assume the `def' case; just
1655substitute `class' for `def' for the other case.
1656
1657If point is in a def statement already, this is the def we use.
1658
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659Else if the def found by `\\[beginning-of-python-def-or-class]'
1660contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001661
1662Else we search forward for the closest following def, and use that.
1663
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664If a def can be found by these rules, point is moved to the start of
1665the line immediately following the def block, and the position of the
1666start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667
1668Else point is moved to the end of the buffer, and nil is returned.
1669
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001670Note that doing this command repeatedly will take you closer to the
1671end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001672
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001674`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001676 (let ((start (progn (py-goto-initial-line) (point)))
1677 (which (if class "class" "def"))
1678 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679 ;; move point to start of appropriate def/class
1680 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1681 (setq state 'at-beginning)
1682 ;; else see if beginning-of-python-def-or-class hits container
1683 (if (and (beginning-of-python-def-or-class class)
1684 (progn (py-goto-beyond-block)
1685 (> (point) start)))
1686 (setq state 'at-end)
1687 ;; else search forward
1688 (goto-char start)
1689 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1690 (progn (setq state 'at-beginning)
1691 (beginning-of-line)))))
1692 (cond
1693 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1694 ((eq state 'at-end) t)
1695 ((eq state 'not-found) nil)
1696 (t (error "internal error in end-of-python-def-or-class")))))
1697
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001698
1699;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001700(defun py-mark-block (&optional extend just-move)
1701 "Mark following block of lines. With prefix arg, mark structure.
1702Easier to use than explain. It sets the region to an `interesting'
1703block of succeeding lines. If point is on a blank line, it goes down to
1704the next non-blank line. That will be the start of the region. The end
1705of the region depends on the kind of line at the start:
1706
1707 - If a comment, the region will include all succeeding comment lines up
1708 to (but not including) the next non-comment line (if any).
1709
1710 - Else if a prefix arg is given, and the line begins one of these
1711 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712
1713 if elif else try except finally for while def class
1714
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715 the region will be set to the body of the structure, including
1716 following blocks that `belong' to it, but excluding trailing blank
1717 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001718 and all (if any) of the following `except' and `finally' blocks
1719 that belong to the `try' structure will be in the region. Ditto
1720 for if/elif/else, for/else and while/else structures, and (a bit
1721 degenerate, since they're always one-block structures) def and
1722 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723
1724 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001725 block (see list above), and the block is not a `one-liner' (i.e.,
1726 the statement ends with a colon, not with code), the region will
1727 include all succeeding lines up to (but not including) the next
1728 code statement (if any) that's indented no more than the starting
1729 line, except that trailing blank and comment lines are excluded.
1730 E.g., if the starting line begins a multi-statement `def'
1731 structure, the region will be set to the full function definition,
1732 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001733
1734 - Else the region will include all succeeding lines up to (but not
1735 including) the next blank line, or code or indenting-comment line
1736 indented strictly less than the starting line. Trailing indenting
1737 comment lines are included in this case, but not trailing blank
1738 lines.
1739
1740A msg identifying the location of the mark is displayed in the echo
1741area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1742
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743If called from a program, optional argument EXTEND plays the role of
1744the prefix arg, and if optional argument JUST-MOVE is not nil, just
1745moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746 (interactive "P") ; raw prefix arg
1747 (py-goto-initial-line)
1748 ;; skip over blank lines
1749 (while (and
1750 (looking-at "[ \t]*$") ; while blank line
1751 (not (eobp))) ; & somewhere to go
1752 (forward-line 1))
1753 (if (eobp)
1754 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755 (let ((initial-pos (point))
1756 (initial-indent (current-indentation))
1757 last-pos ; position of last stmt in region
1758 (followers
1759 '((if elif else) (elif elif else) (else)
1760 (try except finally) (except except) (finally)
1761 (for else) (while else)
1762 (def) (class) ) )
1763 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764
1765 (cond
1766 ;; if comment line, suck up the following comment lines
1767 ((looking-at "[ \t]*#")
1768 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1769 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1770 (setq last-pos (point)))
1771
1772 ;; else if line is a block line and EXTEND given, suck up
1773 ;; the whole structure
1774 ((and extend
1775 (setq first-symbol (py-suck-up-first-keyword) )
1776 (assq first-symbol followers))
1777 (while (and
1778 (or (py-goto-beyond-block) t) ; side effect
1779 (forward-line -1) ; side effect
1780 (setq last-pos (point)) ; side effect
1781 (py-goto-statement-below)
1782 (= (current-indentation) initial-indent)
1783 (setq next-symbol (py-suck-up-first-keyword))
1784 (memq next-symbol (cdr (assq first-symbol followers))))
1785 (setq first-symbol next-symbol)))
1786
1787 ;; else if line *opens* a block, search for next stmt indented <=
1788 ((py-statement-opens-block-p)
1789 (while (and
1790 (setq last-pos (point)) ; always true -- side effect
1791 (py-goto-statement-below)
1792 (> (current-indentation) initial-indent))
1793 nil))
1794
1795 ;; else plain code line; stop at next blank line, or stmt or
1796 ;; indenting comment line indented <
1797 (t
1798 (while (and
1799 (setq last-pos (point)) ; always true -- side effect
1800 (or (py-goto-beyond-final-line) t)
1801 (not (looking-at "[ \t]*$")) ; stop at blank line
1802 (or
1803 (>= (current-indentation) initial-indent)
1804 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1805 nil)))
1806
1807 ;; skip to end of last stmt
1808 (goto-char last-pos)
1809 (py-goto-beyond-final-line)
1810
1811 ;; set mark & display
1812 (if just-move
1813 () ; just return
1814 (push-mark (point) 'no-msg)
1815 (forward-line -1)
1816 (message "Mark set after: %s" (py-suck-up-leading-text))
1817 (goto-char initial-pos))))
1818
Barry Warsaw2518c671997-11-05 00:51:08 +00001819(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820 "Set region to body of def (or class, with prefix arg) enclosing point.
1821Pushes the current mark, then point, on the mark ring (all language
1822modes do this, but although it's handy it's never documented ...).
1823
1824In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1826`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827
1828And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001829Turned out that was more confusing than useful: the `goto start' and
1830`goto end' commands are usually used to search through a file, and
1831people expect them to act a lot like `search backward' and `search
1832forward' string-search commands. But because Python `def' and `class'
1833can nest to arbitrary levels, finding the smallest def containing
1834point cannot be done via a simple backward search: the def containing
1835point may not be the closest preceding def, or even the closest
1836preceding def that's indented less. The fancy algorithm required is
1837appropriate for the usual uses of this `mark' command, but not for the
1838`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840So the def marked by this command may not be the one either of the
1841`goto' commands find: If point is on a blank or non-indenting comment
1842line, moves back to start of the closest preceding code statement or
1843indenting comment line. If this is a `def' statement, that's the def
1844we use. Else searches for the smallest enclosing `def' block and uses
1845that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847When an enclosing def is found: The mark is left immediately beyond
1848the last line of the def block. Point is left at the start of the
1849def, except that: if the def is preceded by a number of comment lines
1850followed by (at most) one optional blank line, point is left at the
1851start of the comments; else if the def is preceded by a blank line,
1852point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853
1854The intent is to mark the containing def/class and its associated
1855documentation, to make moving and duplicating functions and classes
1856pleasant."
1857 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858 (let ((start (point))
1859 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860 (push-mark start)
1861 (if (not (py-go-up-tree-to-keyword which))
1862 (progn (goto-char start)
1863 (error "Enclosing %s not found" which))
1864 ;; else enclosing def/class found
1865 (setq start (point))
1866 (py-goto-beyond-block)
1867 (push-mark (point))
1868 (goto-char start)
1869 (if (zerop (forward-line -1)) ; if there is a preceding line
1870 (progn
1871 (if (looking-at "[ \t]*$") ; it's blank
1872 (setq start (point)) ; so reset start point
1873 (goto-char start)) ; else try again
1874 (if (zerop (forward-line -1))
1875 (if (looking-at "[ \t]*#") ; a comment
1876 ;; look back for non-comment line
1877 ;; tricky: note that the regexp matches a blank
1878 ;; line, cuz \n is in the 2nd character class
1879 (and
1880 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1881 (forward-line 1))
1882 ;; no comment, so go back
1883 (goto-char start))))))))
1884
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001885;; ripped from cc-mode
1886(defun py-forward-into-nomenclature (&optional arg)
1887 "Move forward to end of a nomenclature section or word.
1888With arg, to it arg times.
1889
1890A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1891 (interactive "p")
1892 (let ((case-fold-search nil))
1893 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001894 (re-search-forward
1895 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1896 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001897 (while (and (< arg 0)
1898 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001899 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001900 (point-min) 0))
1901 (forward-char 1)
1902 (setq arg (1+ arg)))))
1903 (py-keep-region-active))
1904
1905(defun py-backward-into-nomenclature (&optional arg)
1906 "Move backward to beginning of a nomenclature section or word.
1907With optional ARG, move that many times. If ARG is negative, move
1908forward.
1909
1910A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1911 (interactive "p")
1912 (py-forward-into-nomenclature (- arg))
1913 (py-keep-region-active))
1914
1915
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001916
1917;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918
1919;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001920;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1921;; out of the right places, along with the keys they're on & current
1922;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001923(defun py-dump-help-string (str)
1924 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001925 (let ((locals (buffer-local-variables))
1926 funckind funcname func funcdoc
1927 (start 0) mstart end
1928 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1930 (setq mstart (match-beginning 0) end (match-end 0)
1931 funckind (substring str (match-beginning 1) (match-end 1))
1932 funcname (substring str (match-beginning 2) (match-end 2))
1933 func (intern funcname))
1934 (princ (substitute-command-keys (substring str start mstart)))
1935 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936 ((equal funckind "c") ; command
1937 (setq funcdoc (documentation func)
1938 keys (concat
1939 "Key(s): "
1940 (mapconcat 'key-description
1941 (where-is-internal func py-mode-map)
1942 ", "))))
1943 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001944 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945 keys (if (assq func locals)
1946 (concat
1947 "Local/Global values: "
1948 (prin1-to-string (symbol-value func))
1949 " / "
1950 (prin1-to-string (default-value func)))
1951 (concat
1952 "Value: "
1953 (prin1-to-string (symbol-value func))))))
1954 (t ; unexpected
1955 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001956 (princ (format "\n-> %s:\t%s\t%s\n\n"
1957 (if (equal funckind "c") "Command" "Variable")
1958 funcname keys))
1959 (princ funcdoc)
1960 (terpri)
1961 (setq start end))
1962 (princ (substitute-command-keys (substring str start))))
1963 (print-help-return-message)))
1964
1965(defun py-describe-mode ()
1966 "Dump long form of Python-mode docs."
1967 (interactive)
1968 (py-dump-help-string "Major mode for editing Python files.
1969Knows about Python indentation, tokens, comments and continuation lines.
1970Paragraphs are separated by blank lines only.
1971
1972Major sections below begin with the string `@'; specific function and
1973variable docs begin with `->'.
1974
1975@EXECUTING PYTHON CODE
1976
1977\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1978\\[py-execute-region]\tsends the current region
1979\\[py-shell]\tstarts a Python interpreter window; this will be used by
1980\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1981%c:py-execute-buffer
1982%c:py-execute-region
1983%c:py-shell
1984
1985@VARIABLES
1986
1987py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001988py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001989
1990py-python-command\tshell command to invoke Python interpreter
1991py-scroll-process-buffer\talways scroll Python process buffer
1992py-temp-directory\tdirectory used for temp files (if needed)
1993
1994py-beep-if-tab-change\tring the bell if tab-width is changed
1995%v:py-indent-offset
1996%v:py-block-comment-prefix
1997%v:py-python-command
1998%v:py-scroll-process-buffer
1999%v:py-temp-directory
2000%v:py-beep-if-tab-change
2001
2002@KINDS OF LINES
2003
2004Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002005preceding line ends with a backslash that's not part of a comment, or
2006the paren/bracket/brace nesting level at the start of the line is
2007non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002008
2009An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002010possibly blanks or tabs), a `comment line' (leftmost non-blank
2011character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002012
2013Comment Lines
2014
2015Although all comment lines are treated alike by Python, Python mode
2016recognizes two kinds that act differently with respect to indentation.
2017
2018An `indenting comment line' is a comment line with a blank, tab or
2019nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002021indenting comment line will be indented like the comment line. All
2022other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023following the initial `#') are `non-indenting comment lines', and
2024their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025
2026Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002027whenever possible. Non-indenting comment lines are useful in cases
2028like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002029
2030\ta = b # a very wordy single-line comment that ends up being
2031\t #... continued onto another line
2032
2033\tif a == b:
2034##\t\tprint 'panic!' # old code we've `commented out'
2035\t\treturn a
2036
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002037Since the `#...' and `##' comment lines have a non-whitespace
2038character following the initial `#', Python mode ignores them when
2039computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002040
2041Continuation Lines and Statements
2042
2043The Python-mode commands generally work on statements instead of on
2044individual lines, where a `statement' is a comment or blank line, or a
2045code line and all of its following continuation lines (if any)
2046considered as a single logical unit. The commands in this mode
2047generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002048statement containing point, even if point happens to be in the middle
2049of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002050
2051
2052@INDENTATION
2053
2054Primarily for entering new code:
2055\t\\[indent-for-tab-command]\t indent line appropriately
2056\t\\[py-newline-and-indent]\t insert newline, then indent
2057\t\\[py-delete-char]\t reduce indentation, or delete single character
2058
2059Primarily for reindenting existing code:
2060\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2061\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2062
2063\t\\[py-indent-region]\t reindent region to match its context
2064\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2065\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2066
2067Unlike most programming languages, Python uses indentation, and only
2068indentation, to specify block structure. Hence the indentation supplied
2069automatically by Python-mode is just an educated guess: only you know
2070the block structure you intend, so only you can supply correct
2071indentation.
2072
2073The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2074the indentation of preceding statements. E.g., assuming
2075py-indent-offset is 4, after you enter
2076\tif a > 0: \\[py-newline-and-indent]
2077the cursor will be moved to the position of the `_' (_ is not a
2078character in the file, it's just used here to indicate the location of
2079the cursor):
2080\tif a > 0:
2081\t _
2082If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2083to
2084\tif a > 0:
2085\t c = d
2086\t _
2087Python-mode cannot know whether that's what you intended, or whether
2088\tif a > 0:
2089\t c = d
2090\t_
2091was your intent. In general, Python-mode either reproduces the
2092indentation of the (closest code or indenting-comment) preceding
2093statement, or adds an extra py-indent-offset blanks if the preceding
2094statement has `:' as its last significant (non-whitespace and non-
2095comment) character. If the suggested indentation is too much, use
2096\\[py-delete-char] to reduce it.
2097
2098Continuation lines are given extra indentation. If you don't like the
2099suggested indentation, change it to something you do like, and Python-
2100mode will strive to indent later lines of the statement in the same way.
2101
2102If a line is a continuation line by virtue of being in an unclosed
2103paren/bracket/brace structure (`list', for short), the suggested
2104indentation depends on whether the current line contains the first item
2105in the list. If it does, it's indented py-indent-offset columns beyond
2106the indentation of the line containing the open bracket. If you don't
2107like that, change it by hand. The remaining items in the list will mimic
2108whatever indentation you give to the first item.
2109
2110If a line is a continuation line because the line preceding it ends with
2111a backslash, the third and following lines of the statement inherit their
2112indentation from the line preceding them. The indentation of the second
2113line in the statement depends on the form of the first (base) line: if
2114the base line is an assignment statement with anything more interesting
2115than the backslash following the leftmost assigning `=', the second line
2116is indented two columns beyond that `='. Else it's indented to two
2117columns beyond the leftmost solid chunk of non-whitespace characters on
2118the base line.
2119
2120Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2121repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2122structure you intend.
2123%c:indent-for-tab-command
2124%c:py-newline-and-indent
2125%c:py-delete-char
2126
2127
2128The next function may be handy when editing code you didn't write:
2129%c:py-guess-indent-offset
2130
2131
2132The remaining `indent' functions apply to a region of Python code. They
2133assume the block structure (equals indentation, in Python) of the region
2134is correct, and alter the indentation in various ways while preserving
2135the block structure:
2136%c:py-indent-region
2137%c:py-shift-region-left
2138%c:py-shift-region-right
2139
2140@MARKING & MANIPULATING REGIONS OF CODE
2141
2142\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002143\\[py-mark-def-or-class]\t mark smallest enclosing def
2144\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002145\\[comment-region]\t comment out region of code
2146\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002147%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002148%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002149%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002150
2151@MOVING POINT
2152
2153\\[py-previous-statement]\t move to statement preceding point
2154\\[py-next-statement]\t move to statement following point
2155\\[py-goto-block-up]\t move up to start of current block
2156\\[beginning-of-python-def-or-class]\t move to start of def
2157\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2158\\[end-of-python-def-or-class]\t move to end of def
2159\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2160
2161The first two move to one statement beyond the statement that contains
2162point. A numeric prefix argument tells them to move that many
2163statements instead. Blank lines, comment lines, and continuation lines
2164do not count as `statements' for these commands. So, e.g., you can go
2165to the first code statement in a file by entering
2166\t\\[beginning-of-buffer]\t to move to the top of the file
2167\t\\[py-next-statement]\t to skip over initial comments and blank lines
2168Or do `\\[py-previous-statement]' with a huge prefix argument.
2169%c:py-previous-statement
2170%c:py-next-statement
2171%c:py-goto-block-up
2172%c:beginning-of-python-def-or-class
2173%c:end-of-python-def-or-class
2174
2175@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2176
2177`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2178
2179`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2180overall class and def structure of a module.
2181
2182`\\[back-to-indentation]' moves point to a line's first non-blank character.
2183
2184`\\[indent-relative]' is handy for creating odd indentation.
2185
2186@OTHER EMACS HINTS
2187
2188If you don't like the default value of a variable, change its value to
2189whatever you do like by putting a `setq' line in your .emacs file.
2190E.g., to set the indentation increment to 4, put this line in your
2191.emacs:
2192\t(setq py-indent-offset 4)
2193To see the value of a variable, do `\\[describe-variable]' and enter the variable
2194name at the prompt.
2195
2196When entering a key sequence like `C-c C-n', it is not necessary to
2197release the CONTROL key after doing the `C-c' part -- it suffices to
2198press the CONTROL key, press and release `c' (while still holding down
2199CONTROL), press and release `n' (while still holding down CONTROL), &
2200then release CONTROL.
2201
2202Entering Python mode calls with no arguments the value of the variable
2203`python-mode-hook', if that value exists and is not nil; for backward
2204compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2205the Elisp manual for details.
2206
2207Obscure: When python-mode is first loaded, it looks for all bindings
2208to newline-and-indent in the global keymap, and shadows them with
2209local bindings to py-newline-and-indent."))
2210
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002211
2212;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002213(defvar py-parse-state-re
2214 (concat
2215 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2216 "\\|"
2217 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002218
Barry Warsaw7ae77681994-12-12 20:38:05 +00002219;; returns the parse state at point (see parse-partial-sexp docs)
2220(defun py-parse-state ()
2221 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002222 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002223 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002224 (while (not done)
2225 ;; back up to the first preceding line (if any; else start of
2226 ;; buffer) that begins with a popular Python keyword, or a
2227 ;; non- whitespace and non-comment character. These are good
2228 ;; places to start parsing to see whether where we started is
2229 ;; at a non-zero nesting level. It may be slow for people who
2230 ;; write huge code blocks or huge lists ... tough beans.
2231 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002232 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002233 (beginning-of-line)
2234 (save-excursion
2235 (setq pps (parse-partial-sexp (point) here)))
2236 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002237 (setq done (or (zerop ci)
2238 (not (nth 3 pps))
2239 (bobp)))
2240 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002241 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002242
2243;; if point is at a non-zero nesting level, returns the number of the
2244;; character that opens the smallest enclosing unclosed list; else
2245;; returns nil.
2246(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002247 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002248 (if (zerop (car status))
2249 nil ; not in a nest
2250 (car (cdr status))))) ; char# of open bracket
2251
2252;; t iff preceding line ends with backslash that's not in a comment
2253(defun py-backslash-continuation-line-p ()
2254 (save-excursion
2255 (beginning-of-line)
2256 (and
2257 ;; use a cheap test first to avoid the regexp if possible
2258 ;; use 'eq' because char-after may return nil
2259 (eq (char-after (- (point) 2)) ?\\ )
2260 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002261 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002262 (looking-at py-continued-re))))
2263
2264;; t iff current line is a continuation line
2265(defun py-continuation-line-p ()
2266 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002267 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002268 (or (py-backslash-continuation-line-p)
2269 (py-nesting-level))))
2270
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002271;; go to initial line of current statement; usually this is the line
2272;; we're on, but if we're on the 2nd or following lines of a
2273;; continuation block, we need to go up to the first line of the
2274;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002275;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002276;; Tricky: We want to avoid quadratic-time behavior for long continued
2277;; blocks, whether of the backslash or open-bracket varieties, or a
2278;; mix of the two. The following manages to do that in the usual
2279;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002280(defun py-goto-initial-line ()
2281 (let ( open-bracket-pos )
2282 (while (py-continuation-line-p)
2283 (beginning-of-line)
2284 (if (py-backslash-continuation-line-p)
2285 (while (py-backslash-continuation-line-p)
2286 (forward-line -1))
2287 ;; else zip out of nested brackets/braces/parens
2288 (while (setq open-bracket-pos (py-nesting-level))
2289 (goto-char open-bracket-pos)))))
2290 (beginning-of-line))
2291
2292;; go to point right beyond final line of current statement; usually
2293;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002294;; statement we need to skip over the continuation lines. Tricky:
2295;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002296(defun py-goto-beyond-final-line ()
2297 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002298 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002299 (while (and (py-continuation-line-p)
2300 (not (eobp)))
2301 ;; skip over the backslash flavor
2302 (while (and (py-backslash-continuation-line-p)
2303 (not (eobp)))
2304 (forward-line 1))
2305 ;; if in nest, zip to the end of the nest
2306 (setq state (py-parse-state))
2307 (if (and (not (zerop (car state)))
2308 (not (eobp)))
2309 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002310 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002311 (forward-line 1))))))
2312
2313;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002314;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002315(defun py-statement-opens-block-p ()
2316 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002317 (let ((start (point))
2318 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2319 (searching t)
2320 (answer nil)
2321 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322 (goto-char start)
2323 (while searching
2324 ;; look for a colon with nothing after it except whitespace, and
2325 ;; maybe a comment
2326 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2327 finish t)
2328 (if (eq (point) finish) ; note: no `else' clause; just
2329 ; keep searching if we're not at
2330 ; the end yet
2331 ;; sure looks like it opens a block -- but it might
2332 ;; be in a comment
2333 (progn
2334 (setq searching nil) ; search is done either way
2335 (setq state (parse-partial-sexp start
2336 (match-beginning 0)))
2337 (setq answer (not (nth 4 state)))))
2338 ;; search failed: couldn't find another interesting colon
2339 (setq searching nil)))
2340 answer)))
2341
Barry Warsawf831d811996-07-31 20:42:59 +00002342(defun py-statement-closes-block-p ()
2343 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002344 ;; starts with `return', `raise', `break', `continue', and `pass'.
2345 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002346 (let ((here (point)))
2347 (back-to-indentation)
2348 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002349 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002350 (goto-char here))))
2351
Barry Warsaw7ae77681994-12-12 20:38:05 +00002352;; go to point right beyond final line of block begun by the current
2353;; line. This is the same as where py-goto-beyond-final-line goes
2354;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002355;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002356(defun py-goto-beyond-block ()
2357 (if (py-statement-opens-block-p)
2358 (py-mark-block nil 'just-move)
2359 (py-goto-beyond-final-line)))
2360
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002361;; go to start of first statement (not blank or comment or
2362;; continuation line) at or preceding point. returns t if there is
2363;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002364(defun py-goto-statement-at-or-above ()
2365 (py-goto-initial-line)
2366 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002367 ;; skip back over blank & comment lines
2368 ;; note: will skip a blank or comment line that happens to be
2369 ;; a continuation line too
2370 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2371 (progn (py-goto-initial-line) t)
2372 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002373 t))
2374
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002375;; go to start of first statement (not blank or comment or
2376;; continuation line) following the statement containing point returns
2377;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002378(defun py-goto-statement-below ()
2379 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002380 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002381 (py-goto-beyond-final-line)
2382 (while (and
2383 (looking-at py-blank-or-comment-re)
2384 (not (eobp)))
2385 (forward-line 1))
2386 (if (eobp)
2387 (progn (goto-char start) nil)
2388 t)))
2389
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002390;; go to start of statement, at or preceding point, starting with
2391;; keyword KEY. Skips blank lines and non-indenting comments upward
2392;; first. If that statement starts with KEY, done, else go back to
2393;; first enclosing block starting with KEY. If successful, leaves
2394;; point at the start of the KEY line & returns t. Else leaves point
2395;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002396(defun py-go-up-tree-to-keyword (key)
2397 ;; skip blanks and non-indenting #
2398 (py-goto-initial-line)
2399 (while (and
2400 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2401 (zerop (forward-line -1))) ; go back
2402 nil)
2403 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002404 (let* ((re (concat "[ \t]*" key "\\b"))
2405 (case-fold-search nil) ; let* so looking-at sees this
2406 (found (looking-at re))
2407 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002408 (while (not (or found dead))
2409 (condition-case nil ; in case no enclosing block
2410 (py-goto-block-up 'no-mark)
2411 (error (setq dead t)))
2412 (or dead (setq found (looking-at re))))
2413 (beginning-of-line)
2414 found))
2415
2416;; return string in buffer from start of indentation to end of line;
2417;; prefix "..." if leading whitespace was skipped
2418(defun py-suck-up-leading-text ()
2419 (save-excursion
2420 (back-to-indentation)
2421 (concat
2422 (if (bolp) "" "...")
2423 (buffer-substring (point) (progn (end-of-line) (point))))))
2424
2425;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2426;; as a Lisp symbol; return nil if none
2427(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002428 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002429 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2430 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2431 nil)))
2432
Barry Warsaw7ae77681994-12-12 20:38:05 +00002433(defun py-delete-file-silently (fname)
2434 (condition-case nil
2435 (delete-file fname)
2436 (error nil)))
2437
2438(defun py-kill-emacs-hook ()
2439 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002440 (py-safe (while py-file-queue
2441 (py-delete-file-silently (car py-file-queue))
2442 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002443
Barry Warsawb3e81d51996-09-04 15:12:42 +00002444(defun py-current-defun ()
2445 ;; tell add-log.el how to find the current function/method/variable
2446 (save-excursion
2447 (if (re-search-backward py-defun-start-re nil t)
2448 (or (match-string 3)
2449 (let ((method (match-string 2)))
2450 (if (and (not (zerop (length (match-string 1))))
2451 (re-search-backward py-class-start-re nil t))
2452 (concat (match-string 1) "." method)
2453 method)))
2454 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002455
2456
Barry Warsawfec75d61995-07-05 23:26:15 +00002457(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002458 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002459
Barry Warsaw850437a1995-03-08 21:50:28 +00002460(defun py-version ()
2461 "Echo the current version of `python-mode' in the minibuffer."
2462 (interactive)
2463 (message "Using `python-mode' version %s" py-version)
2464 (py-keep-region-active))
2465
2466;; only works under Emacs 19
2467;(eval-when-compile
2468; (require 'reporter))
2469
2470(defun py-submit-bug-report (enhancement-p)
2471 "Submit via mail a bug report on `python-mode'.
2472With \\[universal-argument] just submit an enhancement request."
2473 (interactive
2474 (list (not (y-or-n-p
2475 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002476 (let ((reporter-prompt-for-summary-p (if enhancement-p
2477 "(Very) brief summary: "
2478 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002479 (require 'reporter)
2480 (reporter-submit-bug-report
2481 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002482 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002483 ;; varlist
2484 (if enhancement-p nil
2485 '(py-python-command
2486 py-indent-offset
2487 py-block-comment-prefix
2488 py-scroll-process-buffer
2489 py-temp-directory
2490 py-beep-if-tab-change))
2491 nil ;pre-hooks
2492 nil ;post-hooks
2493 "Dear Barry,") ;salutation
2494 (if enhancement-p nil
2495 (set-mark (point))
2496 (insert
2497"Please replace this text with a sufficiently large code sample\n\
2498and an exact recipe so that I can reproduce your problem. Failure\n\
2499to do so may mean a greater delay in fixing your bug.\n\n")
2500 (exchange-point-and-mark)
2501 (py-keep-region-active))))
2502
2503
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002504;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002505(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002506
2507
2508
2509(provide 'python-mode)
2510;;; python-mode.el ends here