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