blob: 4ddd18ac978e204d7aff04de3f57408c406187b7 [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))
416 ;; Miscellaneous
417 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
418 (define-key py-mode-map "\C-c\t" 'py-indent-region)
419 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
420 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
421 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
422 (define-key py-mode-map "\C-c\C-m" 'py-mark-block)
423 (define-key py-mode-map "\C-c#" 'py-comment-region)
424 (define-key py-mode-map "\C-c?" 'py-describe-mode)
425 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
426 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
427 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
428 (define-key py-mode-map "\e\C-h" 'mark-python-def-or-class)
429 ;; information
430 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
431 (define-key py-mode-map "\C-c\C-v" 'py-version)
432 ;; py-newline-and-indent mappings
433 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000434 ;; shadow global bindings for newline-and-indent w/ the py- version.
435 ;; BAW - this is extremely bad form, but I'm not going to change it
436 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000437 (mapcar (function (lambda (key)
438 (define-key
439 py-mode-map key 'py-newline-and-indent)))
440 (where-is-internal 'newline-and-indent))
Barry Warsaw850437a1995-03-08 21:50:28 +0000441 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000442
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000443(defvar py-mode-syntax-table nil
444 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000446 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000447 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000448 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
449 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
450 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
451 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
452 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
453 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
454 ;; Add operator symbols misassigned in the std table
455 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
456 (modify-syntax-entry ?\% "." py-mode-syntax-table)
457 (modify-syntax-entry ?\& "." py-mode-syntax-table)
458 (modify-syntax-entry ?\* "." py-mode-syntax-table)
459 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
460 (modify-syntax-entry ?\- "." py-mode-syntax-table)
461 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
462 (modify-syntax-entry ?\< "." py-mode-syntax-table)
463 (modify-syntax-entry ?\= "." py-mode-syntax-table)
464 (modify-syntax-entry ?\> "." py-mode-syntax-table)
465 (modify-syntax-entry ?\| "." py-mode-syntax-table)
466 ;; For historical reasons, underscore is word class instead of
467 ;; symbol class. GNU conventions say it should be symbol class, but
468 ;; there's a natural conflict between what major mode authors want
469 ;; and what users expect from `forward-word' and `backward-word'.
470 ;; Guido and I have hashed this out and have decided to keep
471 ;; underscore in word class. If you're tempted to change it, try
472 ;; binding M-f and M-b to py-forward-into-nomenclature and
473 ;; py-backward-into-nomenclature instead.
474 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
475 ;; Both single quote and double quote are string delimiters
476 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
477 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
478 ;; backquote is open and close paren
479 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
480 ;; comment delimiters
481 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
482 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
483 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000484
Barry Warsawb3e81d51996-09-04 15:12:42 +0000485
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000486
Barry Warsaw42f707f1996-07-29 21:05:05 +0000487;; Menu definitions, only relevent if you have the easymenu.el package
488;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000489(defvar py-menu nil
490 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000491This menu will get created automatically if you have the `easymenu'
492package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000493
Barry Warsawc72c11c1997-08-09 06:42:08 +0000494(and (py-safe (require 'easymenu) t)
495 (easy-menu-define
496 py-menu py-mode-map "Python Mode menu"
497 '("Python"
498 ["Comment Out Region" py-comment-region (mark)]
499 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
500 "-"
501 ["Mark current block" py-mark-block t]
502 ["Mark current def" mark-python-def-or-class t]
503 ["Mark current class" (mark-python-def-or-class t) t]
504 "-"
505 ["Shift region left" py-shift-region-left (mark)]
506 ["Shift region right" py-shift-region-right (mark)]
507 "-"
508 ["Execute buffer" py-execute-buffer t]
509 ["Execute region" py-execute-region (mark)]
510 ["Start interpreter..." py-shell t]
511 "-"
512 ["Go to start of block" py-goto-block-up t]
513 ["Go to start of class" (beginning-of-python-def-or-class t) t]
514 ["Move to end of class" (end-of-python-def-or-class t) t]
515 ["Move to start of def" beginning-of-python-def-or-class t]
516 ["Move to end of def" end-of-python-def-or-class t]
517 "-"
518 ["Describe mode" py-describe-mode t]
519 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000520
Barry Warsaw81437461996-08-01 19:48:02 +0000521
522
523;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
524(defvar imenu-example--python-class-regexp
525 (concat ; <<classes>>
526 "\\(" ;
527 "^[ \t]*" ; newline and maybe whitespace
528 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
529 ; possibly multiple superclasses
530 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
531 "[ \t]*:" ; and the final :
532 "\\)" ; >>classes<<
533 )
534 "Regexp for Python classes for use with the imenu package."
535 )
536
537(defvar imenu-example--python-method-regexp
538 (concat ; <<methods and functions>>
539 "\\(" ;
540 "^[ \t]*" ; new line and maybe whitespace
541 "\\(def[ \t]+" ; function definitions start with def
542 "\\([a-zA-Z0-9_]+\\)" ; name is here
543 ; function arguments...
544 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
545 "\\)" ; end of def
546 "[ \t]*:" ; and then the :
547 "\\)" ; >>methods and functions<<
548 )
549 "Regexp for Python methods/functions for use with the imenu package."
550 )
551
552(defvar imenu-example--python-method-no-arg-parens '(2 8)
553 "Indicies into groups of the Python regexp for use with imenu.
554
555Using these values will result in smaller imenu lists, as arguments to
556functions are not listed.
557
558See the variable `imenu-example--python-show-method-args-p' for more
559information.")
560
561(defvar imenu-example--python-method-arg-parens '(2 7)
562 "Indicies into groups of the Python regexp for use with imenu.
563Using these values will result in large imenu lists, as arguments to
564functions are listed.
565
566See the variable `imenu-example--python-show-method-args-p' for more
567information.")
568
569;; Note that in this format, this variable can still be used with the
570;; imenu--generic-function. Otherwise, there is no real reason to have
571;; it.
572(defvar imenu-example--generic-python-expression
573 (cons
574 (concat
575 imenu-example--python-class-regexp
576 "\\|" ; or...
577 imenu-example--python-method-regexp
578 )
579 imenu-example--python-method-no-arg-parens)
580 "Generic Python expression which may be used directly with imenu.
581Used by setting the variable `imenu-generic-expression' to this value.
582Also, see the function \\[imenu-example--create-python-index] for a
583better alternative for finding the index.")
584
585;; These next two variables are used when searching for the python
586;; class/definitions. Just saving some time in accessing the
587;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000588(defvar imenu-example--python-generic-regexp nil)
589(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000590
591
592;;;###autoload
593(eval-when-compile
594 ;; Imenu isn't used in XEmacs, so just ignore load errors
595 (condition-case ()
596 (progn
597 (require 'cl)
598 (require 'imenu))
599 (error nil)))
600
601(defun imenu-example--create-python-index ()
602 "Python interface function for imenu package.
603Finds all python classes and functions/methods. Calls function
604\\[imenu-example--create-python-index-engine]. See that function for
605the details of how this works."
606 (setq imenu-example--python-generic-regexp
607 (car imenu-example--generic-python-expression))
608 (setq imenu-example--python-generic-parens
609 (if imenu-example--python-show-method-args-p
610 imenu-example--python-method-arg-parens
611 imenu-example--python-method-no-arg-parens))
612 (goto-char (point-min))
613 (imenu-example--create-python-index-engine nil))
614
615(defun imenu-example--create-python-index-engine (&optional start-indent)
616 "Function for finding imenu definitions in Python.
617
618Finds all definitions (classes, methods, or functions) in a Python
619file for the imenu package.
620
621Returns a possibly nested alist of the form
622
623 (INDEX-NAME . INDEX-POSITION)
624
625The second element of the alist may be an alist, producing a nested
626list as in
627
628 (INDEX-NAME . INDEX-ALIST)
629
630This function should not be called directly, as it calls itself
631recursively and requires some setup. Rather this is the engine for
632the function \\[imenu-example--create-python-index].
633
634It works recursively by looking for all definitions at the current
635indention level. When it finds one, it adds it to the alist. If it
636finds a definition at a greater indentation level, it removes the
637previous definition from the alist. In it's place it adds all
638definitions found at the next indentation level. When it finds a
639definition that is less indented then the current level, it retuns the
640alist it has created thus far.
641
642The optional argument START-INDENT indicates the starting indentation
643at which to continue looking for Python classes, methods, or
644functions. If this is not supplied, the function uses the indentation
645of the first definition found."
646 (let ((index-alist '())
647 (sub-method-alist '())
648 looking-p
649 def-name prev-name
650 cur-indent def-pos
651 (class-paren (first imenu-example--python-generic-parens))
652 (def-paren (second imenu-example--python-generic-parens)))
653 (setq looking-p
654 (re-search-forward imenu-example--python-generic-regexp
655 (point-max) t))
656 (while looking-p
657 (save-excursion
658 ;; used to set def-name to this value but generic-extract-name is
659 ;; new to imenu-1.14. this way it still works with imenu-1.11
660 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
661 (let ((cur-paren (if (match-beginning class-paren)
662 class-paren def-paren)))
663 (setq def-name
664 (buffer-substring (match-beginning cur-paren)
665 (match-end cur-paren))))
666 (beginning-of-line)
667 (setq cur-indent (current-indentation)))
668
669 ;; HACK: want to go to the next correct definition location. we
670 ;; explicitly list them here. would be better to have them in a
671 ;; list.
672 (setq def-pos
673 (or (match-beginning class-paren)
674 (match-beginning def-paren)))
675
676 ;; if we don't have a starting indent level, take this one
677 (or start-indent
678 (setq start-indent cur-indent))
679
680 ;; if we don't have class name yet, take this one
681 (or prev-name
682 (setq prev-name def-name))
683
684 ;; what level is the next definition on? must be same, deeper
685 ;; or shallower indentation
686 (cond
687 ;; at the same indent level, add it to the list...
688 ((= start-indent cur-indent)
689
690 ;; if we don't have push, use the following...
691 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
692 (push (cons def-name def-pos) index-alist))
693
694 ;; deeper indented expression, recur...
695 ((< start-indent cur-indent)
696
697 ;; the point is currently on the expression we're supposed to
698 ;; start on, so go back to the last expression. The recursive
699 ;; call will find this place again and add it to the correct
700 ;; list
701 (re-search-backward imenu-example--python-generic-regexp
702 (point-min) 'move)
703 (setq sub-method-alist (imenu-example--create-python-index-engine
704 cur-indent))
705
706 (if sub-method-alist
707 ;; we put the last element on the index-alist on the start
708 ;; of the submethod alist so the user can still get to it.
709 (let ((save-elmt (pop index-alist)))
710 (push (cons (imenu-create-submenu-name prev-name)
711 (cons save-elmt sub-method-alist))
712 index-alist))))
713
714 ;; found less indented expression, we're done.
715 (t
716 (setq looking-p nil)
717 (re-search-backward imenu-example--python-generic-regexp
718 (point-min) t)))
719 (setq prev-name def-name)
720 (and looking-p
721 (setq looking-p
722 (re-search-forward imenu-example--python-generic-regexp
723 (point-max) 'move))))
724 (nreverse index-alist)))
725
Barry Warsaw42f707f1996-07-29 21:05:05 +0000726
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000727;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000728(defun python-mode ()
729 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000730To submit a problem report, enter `\\[py-submit-bug-report]' from a
731`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
732documentation. To see what version of `python-mode' you are running,
733enter `\\[py-version]'.
734
735This mode knows about Python indentation, tokens, comments and
736continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000737
738COMMANDS
739\\{py-mode-map}
740VARIABLES
741
Barry Warsaw42f707f1996-07-29 21:05:05 +0000742py-indent-offset\t\tindentation increment
743py-block-comment-prefix\t\tcomment string used by comment-region
744py-python-command\t\tshell command to invoke Python interpreter
745py-scroll-process-buffer\t\talways scroll Python process buffer
746py-temp-directory\t\tdirectory used for temp files (if needed)
747py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000749 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000750 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000751 (make-local-variable 'font-lock-defaults)
752 (make-local-variable 'paragraph-separate)
753 (make-local-variable 'paragraph-start)
754 (make-local-variable 'require-final-newline)
755 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000756 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000757 (make-local-variable 'comment-start-skip)
758 (make-local-variable 'comment-column)
759 (make-local-variable 'indent-region-function)
760 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000761 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000762 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000763 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000764 (setq major-mode 'python-mode
765 mode-name "Python"
766 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000767 paragraph-separate "^[ \t]*$"
768 paragraph-start "^[ \t]*$"
769 require-final-newline t
770 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000771 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000772 comment-start-skip "# *"
773 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000774 indent-region-function 'py-indent-region
775 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000776 ;; tell add-log.el how to find the current function/method/variable
777 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000778 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000779 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000780 ;; add the menu
781 (if py-menu
782 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000783 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000784 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000785 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000786 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000787 ;;
788 ;; not sure where the magic comment has to be; to save time
789 ;; searching for a rarity, we give up if it's not found prior to the
790 ;; first executable statement.
791 ;;
792 ;; BAW - on first glance, this seems like complete hackery. Why was
793 ;; this necessary, and is it still necessary?
794 (let ((case-fold-search nil)
795 (start (point))
796 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000797 (if (re-search-forward
798 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
799 (prog2 (py-next-statement 1) (point) (goto-char 1))
800 t)
801 (progn
802 (setq new-tab-width
803 (string-to-int
804 (buffer-substring (match-beginning 1) (match-end 1))))
805 (if (= tab-width new-tab-width)
806 nil
807 (setq tab-width new-tab-width)
808 (message "Caution: tab-width changed to %d" new-tab-width)
809 (if py-beep-if-tab-change (beep)))))
810 (goto-char start))
811
Barry Warsaw755c6711996-08-01 20:02:55 +0000812 ;; install imenu
813 (setq imenu-create-index-function
814 (function imenu-example--create-python-index))
815 (if (fboundp 'imenu-add-to-menubar)
816 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
817
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000818 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000819 (if python-mode-hook
820 (run-hooks 'python-mode-hook)
821 (run-hooks 'py-mode-hook)))
822
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000823
Barry Warsawb91b7431995-03-14 15:55:20 +0000824;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000825(defun py-outdent-p ()
826 ;; returns non-nil if the current line should outdent one level
827 (save-excursion
828 (and (progn (back-to-indentation)
829 (looking-at py-outdent-re))
830 (progn (backward-to-indentation 1)
831 (while (or (looking-at py-blank-or-comment-re)
832 (bobp))
833 (backward-to-indentation 1))
834 (not (looking-at py-no-outdent-re)))
835 )))
836
Barry Warsawb91b7431995-03-14 15:55:20 +0000837(defun py-electric-colon (arg)
838 "Insert a colon.
839In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000840argument is provided, that many colons are inserted non-electrically.
841Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000842 (interactive "P")
843 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000844 ;; are we in a string or comment?
845 (if (save-excursion
846 (let ((pps (parse-partial-sexp (save-excursion
847 (beginning-of-python-def-or-class)
848 (point))
849 (point))))
850 (not (or (nth 3 pps) (nth 4 pps)))))
851 (save-excursion
852 (let ((here (point))
853 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000854 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000855 (if (and (not arg)
856 (py-outdent-p)
857 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000858 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000859 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000860 )
861 (setq outdent py-indent-offset))
862 ;; Don't indent, only outdent. This assumes that any lines that
863 ;; are already outdented relative to py-compute-indentation were
864 ;; put there on purpose. Its highly annoying to have `:' indent
865 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
866 ;; there a better way to determine this???
867 (if (< (current-indentation) indent) nil
868 (goto-char here)
869 (beginning-of-line)
870 (delete-horizontal-space)
871 (indent-to (- indent outdent))
872 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000873
874
Barry Warsawa97a3f31997-11-04 18:47:06 +0000875;; Python subprocess utilities and filters
876(defun py-execute-file (proc filename)
877 ;; Send a properly formatted execfile('FILENAME') to the underlying
878 ;; Python interpreter process FILENAME. Make that process's buffer
879 ;; visible and force display. Also make comint believe the user
880 ;; typed this string so that kill-output-from-shell does The Right
881 ;; Thing.
882 (let ((curbuf (current-buffer))
883 (procbuf (process-buffer proc))
884 (comint-scroll-to-bottom-on-output t)
885 (msg (format "## working on region in file %s...\n" filename))
886 (cmd (format "execfile('%s')\n" filename)))
887 (unwind-protect
888 (progn
889 (set-buffer procbuf)
890 (goto-char (point-max))
891 (move-marker (process-mark proc) (point))
892 (funcall (process-filter proc) proc msg))
893 (set-buffer curbuf))
894 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000895
896(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 (let ((curbuf (current-buffer))
898 (pbuf (process-buffer pyproc))
899 (pmark (process-mark pyproc))
900 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901 ;; make sure we switch to a different buffer at least once. if we
902 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000903 ;; window, and point is before the end, and lots of output is
904 ;; coming at a fast pace, then (a) simple cursor-movement commands
905 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
906 ;; to have a visible effect (the window just doesn't get updated,
907 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
908 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000910 ;; #b makes no sense to me at all. #a almost makes sense: unless
911 ;; we actually change buffers, set_buffer_internal in buffer.c
912 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
913 ;; seems to make the Emacs command loop reluctant to update the
914 ;; display. Perhaps the default process filter in process.c's
915 ;; read_process_output has update_mode_lines++ for a similar
916 ;; reason? beats me ...
917
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000918 (unwind-protect
919 ;; make sure current buffer is restored
920 ;; BAW - we want to check to see if this still applies
921 (progn
922 ;; mysterious ugly hack
923 (if (eq curbuf pbuf)
924 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000926 (set-buffer pbuf)
927 (let* ((start (point))
928 (goback (< start pmark))
929 (goend (and (not goback) (= start (point-max))))
930 (buffer-read-only nil))
931 (goto-char pmark)
932 (insert string)
933 (move-marker pmark (point))
934 (setq file-finished
935 (and py-file-queue
936 (equal ">>> "
937 (buffer-substring
938 (prog2 (beginning-of-line) (point)
939 (goto-char pmark))
940 (point)))))
941 (if goback (goto-char start)
942 ;; else
943 (if py-scroll-process-buffer
944 (let* ((pop-up-windows t)
945 (pwin (display-buffer pbuf)))
946 (set-window-point pwin (point)))))
947 (set-buffer curbuf)
948 (if file-finished
949 (progn
950 (py-delete-file-silently (car py-file-queue))
951 (setq py-file-queue (cdr py-file-queue))
952 (if py-file-queue
953 (py-execute-file pyproc (car py-file-queue)))))
954 (and goend
955 (progn (set-buffer pbuf)
956 (goto-char (point-max))))
957 ))
958 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000959
Barry Warsawa97a3f31997-11-04 18:47:06 +0000960
961;;; Subprocess commands
962
963;;;###autoload
964(defun py-shell ()
965 "Start an interactive Python interpreter in another window.
966This is like Shell mode, except that Python is running in the window
967instead of a shell. See the `Interactive Shell' and `Shell Mode'
968sections of the Emacs manual for details, especially for the key
969bindings active in the `*Python*' buffer.
970
971See the docs for variable `py-scroll-buffer' for info on scrolling
972behavior in the process window.
973
974Warning: Don't use an interactive Python if you change sys.ps1 or
975sys.ps2 from their default values, or if you're running code that
976prints `>>> ' or `... ' at the start of a line. `python-mode' can't
977distinguish your output from Python's output, and assumes that `>>> '
978at the start of a line is a prompt from Python. Similarly, the Emacs
979Shell mode code assumes that both `>>> ' and `... ' at the start of a
980line are Python prompts. Bad things can happen if you fool either
981mode.
982
983Warning: If you do any editing *in* the process buffer *while* the
984buffer is accepting output from Python, do NOT attempt to `undo' the
985changes. Some of the output (nowhere near the parts you changed!) may
986be lost if you do. This appears to be an Emacs bug, an unfortunate
987interaction between undo and process filters; the same problem exists in
988non-Python process buffers using the default (Emacs-supplied) process
989filter."
990 ;; BAW - should undo be disabled in the python process buffer, if
991 ;; this bug still exists?
992 (interactive)
993 (require 'comint)
994 (switch-to-buffer-other-window (make-comint "Python" py-python-command "-i"))
995 (make-local-variable 'comint-prompt-regexp)
996 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
997 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
998 (set-syntax-table py-mode-syntax-table)
999 (local-set-key [tab] 'self-insert-command))
1000
1001
1002(defun py-clear-queue ()
1003 "Clear the queue of temporary files waiting to execute."
1004 (interactive)
1005 (let ((n (length py-file-queue)))
1006 (mapcar 'delete-file py-file-queue)
1007 (setq py-file-queue nil)
1008 (message "%d pending files de-queued." n)))
1009
1010(defun py-execute-region (start end &optional async)
1011 "Execute the the region in a Python interpreter.
1012The region is first copied into a temporary file (in the directory
1013`py-temp-directory'). If there is no Python interpreter shell
1014running, this file is executed synchronously using
1015`shell-command-on-region'. If the program is long running, use an
1016optional \\[universal-argument] to run the command asynchronously in
1017its own buffer.
1018
1019If the Python interpreter shell is running, the region is execfile()'d
1020in that shell. If you try to execute regions too quickly,
1021`python-mode' will queue them up and execute them one at a time when
1022it sees a `>>> ' prompt from Python. Each time this happens, the
1023process buffer is popped into a window (if it's not already in some
1024window) so you can see it, and a comment of the form
1025
1026 \t## working on region in file <name>...
1027
1028is inserted at the end. See also the command `py-clear-queue'."
1029 (interactive "r\nP")
1030 (or (< start end)
1031 (error "Region is empty"))
1032 (let* ((proc (get-process "Python"))
1033 (temp (make-temp-name "python"))
1034 (file (concat (file-name-as-directory py-temp-directory) temp))
1035 (outbuf "*Python Output*"))
1036 (write-region start end file nil 'nomsg)
1037 (cond
1038 ;; always run the code in it's own asynchronous subprocess
1039 (async
1040 (let* ((buf (generate-new-buffer-name "*Python Output*")))
1041 (start-process "Python" buf py-python-command "-u" file)
1042 (pop-to-buffer buf)
1043 ))
1044 ;; if the Python interpreter shell is running, queue it up for
1045 ;; execution there.
1046 (proc
1047 ;; use the existing python shell
1048 (if (not py-file-queue)
1049 (py-execute-file proc file)
1050 (push file py-file-queue)
1051 (message "File %s queued for execution" file))
1052 )
1053 (t
1054 ;; otherwise either run it synchronously in a subprocess
1055 (shell-command-on-region start end py-python-command outbuf)
1056 ))))
1057
1058;; Code execution command
1059(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001060 "Send the contents of the buffer to a Python interpreter.
1061If there is a *Python* process buffer it is used. If a clipping
1062restriction is in effect, only the accessible portion of the buffer is
1063sent. A trailing newline will be supplied if needed.
1064
1065See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001066 (interactive "P")
1067 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001068
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001070;; Electric deletion
1071(defun py-electric-backspace (arg)
1072 "Deletes preceding character or levels of indentation.
1073Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001074with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001076If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001077
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001078Otherwise, if point is at the leftmost non-whitespace character of a
1079line that is neither a continuation line nor a non-indenting comment
1080line, or if point is at the end of a blank line, this command reduces
1081the indentation to match that of the line that opened the current
1082block of code. The line that opened the block is displayed in the
1083echo area to help you keep track of where you are. With numeric arg,
1084outdents that many blocks (but not past column zero).
1085
1086Otherwise the preceding character is deleted, converting a tab to
1087spaces if needed so that only a single column position is deleted.
1088Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001089 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001090 (if (or (/= (current-indentation) (current-column))
1091 (bolp)
1092 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001093 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001095 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001096 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097 ;; force non-blank so py-goto-block-up doesn't ignore it
1098 (insert-char ?* 1)
1099 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001100 (let ((base-indent 0) ; indentation of base line
1101 (base-text "") ; and text of base line
1102 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001103 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001104 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001105 (condition-case nil ; in case no enclosing block
1106 (progn
1107 (py-goto-block-up 'no-mark)
1108 (setq base-indent (current-indentation)
1109 base-text (py-suck-up-leading-text)
1110 base-found-p t))
1111 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001112 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001113 (delete-char 1) ; toss the dummy character
1114 (delete-horizontal-space)
1115 (indent-to base-indent)
1116 (if base-found-p
1117 (message "Closes block: %s" base-text)))))
1118
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001119
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001120(defun py-electric-delete (arg)
1121 "Deletes preceding or following character or levels of whitespace.
1122
1123The behavior of this function depends on the variable
1124`delete-key-deletes-forward'. If this variable is nil (or does not
1125exist, as in older Emacsen), then this function behaves identical to
1126\\[c-electric-backspace].
1127
1128If `delete-key-deletes-forward' is non-nil and is supported in your
1129Emacs, then deletion occurs in the forward direction, by calling the
1130function in `py-delete-function'."
1131 (interactive "*p")
1132 (if (and (boundp 'delete-key-deletes-forward)
1133 delete-key-deletes-forward)
1134 (funcall py-delete-function arg)
1135 ;; else
1136 (py-electric-backspace arg)))
1137
1138;; required for pending-del and delsel modes
1139(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1140(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1141(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1142(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1143
1144
1145
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001146(defun py-indent-line (&optional arg)
1147 "Fix the indentation of the current line according to Python rules.
1148With \\[universal-argument], ignore outdenting rules for block
1149closing statements (e.g. return, raise, break, continue, pass)
1150
1151This function is normally bound to `indent-line-function' so
1152\\[indent-for-tab-command] will call it."
1153 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001154 (let* ((ci (current-indentation))
1155 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001156 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001157 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001158 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001159 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001160 (if (/= ci need)
1161 (save-excursion
1162 (beginning-of-line)
1163 (delete-horizontal-space)
1164 (indent-to need)))
1165 (if move-to-indentation-p (back-to-indentation))))
1166
1167(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001168 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169This is just `strives to' because correct indentation can't be computed
1170from scratch for Python code. In general, deletes the whitespace before
1171point, inserts a newline, and takes an educated guess as to how you want
1172the new line indented."
1173 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001174 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001175 (if (< ci (current-column)) ; if point beyond indentation
1176 (newline-and-indent)
1177 ;; else try to act like newline-and-indent "normally" acts
1178 (beginning-of-line)
1179 (insert-char ?\n 1)
1180 (move-to-column ci))))
1181
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001182(defun py-compute-indentation (honor-block-close-p)
1183 ;; implements all the rules for indentation computation. when
1184 ;; honor-block-close-p is non-nil, statements such as return, raise,
1185 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001186 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001187 (let ((pps (parse-partial-sexp (save-excursion
1188 (beginning-of-python-def-or-class)
1189 (point))
1190 (point))))
1191 (beginning-of-line)
1192 (cond
1193 ;; are we inside a string or comment?
1194 ((or (nth 3 pps) (nth 4 pps))
1195 (save-excursion
1196 (if (not py-align-multiline-strings-p) 0
1197 ;; skip back over blank & non-indenting comment lines
1198 ;; note: will skip a blank or non-indenting comment line
1199 ;; that happens to be a continuation line too
1200 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1201 (back-to-indentation)
1202 (current-column))))
1203 ;; are we on a continuation line?
1204 ((py-continuation-line-p)
1205 (let ((startpos (point))
1206 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001207 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001208 (if open-bracket-pos
1209 (progn
1210 ;; align with first item in list; else a normal
1211 ;; indent beyond the line with the open bracket
1212 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1213 ;; is the first list item on the same line?
1214 (skip-chars-forward " \t")
1215 (if (null (memq (following-char) '(?\n ?# ?\\)))
1216 ; yes, so line up with it
1217 (current-column)
1218 ;; first list item on another line, or doesn't exist yet
1219 (forward-line 1)
1220 (while (and (< (point) startpos)
1221 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1222 (forward-line 1))
1223 (if (< (point) startpos)
1224 ;; again mimic the first list item
1225 (current-indentation)
1226 ;; else they're about to enter the first item
1227 (goto-char open-bracket-pos)
1228 (+ (current-indentation) py-indent-offset))))
1229
1230 ;; else on backslash continuation line
1231 (forward-line -1)
1232 (if (py-continuation-line-p) ; on at least 3rd line in block
1233 (current-indentation) ; so just continue the pattern
1234 ;; else started on 2nd line in block, so indent more.
1235 ;; if base line is an assignment with a start on a RHS,
1236 ;; indent to 2 beyond the leftmost "="; else skip first
1237 ;; chunk of non-whitespace characters on base line, + 1 more
1238 ;; column
1239 (end-of-line)
1240 (setq endpos (point) searching t)
1241 (back-to-indentation)
1242 (setq startpos (point))
1243 ;; look at all "=" from left to right, stopping at first
1244 ;; one not nested in a list or string
1245 (while searching
1246 (skip-chars-forward "^=" endpos)
1247 (if (= (point) endpos)
1248 (setq searching nil)
1249 (forward-char 1)
1250 (setq state (parse-partial-sexp startpos (point)))
1251 (if (and (zerop (car state)) ; not in a bracket
1252 (null (nth 3 state))) ; & not in a string
1253 (progn
1254 (setq searching nil) ; done searching in any case
1255 (setq found
1256 (not (or
1257 (eq (following-char) ?=)
1258 (memq (char-after (- (point) 2))
1259 '(?< ?> ?!)))))))))
1260 (if (or (not found) ; not an assignment
1261 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1262 (progn
1263 (goto-char startpos)
1264 (skip-chars-forward "^ \t\n")))
1265 (1+ (current-column))))))
1266
1267 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001268 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001269
Barry Warsawa7891711996-08-01 15:53:09 +00001270 ;; Dfn: "Indenting comment line". A line containing only a
1271 ;; comment, but which is treated like a statement for
1272 ;; indentation calculation purposes. Such lines are only
1273 ;; treated specially by the mode; they are not treated
1274 ;; specially by the Python interpreter.
1275
1276 ;; The rules for indenting comment lines are a line where:
1277 ;; - the first non-whitespace character is `#', and
1278 ;; - the character following the `#' is whitespace, and
1279 ;; - the line is outdented with respect to (i.e. to the left
1280 ;; of) the indentation of the preceding non-blank line.
1281
1282 ;; The first non-blank line following an indenting comment
1283 ;; line is given the same amount of indentation as the
1284 ;; indenting comment line.
1285
1286 ;; All other comment-only lines are ignored for indentation
1287 ;; purposes.
1288
1289 ;; Are we looking at a comment-only line which is *not* an
1290 ;; indenting comment line? If so, we assume that its been
1291 ;; placed at the desired indentation, so leave it alone.
1292 ;; Indenting comment lines are aligned as statements down
1293 ;; below.
1294 ((and (looking-at "[ \t]*#[^ \t\n]")
1295 ;; NOTE: this test will not be performed in older Emacsen
1296 (fboundp 'forward-comment)
1297 (<= (current-indentation)
1298 (save-excursion
1299 (forward-comment (- (point-max)))
1300 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001301 (current-indentation))
1302
1303 ;; else indentation based on that of the statement that
1304 ;; precedes us; use the first line of that statement to
1305 ;; establish the base, in case the user forced a non-std
1306 ;; indentation for the continuation lines (if any)
1307 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001308 ;; skip back over blank & non-indenting comment lines note:
1309 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001310 ;; happens to be a continuation line too. use fast Emacs 19
1311 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001312 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001313 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001314 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001315 (let (done)
1316 (while (not done)
1317 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1318 nil 'move)
1319 (setq done (or (eq py-honor-comment-indentation t)
1320 (bobp)
1321 (/= (following-char) ?#)
1322 (not (zerop (current-column)))))
1323 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001324 ;; if we landed inside a string, go to the beginning of that
1325 ;; string. this handles triple quoted, multi-line spanning
1326 ;; strings.
1327 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001328 (+ (current-indentation)
1329 (if (py-statement-opens-block-p)
1330 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001331 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001332 (- py-indent-offset)
1333 0)))
1334 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001335
1336(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001337 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001338By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001339`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001341`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001342their own buffer-local copy), both those currently existing and those
1343created later in the Emacs session.
1344
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001345Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001346There's no excuse for such foolishness, but sometimes you have to deal
1347with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348`py-indent-offset' to what it thinks it was when they created the
1349mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001350
1351Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001352looking for a line that opens a block of code. `py-indent-offset' is
1353set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354statement following it. If the search doesn't succeed going forward,
1355it's tried again going backward."
1356 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001357 (let (new-value
1358 (start (point))
1359 restart
1360 (found nil)
1361 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001362 (py-goto-initial-line)
1363 (while (not (or found (eobp)))
1364 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1365 (progn
1366 (setq restart (point))
1367 (py-goto-initial-line)
1368 (if (py-statement-opens-block-p)
1369 (setq found t)
1370 (goto-char restart)))))
1371 (if found
1372 ()
1373 (goto-char start)
1374 (py-goto-initial-line)
1375 (while (not (or found (bobp)))
1376 (setq found
1377 (and
1378 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1379 (or (py-goto-initial-line) t) ; always true -- side effect
1380 (py-statement-opens-block-p)))))
1381 (setq colon-indent (current-indentation)
1382 found (and found (zerop (py-next-statement 1)))
1383 new-value (- (current-indentation) colon-indent))
1384 (goto-char start)
1385 (if found
1386 (progn
1387 (funcall (if global 'kill-local-variable 'make-local-variable)
1388 'py-indent-offset)
1389 (setq py-indent-offset new-value)
1390 (message "%s value of py-indent-offset set to %d"
1391 (if global "Global" "Local")
1392 py-indent-offset))
1393 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1394
1395(defun py-shift-region (start end count)
1396 (save-excursion
1397 (goto-char end) (beginning-of-line) (setq end (point))
1398 (goto-char start) (beginning-of-line) (setq start (point))
1399 (indent-rigidly start end count)))
1400
1401(defun py-shift-region-left (start end &optional count)
1402 "Shift region of Python code to the left.
1403The lines from the line containing the start of the current region up
1404to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001405shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406
1407If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001408many columns. With no active region, outdent only the current line.
1409You cannot outdent the region if any line is already at column zero."
1410 (interactive
1411 (let ((p (point))
1412 (m (mark))
1413 (arg current-prefix-arg))
1414 (if m
1415 (list (min p m) (max p m) arg)
1416 (list p (save-excursion (forward-line 1) (point)) arg))))
1417 ;; if any line is at column zero, don't shift the region
1418 (save-excursion
1419 (goto-char start)
1420 (while (< (point) end)
1421 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001422 (if (and (zerop (current-column))
1423 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001424 (error "Region is at left edge."))
1425 (forward-line 1)))
1426 (py-shift-region start end (- (prefix-numeric-value
1427 (or count py-indent-offset))))
1428 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001429
1430(defun py-shift-region-right (start end &optional count)
1431 "Shift region of Python code to the right.
1432The lines from the line containing the start of the current region up
1433to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001434shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001435
1436If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001437many columns. With no active region, indent only the current line."
1438 (interactive
1439 (let ((p (point))
1440 (m (mark))
1441 (arg current-prefix-arg))
1442 (if m
1443 (list (min p m) (max p m) arg)
1444 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001445 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001446 (or count py-indent-offset)))
1447 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001448
1449(defun py-indent-region (start end &optional indent-offset)
1450 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001451
Barry Warsaw7ae77681994-12-12 20:38:05 +00001452The lines from the line containing the start of the current region up
1453to (but not including) the line containing the end of the region are
1454reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001455character in the first column, the first line is left alone and the
1456rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001457region is reindented with respect to the (closest code or indenting
1458comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459
1460This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001461control structures are introduced or removed, or to reformat code
1462using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001463
1464If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001465the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001466used.
1467
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001468Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001469is called! This function does not compute proper indentation from
1470scratch (that's impossible in Python), it merely adjusts the existing
1471indentation to be correct in context.
1472
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001473Warning: This function really has no idea what to do with
1474non-indenting comment lines, and shifts them as if they were indenting
1475comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001476
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001477Special cases: whitespace is deleted from blank lines; continuation
1478lines are shifted by the same amount their initial line was shifted,
1479in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001481 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001482 (save-excursion
1483 (goto-char end) (beginning-of-line) (setq end (point-marker))
1484 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001485 (let ((py-indent-offset (prefix-numeric-value
1486 (or indent-offset py-indent-offset)))
1487 (indents '(-1)) ; stack of active indent levels
1488 (target-column 0) ; column to which to indent
1489 (base-shifted-by 0) ; amount last base line was shifted
1490 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001491 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492 0))
1493 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001494 (while (< (point) end)
1495 (setq ci (current-indentation))
1496 ;; figure out appropriate target column
1497 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001498 ((or (eq (following-char) ?#) ; comment in column 1
1499 (looking-at "[ \t]*$")) ; entirely blank
1500 (setq target-column 0))
1501 ((py-continuation-line-p) ; shift relative to base line
1502 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001503 (t ; new base line
1504 (if (> ci (car indents)) ; going deeper; push it
1505 (setq indents (cons ci indents))
1506 ;; else we should have seen this indent before
1507 (setq indents (memq ci indents)) ; pop deeper indents
1508 (if (null indents)
1509 (error "Bad indentation in region, at line %d"
1510 (save-restriction
1511 (widen)
1512 (1+ (count-lines 1 (point)))))))
1513 (setq target-column (+ indent-base
1514 (* py-indent-offset
1515 (- (length indents) 2))))
1516 (setq base-shifted-by (- target-column ci))))
1517 ;; shift as needed
1518 (if (/= ci target-column)
1519 (progn
1520 (delete-horizontal-space)
1521 (indent-to target-column)))
1522 (forward-line 1))))
1523 (set-marker end nil))
1524
Barry Warsawa7891711996-08-01 15:53:09 +00001525(defun py-comment-region (beg end &optional arg)
1526 "Like `comment-region' but uses double hash (`#') comment starter."
1527 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001528 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001529 (comment-region beg end arg)))
1530
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531
1532;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533(defun py-previous-statement (count)
1534 "Go to the start of previous Python statement.
1535If the statement at point is the i'th Python statement, goes to the
1536start of statement i-COUNT. If there is no such statement, goes to the
1537first statement. Returns count of statements left to move.
1538`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540 (if (< count 0) (py-next-statement (- count))
1541 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001543 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001544 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545 (> count 0)
1546 (zerop (forward-line -1))
1547 (py-goto-statement-at-or-above))
1548 (setq count (1- count)))
1549 (if (> count 0) (goto-char start)))
1550 count))
1551
1552(defun py-next-statement (count)
1553 "Go to the start of next Python statement.
1554If the statement at point is the i'th Python statement, goes to the
1555start of statement i+COUNT. If there is no such statement, goes to the
1556last statement. Returns count of statements left to move. `Statements'
1557do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001558 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559 (if (< count 0) (py-previous-statement (- count))
1560 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001561 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001562 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001563 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564 (> count 0)
1565 (py-goto-statement-below))
1566 (setq count (1- count)))
1567 (if (> count 0) (goto-char start)))
1568 count))
1569
1570(defun py-goto-block-up (&optional nomark)
1571 "Move up to start of current block.
1572Go to the statement that starts the smallest enclosing block; roughly
1573speaking, this will be the closest preceding statement that ends with a
1574colon and is indented less than the statement you started on. If
1575successful, also sets the mark to the starting point.
1576
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001577`\\[py-mark-block]' can be used afterward to mark the whole code
1578block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001579
1580If called from a program, the mark will not be set if optional argument
1581NOMARK is not nil."
1582 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001583 (let ((start (point))
1584 (found nil)
1585 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586 (py-goto-initial-line)
1587 ;; if on blank or non-indenting comment line, use the preceding stmt
1588 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1589 (progn
1590 (py-goto-statement-at-or-above)
1591 (setq found (py-statement-opens-block-p))))
1592 ;; search back for colon line indented less
1593 (setq initial-indent (current-indentation))
1594 (if (zerop initial-indent)
1595 ;; force fast exit
1596 (goto-char (point-min)))
1597 (while (not (or found (bobp)))
1598 (setq found
1599 (and
1600 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1601 (or (py-goto-initial-line) t) ; always true -- side effect
1602 (< (current-indentation) initial-indent)
1603 (py-statement-opens-block-p))))
1604 (if found
1605 (progn
1606 (or nomark (push-mark start))
1607 (back-to-indentation))
1608 (goto-char start)
1609 (error "Enclosing block not found"))))
1610
1611(defun beginning-of-python-def-or-class (&optional class)
1612 "Move point to start of def (or class, with prefix arg).
1613
1614Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001615arg, looks for a `class' instead. The docs assume the `def' case;
1616just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001617
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001618If point is in a def statement already, and after the `d', simply
1619moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001620
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001621Else (point is not in a def statement, or at or before the `d' of a
1622def statement), searches for the closest preceding def statement, and
1623leaves point at its start. If no such statement can be found, leaves
1624point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001625
1626Returns t iff a def statement is found by these rules.
1627
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628Note that doing this command repeatedly will take you closer to the
1629start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001630
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001631If you want to mark the current def/class, see
1632`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001633 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001634 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1635 (start-of-line (progn (beginning-of-line) (point)))
1636 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637 (if (or (/= start-of-stmt start-of-line)
1638 (not at-or-before-p))
1639 (end-of-line)) ; OK to match on this line
1640 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001641 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001642
1643(defun end-of-python-def-or-class (&optional class)
1644 "Move point beyond end of def (or class, with prefix arg) body.
1645
1646By default, looks for an appropriate `def'. If you supply a prefix arg,
1647looks for a `class' instead. The docs assume the `def' case; just
1648substitute `class' for `def' for the other case.
1649
1650If point is in a def statement already, this is the def we use.
1651
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001652Else if the def found by `\\[beginning-of-python-def-or-class]'
1653contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654
1655Else we search forward for the closest following def, and use that.
1656
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001657If a def can be found by these rules, point is moved to the start of
1658the line immediately following the def block, and the position of the
1659start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660
1661Else point is moved to the end of the buffer, and nil is returned.
1662
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001663Note that doing this command repeatedly will take you closer to the
1664end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001665
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666If you want to mark the current def/class, see
1667`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001668 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669 (let ((start (progn (py-goto-initial-line) (point)))
1670 (which (if class "class" "def"))
1671 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001672 ;; move point to start of appropriate def/class
1673 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1674 (setq state 'at-beginning)
1675 ;; else see if beginning-of-python-def-or-class hits container
1676 (if (and (beginning-of-python-def-or-class class)
1677 (progn (py-goto-beyond-block)
1678 (> (point) start)))
1679 (setq state 'at-end)
1680 ;; else search forward
1681 (goto-char start)
1682 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1683 (progn (setq state 'at-beginning)
1684 (beginning-of-line)))))
1685 (cond
1686 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1687 ((eq state 'at-end) t)
1688 ((eq state 'not-found) nil)
1689 (t (error "internal error in end-of-python-def-or-class")))))
1690
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001691
1692;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001693(defun py-mark-block (&optional extend just-move)
1694 "Mark following block of lines. With prefix arg, mark structure.
1695Easier to use than explain. It sets the region to an `interesting'
1696block of succeeding lines. If point is on a blank line, it goes down to
1697the next non-blank line. That will be the start of the region. The end
1698of the region depends on the kind of line at the start:
1699
1700 - If a comment, the region will include all succeeding comment lines up
1701 to (but not including) the next non-comment line (if any).
1702
1703 - Else if a prefix arg is given, and the line begins one of these
1704 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001705
1706 if elif else try except finally for while def class
1707
Barry Warsaw7ae77681994-12-12 20:38:05 +00001708 the region will be set to the body of the structure, including
1709 following blocks that `belong' to it, but excluding trailing blank
1710 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001711 and all (if any) of the following `except' and `finally' blocks
1712 that belong to the `try' structure will be in the region. Ditto
1713 for if/elif/else, for/else and while/else structures, and (a bit
1714 degenerate, since they're always one-block structures) def and
1715 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001716
1717 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001718 block (see list above), and the block is not a `one-liner' (i.e.,
1719 the statement ends with a colon, not with code), the region will
1720 include all succeeding lines up to (but not including) the next
1721 code statement (if any) that's indented no more than the starting
1722 line, except that trailing blank and comment lines are excluded.
1723 E.g., if the starting line begins a multi-statement `def'
1724 structure, the region will be set to the full function definition,
1725 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001726
1727 - Else the region will include all succeeding lines up to (but not
1728 including) the next blank line, or code or indenting-comment line
1729 indented strictly less than the starting line. Trailing indenting
1730 comment lines are included in this case, but not trailing blank
1731 lines.
1732
1733A msg identifying the location of the mark is displayed in the echo
1734area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1735
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001736If called from a program, optional argument EXTEND plays the role of
1737the prefix arg, and if optional argument JUST-MOVE is not nil, just
1738moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739 (interactive "P") ; raw prefix arg
1740 (py-goto-initial-line)
1741 ;; skip over blank lines
1742 (while (and
1743 (looking-at "[ \t]*$") ; while blank line
1744 (not (eobp))) ; & somewhere to go
1745 (forward-line 1))
1746 (if (eobp)
1747 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001748 (let ((initial-pos (point))
1749 (initial-indent (current-indentation))
1750 last-pos ; position of last stmt in region
1751 (followers
1752 '((if elif else) (elif elif else) (else)
1753 (try except finally) (except except) (finally)
1754 (for else) (while else)
1755 (def) (class) ) )
1756 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757
1758 (cond
1759 ;; if comment line, suck up the following comment lines
1760 ((looking-at "[ \t]*#")
1761 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1762 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1763 (setq last-pos (point)))
1764
1765 ;; else if line is a block line and EXTEND given, suck up
1766 ;; the whole structure
1767 ((and extend
1768 (setq first-symbol (py-suck-up-first-keyword) )
1769 (assq first-symbol followers))
1770 (while (and
1771 (or (py-goto-beyond-block) t) ; side effect
1772 (forward-line -1) ; side effect
1773 (setq last-pos (point)) ; side effect
1774 (py-goto-statement-below)
1775 (= (current-indentation) initial-indent)
1776 (setq next-symbol (py-suck-up-first-keyword))
1777 (memq next-symbol (cdr (assq first-symbol followers))))
1778 (setq first-symbol next-symbol)))
1779
1780 ;; else if line *opens* a block, search for next stmt indented <=
1781 ((py-statement-opens-block-p)
1782 (while (and
1783 (setq last-pos (point)) ; always true -- side effect
1784 (py-goto-statement-below)
1785 (> (current-indentation) initial-indent))
1786 nil))
1787
1788 ;; else plain code line; stop at next blank line, or stmt or
1789 ;; indenting comment line indented <
1790 (t
1791 (while (and
1792 (setq last-pos (point)) ; always true -- side effect
1793 (or (py-goto-beyond-final-line) t)
1794 (not (looking-at "[ \t]*$")) ; stop at blank line
1795 (or
1796 (>= (current-indentation) initial-indent)
1797 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1798 nil)))
1799
1800 ;; skip to end of last stmt
1801 (goto-char last-pos)
1802 (py-goto-beyond-final-line)
1803
1804 ;; set mark & display
1805 (if just-move
1806 () ; just return
1807 (push-mark (point) 'no-msg)
1808 (forward-line -1)
1809 (message "Mark set after: %s" (py-suck-up-leading-text))
1810 (goto-char initial-pos))))
1811
1812(defun mark-python-def-or-class (&optional class)
1813 "Set region to body of def (or class, with prefix arg) enclosing point.
1814Pushes the current mark, then point, on the mark ring (all language
1815modes do this, but although it's handy it's never documented ...).
1816
1817In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001818hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1819`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820
1821And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001822Turned out that was more confusing than useful: the `goto start' and
1823`goto end' commands are usually used to search through a file, and
1824people expect them to act a lot like `search backward' and `search
1825forward' string-search commands. But because Python `def' and `class'
1826can nest to arbitrary levels, finding the smallest def containing
1827point cannot be done via a simple backward search: the def containing
1828point may not be the closest preceding def, or even the closest
1829preceding def that's indented less. The fancy algorithm required is
1830appropriate for the usual uses of this `mark' command, but not for the
1831`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833So the def marked by this command may not be the one either of the
1834`goto' commands find: If point is on a blank or non-indenting comment
1835line, moves back to start of the closest preceding code statement or
1836indenting comment line. If this is a `def' statement, that's the def
1837we use. Else searches for the smallest enclosing `def' block and uses
1838that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840When an enclosing def is found: The mark is left immediately beyond
1841the last line of the def block. Point is left at the start of the
1842def, except that: if the def is preceded by a number of comment lines
1843followed by (at most) one optional blank line, point is left at the
1844start of the comments; else if the def is preceded by a blank line,
1845point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846
1847The intent is to mark the containing def/class and its associated
1848documentation, to make moving and duplicating functions and classes
1849pleasant."
1850 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001851 (let ((start (point))
1852 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853 (push-mark start)
1854 (if (not (py-go-up-tree-to-keyword which))
1855 (progn (goto-char start)
1856 (error "Enclosing %s not found" which))
1857 ;; else enclosing def/class found
1858 (setq start (point))
1859 (py-goto-beyond-block)
1860 (push-mark (point))
1861 (goto-char start)
1862 (if (zerop (forward-line -1)) ; if there is a preceding line
1863 (progn
1864 (if (looking-at "[ \t]*$") ; it's blank
1865 (setq start (point)) ; so reset start point
1866 (goto-char start)) ; else try again
1867 (if (zerop (forward-line -1))
1868 (if (looking-at "[ \t]*#") ; a comment
1869 ;; look back for non-comment line
1870 ;; tricky: note that the regexp matches a blank
1871 ;; line, cuz \n is in the 2nd character class
1872 (and
1873 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1874 (forward-line 1))
1875 ;; no comment, so go back
1876 (goto-char start))))))))
1877
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001878;; ripped from cc-mode
1879(defun py-forward-into-nomenclature (&optional arg)
1880 "Move forward to end of a nomenclature section or word.
1881With arg, to it arg times.
1882
1883A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1884 (interactive "p")
1885 (let ((case-fold-search nil))
1886 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001887 (re-search-forward
1888 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1889 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001890 (while (and (< arg 0)
1891 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001892 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001893 (point-min) 0))
1894 (forward-char 1)
1895 (setq arg (1+ arg)))))
1896 (py-keep-region-active))
1897
1898(defun py-backward-into-nomenclature (&optional arg)
1899 "Move backward to beginning of a nomenclature section or word.
1900With optional ARG, move that many times. If ARG is negative, move
1901forward.
1902
1903A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1904 (interactive "p")
1905 (py-forward-into-nomenclature (- arg))
1906 (py-keep-region-active))
1907
1908
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001909
1910;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001911
1912;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001913;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1914;; out of the right places, along with the keys they're on & current
1915;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001916(defun py-dump-help-string (str)
1917 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918 (let ((locals (buffer-local-variables))
1919 funckind funcname func funcdoc
1920 (start 0) mstart end
1921 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1923 (setq mstart (match-beginning 0) end (match-end 0)
1924 funckind (substring str (match-beginning 1) (match-end 1))
1925 funcname (substring str (match-beginning 2) (match-end 2))
1926 func (intern funcname))
1927 (princ (substitute-command-keys (substring str start mstart)))
1928 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929 ((equal funckind "c") ; command
1930 (setq funcdoc (documentation func)
1931 keys (concat
1932 "Key(s): "
1933 (mapconcat 'key-description
1934 (where-is-internal func py-mode-map)
1935 ", "))))
1936 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001937 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938 keys (if (assq func locals)
1939 (concat
1940 "Local/Global values: "
1941 (prin1-to-string (symbol-value func))
1942 " / "
1943 (prin1-to-string (default-value func)))
1944 (concat
1945 "Value: "
1946 (prin1-to-string (symbol-value func))))))
1947 (t ; unexpected
1948 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949 (princ (format "\n-> %s:\t%s\t%s\n\n"
1950 (if (equal funckind "c") "Command" "Variable")
1951 funcname keys))
1952 (princ funcdoc)
1953 (terpri)
1954 (setq start end))
1955 (princ (substitute-command-keys (substring str start))))
1956 (print-help-return-message)))
1957
1958(defun py-describe-mode ()
1959 "Dump long form of Python-mode docs."
1960 (interactive)
1961 (py-dump-help-string "Major mode for editing Python files.
1962Knows about Python indentation, tokens, comments and continuation lines.
1963Paragraphs are separated by blank lines only.
1964
1965Major sections below begin with the string `@'; specific function and
1966variable docs begin with `->'.
1967
1968@EXECUTING PYTHON CODE
1969
1970\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1971\\[py-execute-region]\tsends the current region
1972\\[py-shell]\tstarts a Python interpreter window; this will be used by
1973\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1974%c:py-execute-buffer
1975%c:py-execute-region
1976%c:py-shell
1977
1978@VARIABLES
1979
1980py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001981py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001982
1983py-python-command\tshell command to invoke Python interpreter
1984py-scroll-process-buffer\talways scroll Python process buffer
1985py-temp-directory\tdirectory used for temp files (if needed)
1986
1987py-beep-if-tab-change\tring the bell if tab-width is changed
1988%v:py-indent-offset
1989%v:py-block-comment-prefix
1990%v:py-python-command
1991%v:py-scroll-process-buffer
1992%v:py-temp-directory
1993%v:py-beep-if-tab-change
1994
1995@KINDS OF LINES
1996
1997Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001998preceding line ends with a backslash that's not part of a comment, or
1999the paren/bracket/brace nesting level at the start of the line is
2000non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001
2002An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002003possibly blanks or tabs), a `comment line' (leftmost non-blank
2004character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002005
2006Comment Lines
2007
2008Although all comment lines are treated alike by Python, Python mode
2009recognizes two kinds that act differently with respect to indentation.
2010
2011An `indenting comment line' is a comment line with a blank, tab or
2012nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002014indenting comment line will be indented like the comment line. All
2015other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002016following the initial `#') are `non-indenting comment lines', and
2017their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002018
2019Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020whenever possible. Non-indenting comment lines are useful in cases
2021like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022
2023\ta = b # a very wordy single-line comment that ends up being
2024\t #... continued onto another line
2025
2026\tif a == b:
2027##\t\tprint 'panic!' # old code we've `commented out'
2028\t\treturn a
2029
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030Since the `#...' and `##' comment lines have a non-whitespace
2031character following the initial `#', Python mode ignores them when
2032computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002033
2034Continuation Lines and Statements
2035
2036The Python-mode commands generally work on statements instead of on
2037individual lines, where a `statement' is a comment or blank line, or a
2038code line and all of its following continuation lines (if any)
2039considered as a single logical unit. The commands in this mode
2040generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002041statement containing point, even if point happens to be in the middle
2042of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002043
2044
2045@INDENTATION
2046
2047Primarily for entering new code:
2048\t\\[indent-for-tab-command]\t indent line appropriately
2049\t\\[py-newline-and-indent]\t insert newline, then indent
2050\t\\[py-delete-char]\t reduce indentation, or delete single character
2051
2052Primarily for reindenting existing code:
2053\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2054\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2055
2056\t\\[py-indent-region]\t reindent region to match its context
2057\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2058\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2059
2060Unlike most programming languages, Python uses indentation, and only
2061indentation, to specify block structure. Hence the indentation supplied
2062automatically by Python-mode is just an educated guess: only you know
2063the block structure you intend, so only you can supply correct
2064indentation.
2065
2066The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2067the indentation of preceding statements. E.g., assuming
2068py-indent-offset is 4, after you enter
2069\tif a > 0: \\[py-newline-and-indent]
2070the cursor will be moved to the position of the `_' (_ is not a
2071character in the file, it's just used here to indicate the location of
2072the cursor):
2073\tif a > 0:
2074\t _
2075If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2076to
2077\tif a > 0:
2078\t c = d
2079\t _
2080Python-mode cannot know whether that's what you intended, or whether
2081\tif a > 0:
2082\t c = d
2083\t_
2084was your intent. In general, Python-mode either reproduces the
2085indentation of the (closest code or indenting-comment) preceding
2086statement, or adds an extra py-indent-offset blanks if the preceding
2087statement has `:' as its last significant (non-whitespace and non-
2088comment) character. If the suggested indentation is too much, use
2089\\[py-delete-char] to reduce it.
2090
2091Continuation lines are given extra indentation. If you don't like the
2092suggested indentation, change it to something you do like, and Python-
2093mode will strive to indent later lines of the statement in the same way.
2094
2095If a line is a continuation line by virtue of being in an unclosed
2096paren/bracket/brace structure (`list', for short), the suggested
2097indentation depends on whether the current line contains the first item
2098in the list. If it does, it's indented py-indent-offset columns beyond
2099the indentation of the line containing the open bracket. If you don't
2100like that, change it by hand. The remaining items in the list will mimic
2101whatever indentation you give to the first item.
2102
2103If a line is a continuation line because the line preceding it ends with
2104a backslash, the third and following lines of the statement inherit their
2105indentation from the line preceding them. The indentation of the second
2106line in the statement depends on the form of the first (base) line: if
2107the base line is an assignment statement with anything more interesting
2108than the backslash following the leftmost assigning `=', the second line
2109is indented two columns beyond that `='. Else it's indented to two
2110columns beyond the leftmost solid chunk of non-whitespace characters on
2111the base line.
2112
2113Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2114repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2115structure you intend.
2116%c:indent-for-tab-command
2117%c:py-newline-and-indent
2118%c:py-delete-char
2119
2120
2121The next function may be handy when editing code you didn't write:
2122%c:py-guess-indent-offset
2123
2124
2125The remaining `indent' functions apply to a region of Python code. They
2126assume the block structure (equals indentation, in Python) of the region
2127is correct, and alter the indentation in various ways while preserving
2128the block structure:
2129%c:py-indent-region
2130%c:py-shift-region-left
2131%c:py-shift-region-right
2132
2133@MARKING & MANIPULATING REGIONS OF CODE
2134
2135\\[py-mark-block]\t mark block of lines
2136\\[mark-python-def-or-class]\t mark smallest enclosing def
2137\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002138\\[comment-region]\t comment out region of code
2139\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002140%c:py-mark-block
2141%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002142%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002143
2144@MOVING POINT
2145
2146\\[py-previous-statement]\t move to statement preceding point
2147\\[py-next-statement]\t move to statement following point
2148\\[py-goto-block-up]\t move up to start of current block
2149\\[beginning-of-python-def-or-class]\t move to start of def
2150\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2151\\[end-of-python-def-or-class]\t move to end of def
2152\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2153
2154The first two move to one statement beyond the statement that contains
2155point. A numeric prefix argument tells them to move that many
2156statements instead. Blank lines, comment lines, and continuation lines
2157do not count as `statements' for these commands. So, e.g., you can go
2158to the first code statement in a file by entering
2159\t\\[beginning-of-buffer]\t to move to the top of the file
2160\t\\[py-next-statement]\t to skip over initial comments and blank lines
2161Or do `\\[py-previous-statement]' with a huge prefix argument.
2162%c:py-previous-statement
2163%c:py-next-statement
2164%c:py-goto-block-up
2165%c:beginning-of-python-def-or-class
2166%c:end-of-python-def-or-class
2167
2168@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2169
2170`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2171
2172`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2173overall class and def structure of a module.
2174
2175`\\[back-to-indentation]' moves point to a line's first non-blank character.
2176
2177`\\[indent-relative]' is handy for creating odd indentation.
2178
2179@OTHER EMACS HINTS
2180
2181If you don't like the default value of a variable, change its value to
2182whatever you do like by putting a `setq' line in your .emacs file.
2183E.g., to set the indentation increment to 4, put this line in your
2184.emacs:
2185\t(setq py-indent-offset 4)
2186To see the value of a variable, do `\\[describe-variable]' and enter the variable
2187name at the prompt.
2188
2189When entering a key sequence like `C-c C-n', it is not necessary to
2190release the CONTROL key after doing the `C-c' part -- it suffices to
2191press the CONTROL key, press and release `c' (while still holding down
2192CONTROL), press and release `n' (while still holding down CONTROL), &
2193then release CONTROL.
2194
2195Entering Python mode calls with no arguments the value of the variable
2196`python-mode-hook', if that value exists and is not nil; for backward
2197compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2198the Elisp manual for details.
2199
2200Obscure: When python-mode is first loaded, it looks for all bindings
2201to newline-and-indent in the global keymap, and shadows them with
2202local bindings to py-newline-and-indent."))
2203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204
2205;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002206(defvar py-parse-state-re
2207 (concat
2208 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2209 "\\|"
2210 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002211
Barry Warsaw7ae77681994-12-12 20:38:05 +00002212;; returns the parse state at point (see parse-partial-sexp docs)
2213(defun py-parse-state ()
2214 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002215 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002216 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002217 (while (not done)
2218 ;; back up to the first preceding line (if any; else start of
2219 ;; buffer) that begins with a popular Python keyword, or a
2220 ;; non- whitespace and non-comment character. These are good
2221 ;; places to start parsing to see whether where we started is
2222 ;; at a non-zero nesting level. It may be slow for people who
2223 ;; write huge code blocks or huge lists ... tough beans.
2224 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002225 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002226 (beginning-of-line)
2227 (save-excursion
2228 (setq pps (parse-partial-sexp (point) here)))
2229 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002230 (setq done (or (zerop ci)
2231 (not (nth 3 pps))
2232 (bobp)))
2233 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002234 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002235
2236;; if point is at a non-zero nesting level, returns the number of the
2237;; character that opens the smallest enclosing unclosed list; else
2238;; returns nil.
2239(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002240 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002241 (if (zerop (car status))
2242 nil ; not in a nest
2243 (car (cdr status))))) ; char# of open bracket
2244
2245;; t iff preceding line ends with backslash that's not in a comment
2246(defun py-backslash-continuation-line-p ()
2247 (save-excursion
2248 (beginning-of-line)
2249 (and
2250 ;; use a cheap test first to avoid the regexp if possible
2251 ;; use 'eq' because char-after may return nil
2252 (eq (char-after (- (point) 2)) ?\\ )
2253 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002254 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002255 (looking-at py-continued-re))))
2256
2257;; t iff current line is a continuation line
2258(defun py-continuation-line-p ()
2259 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002260 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002261 (or (py-backslash-continuation-line-p)
2262 (py-nesting-level))))
2263
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002264;; go to initial line of current statement; usually this is the line
2265;; we're on, but if we're on the 2nd or following lines of a
2266;; continuation block, we need to go up to the first line of the
2267;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002268;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002269;; Tricky: We want to avoid quadratic-time behavior for long continued
2270;; blocks, whether of the backslash or open-bracket varieties, or a
2271;; mix of the two. The following manages to do that in the usual
2272;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002273(defun py-goto-initial-line ()
2274 (let ( open-bracket-pos )
2275 (while (py-continuation-line-p)
2276 (beginning-of-line)
2277 (if (py-backslash-continuation-line-p)
2278 (while (py-backslash-continuation-line-p)
2279 (forward-line -1))
2280 ;; else zip out of nested brackets/braces/parens
2281 (while (setq open-bracket-pos (py-nesting-level))
2282 (goto-char open-bracket-pos)))))
2283 (beginning-of-line))
2284
2285;; go to point right beyond final line of current statement; usually
2286;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002287;; statement we need to skip over the continuation lines. Tricky:
2288;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002289(defun py-goto-beyond-final-line ()
2290 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002291 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002292 (while (and (py-continuation-line-p)
2293 (not (eobp)))
2294 ;; skip over the backslash flavor
2295 (while (and (py-backslash-continuation-line-p)
2296 (not (eobp)))
2297 (forward-line 1))
2298 ;; if in nest, zip to the end of the nest
2299 (setq state (py-parse-state))
2300 (if (and (not (zerop (car state)))
2301 (not (eobp)))
2302 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002303 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304 (forward-line 1))))))
2305
2306;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002308(defun py-statement-opens-block-p ()
2309 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002310 (let ((start (point))
2311 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2312 (searching t)
2313 (answer nil)
2314 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002315 (goto-char start)
2316 (while searching
2317 ;; look for a colon with nothing after it except whitespace, and
2318 ;; maybe a comment
2319 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2320 finish t)
2321 (if (eq (point) finish) ; note: no `else' clause; just
2322 ; keep searching if we're not at
2323 ; the end yet
2324 ;; sure looks like it opens a block -- but it might
2325 ;; be in a comment
2326 (progn
2327 (setq searching nil) ; search is done either way
2328 (setq state (parse-partial-sexp start
2329 (match-beginning 0)))
2330 (setq answer (not (nth 4 state)))))
2331 ;; search failed: couldn't find another interesting colon
2332 (setq searching nil)))
2333 answer)))
2334
Barry Warsawf831d811996-07-31 20:42:59 +00002335(defun py-statement-closes-block-p ()
2336 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002337 ;; starts with `return', `raise', `break', `continue', and `pass'.
2338 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002339 (let ((here (point)))
2340 (back-to-indentation)
2341 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002342 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002343 (goto-char here))))
2344
Barry Warsaw7ae77681994-12-12 20:38:05 +00002345;; go to point right beyond final line of block begun by the current
2346;; line. This is the same as where py-goto-beyond-final-line goes
2347;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002348;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002349(defun py-goto-beyond-block ()
2350 (if (py-statement-opens-block-p)
2351 (py-mark-block nil 'just-move)
2352 (py-goto-beyond-final-line)))
2353
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002354;; go to start of first statement (not blank or comment or
2355;; continuation line) at or preceding point. returns t if there is
2356;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002357(defun py-goto-statement-at-or-above ()
2358 (py-goto-initial-line)
2359 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002360 ;; skip back over blank & comment lines
2361 ;; note: will skip a blank or comment line that happens to be
2362 ;; a continuation line too
2363 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2364 (progn (py-goto-initial-line) t)
2365 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002366 t))
2367
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002368;; go to start of first statement (not blank or comment or
2369;; continuation line) following the statement containing point returns
2370;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002371(defun py-goto-statement-below ()
2372 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002373 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002374 (py-goto-beyond-final-line)
2375 (while (and
2376 (looking-at py-blank-or-comment-re)
2377 (not (eobp)))
2378 (forward-line 1))
2379 (if (eobp)
2380 (progn (goto-char start) nil)
2381 t)))
2382
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002383;; go to start of statement, at or preceding point, starting with
2384;; keyword KEY. Skips blank lines and non-indenting comments upward
2385;; first. If that statement starts with KEY, done, else go back to
2386;; first enclosing block starting with KEY. If successful, leaves
2387;; point at the start of the KEY line & returns t. Else leaves point
2388;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002389(defun py-go-up-tree-to-keyword (key)
2390 ;; skip blanks and non-indenting #
2391 (py-goto-initial-line)
2392 (while (and
2393 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2394 (zerop (forward-line -1))) ; go back
2395 nil)
2396 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002397 (let* ((re (concat "[ \t]*" key "\\b"))
2398 (case-fold-search nil) ; let* so looking-at sees this
2399 (found (looking-at re))
2400 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002401 (while (not (or found dead))
2402 (condition-case nil ; in case no enclosing block
2403 (py-goto-block-up 'no-mark)
2404 (error (setq dead t)))
2405 (or dead (setq found (looking-at re))))
2406 (beginning-of-line)
2407 found))
2408
2409;; return string in buffer from start of indentation to end of line;
2410;; prefix "..." if leading whitespace was skipped
2411(defun py-suck-up-leading-text ()
2412 (save-excursion
2413 (back-to-indentation)
2414 (concat
2415 (if (bolp) "" "...")
2416 (buffer-substring (point) (progn (end-of-line) (point))))))
2417
2418;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2419;; as a Lisp symbol; return nil if none
2420(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002421 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002422 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2423 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2424 nil)))
2425
Barry Warsaw7ae77681994-12-12 20:38:05 +00002426(defun py-delete-file-silently (fname)
2427 (condition-case nil
2428 (delete-file fname)
2429 (error nil)))
2430
2431(defun py-kill-emacs-hook ()
2432 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002433 (py-safe (while py-file-queue
2434 (py-delete-file-silently (car py-file-queue))
2435 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002436
Barry Warsawb3e81d51996-09-04 15:12:42 +00002437(defun py-current-defun ()
2438 ;; tell add-log.el how to find the current function/method/variable
2439 (save-excursion
2440 (if (re-search-backward py-defun-start-re nil t)
2441 (or (match-string 3)
2442 (let ((method (match-string 2)))
2443 (if (and (not (zerop (length (match-string 1))))
2444 (re-search-backward py-class-start-re nil t))
2445 (concat (match-string 1) "." method)
2446 method)))
2447 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002448
2449
Barry Warsawfec75d61995-07-05 23:26:15 +00002450(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002451 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002452
Barry Warsaw850437a1995-03-08 21:50:28 +00002453(defun py-version ()
2454 "Echo the current version of `python-mode' in the minibuffer."
2455 (interactive)
2456 (message "Using `python-mode' version %s" py-version)
2457 (py-keep-region-active))
2458
2459;; only works under Emacs 19
2460;(eval-when-compile
2461; (require 'reporter))
2462
2463(defun py-submit-bug-report (enhancement-p)
2464 "Submit via mail a bug report on `python-mode'.
2465With \\[universal-argument] just submit an enhancement request."
2466 (interactive
2467 (list (not (y-or-n-p
2468 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002469 (let ((reporter-prompt-for-summary-p (if enhancement-p
2470 "(Very) brief summary: "
2471 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002472 (require 'reporter)
2473 (reporter-submit-bug-report
2474 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002475 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002476 ;; varlist
2477 (if enhancement-p nil
2478 '(py-python-command
2479 py-indent-offset
2480 py-block-comment-prefix
2481 py-scroll-process-buffer
2482 py-temp-directory
2483 py-beep-if-tab-change))
2484 nil ;pre-hooks
2485 nil ;post-hooks
2486 "Dear Barry,") ;salutation
2487 (if enhancement-p nil
2488 (set-mark (point))
2489 (insert
2490"Please replace this text with a sufficiently large code sample\n\
2491and an exact recipe so that I can reproduce your problem. Failure\n\
2492to do so may mean a greater delay in fixing your bug.\n\n")
2493 (exchange-point-and-mark)
2494 (py-keep-region-active))))
2495
2496
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002497;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002498(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002499
2500
2501
2502(provide 'python-mode)
2503;;; python-mode.el ends here