blob: 20fc4cf8462ed896b2a139c1a656dfd24ca05475 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5e21cb01997-11-05 18:41:11 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsawaffc0ca1997-11-03 16:59:38 +000027;; Note: this version of python-mode.el is no longer compatible with
28;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
29;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
30;; you may need to acquire the Custom library.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
Barry Warsawaffc0ca1997-11-03 16:59:38 +000032;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
33;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000034;; but it is compatible with 19.34 and the current 20 series Emacsen.
35;; By default, in XEmacs when you visit a .py file, it is put in
36;; Python mode. In Emacs, you need to add the following to your
37;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000039;; (autoload 'python-mode "python-mode" "Python editing mode." t)
40;; (setq auto-mode-alist
41;; (cons '("\\.py$" . python-mode) auto-mode-alist))
42;; (setq interpreter-mode-alist
43;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000044;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000045;; Assuming python-mode.el is on your load-path, it will be invoked
46;; when you visit a .py file, or a file with a first line that looks
47;; like:
48;;
49;; #! /usr/bin/env python
50
Barry Warsaw44b72201996-07-05 20:11:35 +000051;; If you want font-lock support for Python source code (a.k.a. syntax
52;; coloring, highlighting), add this to your .emacs file:
53;;
54;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000055;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000056;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000057
Barry Warsawaffc0ca1997-11-03 16:59:38 +000058;; To submit bug reports, use C-c C-b. Please include a complete, but
59;; concise code sample and a recipe for reproducing the bug. Send
60;; suggestions and other comments to python-mode@python.org.
61
62;; When in a Python mode buffer, do a C-h m for more help. It's
63;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; Here's a brief to do list:
66;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000067;; - Better integration with gud-mode for debugging.
68;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000069;; - possibly force indent-tabs-mode == nil, and add a
70;; write-file-hooks that runs untabify on the whole buffer (to work
71;; around potential tab/space mismatch problems). In practice this
72;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000073;; - have py-execute-region on indented code act as if the region is
74;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000075;; - Add a py-goto-error or some such that would scan an exception in
76;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsaw7b0f5681995-03-08 21:33:04 +000078;;; Code:
79
Barry Warsawc72c11c1997-08-09 06:42:08 +000080(require 'custom)
81
Barry Warsaw7b0f5681995-03-08 21:33:04 +000082
83;; user definable variables
84;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000085
Barry Warsawc72c11c1997-08-09 06:42:08 +000086(defgroup python nil
87 "Support for the Python programming language, <http://www.python.org/>"
88 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000089
Barry Warsawc72c11c1997-08-09 06:42:08 +000090(defcustom py-python-command "python"
91 "*Shell command used to start Python interpreter."
92 :type 'string
93 :group 'python)
94
95(defcustom py-indent-offset 4
96 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +000098when you're editing someone else's Python code."
99 :type 'integer
100 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000101
Barry Warsawc72c11c1997-08-09 06:42:08 +0000102(defcustom py-align-multiline-strings-p t
103 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000104When this flag is non-nil, continuation lines are lined up under the
105preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000106lines are aligned to column zero."
107 :type '(choice (const :tag "Align under preceding line" t)
108 (const :tag "Align to column zero" nil))
109 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000110
Barry Warsawc72c11c1997-08-09 06:42:08 +0000111(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000112 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000113This should follow the convention for non-indenting comment lines so
114that the indentation commands won't get confused (i.e., the string
115should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000116`...' is arbitrary)."
117 :type 'string
118 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000119
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000121 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000122
Barry Warsaw6d627751996-03-06 18:41:38 +0000123When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000125
126When t, lines that begin with a single `#' are a hint to subsequent
127line indentation. If the previous line is such a comment line (as
128opposed to one that starts with `py-block-comment-prefix'), then it's
129indentation is used as a hint for this line's indentation. Lines that
130begin with `py-block-comment-prefix' are ignored for indentation
131purposes.
132
133When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000134indentation hints, unless the comment character is in column zero."
135 :type '(choice
136 (const :tag "Skip all comment lines (fast)" nil)
137 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000138 (const :tag "Single # `sets' indentation except at column zero"
139 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140 )
141 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000142
Barry Warsawc72c11c1997-08-09 06:42:08 +0000143(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000144 "*Scroll Python process buffer as output arrives.
145If nil, the Python process buffer acts, with respect to scrolling, like
146Shell-mode buffers normally act. This is surprisingly complicated and
147so won't be explained here; in fact, you can't get the whole story
148without studying the Emacs C code.
149
150If non-nil, the behavior is different in two respects (which are
151slightly inaccurate in the interest of brevity):
152
153 - If the buffer is in a window, and you left point at its end, the
154 window will scroll as new output arrives, and point will move to the
155 buffer's end, even if the window is not the selected window (that
156 being the one the cursor is in). The usual behavior for shell-mode
157 windows is not to scroll, and to leave point where it was, if the
158 buffer is in a window other than the selected window.
159
160 - If the buffer is not visible in any window, and you left point at
161 its end, the buffer will be popped into a window as soon as more
162 output arrives. This is handy if you have a long-running
163 computation and don't want to tie up screen area waiting for the
164 output. The usual behavior for a shell-mode buffer is to stay
165 invisible until you explicitly visit it.
166
167Note the `and if you left point at its end' clauses in both of the
168above: you can `turn off' the special behaviors while output is in
169progress, by visiting the Python buffer and moving point to anywhere
170besides the end. Then the buffer won't scroll, point will remain where
171you leave it, and if you hide the buffer it will stay hidden until you
172visit it again. You can enable and disable the special behaviors as
173often as you like, while output is in progress, by (respectively) moving
174point to, or away from, the end of the buffer.
175
176Warning: If you expect a large amount of output, you'll probably be
177happier setting this option to nil.
178
179Obscure: `End of buffer' above should really say `at or beyond the
180process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000181told <grin>."
182 :type 'boolean
183 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000184
Barry Warsaw516b6201997-08-09 06:43:20 +0000185(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000186 (let ((ok '(lambda (x)
187 (and x
188 (setq x (expand-file-name x)) ; always true
189 (file-directory-p x)
190 (file-writable-p x)
191 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000192 (or (funcall ok (getenv "TMPDIR"))
193 (funcall ok "/usr/tmp")
194 (funcall ok "/tmp")
195 (funcall ok ".")
196 (error
197 "Couldn't find a usable temp directory -- set py-temp-directory")))
198 "*Directory used for temp files created by a *Python* process.
199By default, the first directory from this list that exists and that you
200can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201/usr/tmp, /tmp, or the current directory."
202 :type 'string
203 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000204
Barry Warsaw516b6201997-08-09 06:43:20 +0000205(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000206 "*Ring the bell if tab-width is changed.
207If a comment of the form
208
209 \t# vi:set tabsize=<number>:
210
211is found before the first code line when the file is entered, and the
212current value of (the general Emacs variable) `tab-width' does not
213equal <number>, `tab-width' is set to <number>, a message saying so is
214displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000215the Emacs bell is also rung as a warning."
216 :type 'boolean
217 :group 'python)
218
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000219(defcustom py-backspace-function 'backward-delete-char-untabify
220 "*Function called by `py-electric-backspace' when deleting backwards."
221 :type 'function
222 :group 'python)
223
224(defcustom py-delete-function 'delete-char
225 "*Function called by `py-electric-delete' when deleting forwards."
226 :type 'function
227 :group 'python)
228
229
Barry Warsawc72c11c1997-08-09 06:42:08 +0000230
231;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
232;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
233
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000234(defconst py-emacs-features
235 (let (features)
236 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
237 ;; the same string.
238 (let ((tmp1 (make-temp-name ""))
239 (tmp2 (make-temp-name "")))
240 (if (string-equal tmp1 tmp2)
241 (push 'broken-temp-names features)))
242 ;; return the features
243 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000244 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000245There are many flavors of Emacs out there, with different levels of
246support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000247
Barry Warsawfb07f401997-02-24 03:37:22 +0000248(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000249 (let ((kw1 (mapconcat 'identity
250 '("and" "assert" "break" "class"
251 "continue" "def" "del" "elif"
252 "else" "except" "exec" "for"
253 "from" "global" "if" "import"
254 "in" "is" "lambda" "not"
255 "or" "pass" "print" "raise"
256 "return" "while"
257 )
258 "\\|"))
259 (kw2 (mapconcat 'identity
260 '("else:" "except:" "finally:" "try:")
261 "\\|"))
262 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000263 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000264 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000265 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
266 ;; block introducing keywords with immediately following colons.
267 ;; Yes "except" is in both lists.
268 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000269 ;; classes
270 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
271 1 font-lock-type-face)
272 ;; functions
273 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
274 1 font-lock-function-name-face)
275 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000276 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000277(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
278
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000279
Barry Warsaw81437461996-08-01 19:48:02 +0000280(defvar imenu-example--python-show-method-args-p nil
281 "*Controls echoing of arguments of functions & methods in the imenu buffer.
282When non-nil, arguments are printed.")
283
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000284(make-variable-buffer-local 'py-indent-offset)
285
Barry Warsaw7ae77681994-12-12 20:38:05 +0000286;; have to bind py-file-queue before installing the kill-emacs hook
287(defvar py-file-queue nil
288 "Queue of Python temp files awaiting execution.
289Currently-active file is at the head of the list.")
290
Barry Warsawc72c11c1997-08-09 06:42:08 +0000291
292;; Constants
293
294;; Regexp matching a Python string literal
295(defconst py-stringlit-re
296 (concat
297 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
298 "\\|" ; or
299 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
300
301;; Regexp matching Python lines that are continued via backslash.
302;; This is tricky because a trailing backslash does not mean
303;; continuation if it's in a comment
304(defconst py-continued-re
305 (concat
306 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
307 "\\\\$"))
308
309;; Regexp matching blank or comment lines.
310(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
311
312;; Regexp matching clauses to be outdented one level.
313(defconst py-outdent-re
314 (concat "\\(" (mapconcat 'identity
315 '("else:"
316 "except\\(\\s +.*\\)?:"
317 "finally:"
318 "elif\\s +.*:")
319 "\\|")
320 "\\)"))
321
322
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000323;; Regexp matching keywords which typically close a block
324(defconst py-block-closing-keywords-re
325 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
326
Barry Warsawc72c11c1997-08-09 06:42:08 +0000327;; Regexp matching lines to not outdent after.
328(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000329 (concat
330 "\\("
331 (mapconcat 'identity
332 (list "try:"
333 "except\\(\\s +.*\\)?:"
334 "while\\s +.*:"
335 "for\\s +.*:"
336 "if\\s +.*:"
337 "elif\\s +.*:"
338 (concat py-block-closing-keywords-re "[ \t\n]")
339 )
340 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000341 "\\)"))
342
343;; Regexp matching a function, method or variable assignment. If you
344;; change this, you probably have to change `py-current-defun' as
345;; well. This is only used by `py-current-defun' to find the name for
346;; add-log.el.
347(defvar py-defun-start-re
348 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
349
350;; Regexp for finding a class name. If you change this, you probably
351;; have to change `py-current-defun' as well. This is only used by
352;; `py-current-defun' to find the name for add-log.el.
353(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
354
355
356
357;; Utilities
358
359(defmacro py-safe (&rest body)
360 ;; safely execute BODY, return nil if an error occurred
361 (` (condition-case nil
362 (progn (,@ body))
363 (error nil))))
364
365(defsubst py-keep-region-active ()
366 ;; Do whatever is necessary to keep the region active in XEmacs.
367 ;; Ignore byte-compiler warnings you might see. Also note that
368 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
369 ;; to take explicit action.
370 (and (boundp 'zmacs-region-stays)
371 (setq zmacs-region-stays t)))
372
373
374;; Major mode boilerplate
375
Barry Warsaw7ae77681994-12-12 20:38:05 +0000376;; define a mode-specific abbrev table for those who use such things
377(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000379(define-abbrev-table 'python-mode-abbrev-table nil)
380
Barry Warsaw7ae77681994-12-12 20:38:05 +0000381(defvar python-mode-hook nil
382 "*Hook called by `python-mode'.")
383
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000384;; in previous version of python-mode.el, the hook was incorrectly
385;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386(and (fboundp 'make-obsolete-variable)
387 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
388
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000389(defvar py-mode-map ()
390 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000391(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000392 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000393 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000394 ;; electric keys
395 (define-key py-mode-map ":" 'py-electric-colon)
396 ;; indentation level modifiers
397 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
398 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
399 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
400 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
401 ;; subprocess commands
402 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
403 (define-key py-mode-map "\C-c|" 'py-execute-region)
404 (define-key py-mode-map "\C-c!" 'py-shell)
405 ;; Caution! Enter here at your own risk. We are trying to support
406 ;; several behaviors and it gets disgusting. :-( This logic ripped
407 ;; largely from CC Mode.
408 ;;
409 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
410 ;; backwards deletion behavior to DEL, which both Delete and
411 ;; Backspace get translated to. There's no way to separate this
412 ;; behavior in a clean way, so deal with it! Besides, it's been
413 ;; this way since the dawn of time.
414 (if (not (boundp 'delete-key-deletes-forward))
415 (define-key py-mode-map "\177" 'py-electric-backspace)
416 ;; However, XEmacs 20 actually achieved enlightenment. It is
417 ;; possible to sanely define both backward and forward deletion
418 ;; behavior under X separately (TTYs are forever beyond hope, but
419 ;; who cares? XEmacs 20 does the right thing with these too).
420 (define-key py-mode-map [delete] 'py-electric-delete)
421 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw2518c671997-11-05 00:51:08 +0000422 ;; marking interesting locations
423 (define-key py-mode-map "\C-c\C-m" 'py-mark-def-or-class)
424 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000425 ;; Miscellaneous
426 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
427 (define-key py-mode-map "\C-c\t" 'py-indent-region)
428 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
429 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
430 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000431 (define-key py-mode-map "\C-c#" 'py-comment-region)
432 (define-key py-mode-map "\C-c?" 'py-describe-mode)
433 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
434 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
435 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000436 ;; information
437 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
438 (define-key py-mode-map "\C-c\C-v" 'py-version)
439 ;; py-newline-and-indent mappings
440 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000441 ;; shadow global bindings for newline-and-indent w/ the py- version.
442 ;; BAW - this is extremely bad form, but I'm not going to change it
443 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000444 (mapcar (function (lambda (key)
445 (define-key
446 py-mode-map key 'py-newline-and-indent)))
447 (where-is-internal 'newline-and-indent))
Barry Warsaw850437a1995-03-08 21:50:28 +0000448 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000449
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000450(defvar py-mode-syntax-table nil
451 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000452(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000453 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000454 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000455 (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 ;; Add operator symbols misassigned in the std table
462 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
463 (modify-syntax-entry ?\% "." py-mode-syntax-table)
464 (modify-syntax-entry ?\& "." py-mode-syntax-table)
465 (modify-syntax-entry ?\* "." py-mode-syntax-table)
466 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
467 (modify-syntax-entry ?\- "." py-mode-syntax-table)
468 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
469 (modify-syntax-entry ?\< "." py-mode-syntax-table)
470 (modify-syntax-entry ?\= "." py-mode-syntax-table)
471 (modify-syntax-entry ?\> "." py-mode-syntax-table)
472 (modify-syntax-entry ?\| "." py-mode-syntax-table)
473 ;; For historical reasons, underscore is word class instead of
474 ;; symbol class. GNU conventions say it should be symbol class, but
475 ;; there's a natural conflict between what major mode authors want
476 ;; and what users expect from `forward-word' and `backward-word'.
477 ;; Guido and I have hashed this out and have decided to keep
478 ;; underscore in word class. If you're tempted to change it, try
479 ;; binding M-f and M-b to py-forward-into-nomenclature and
480 ;; py-backward-into-nomenclature instead.
481 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
482 ;; Both single quote and double quote are string delimiters
483 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
484 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
485 ;; backquote is open and close paren
486 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
487 ;; comment delimiters
488 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
489 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
490 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000491
Barry Warsawb3e81d51996-09-04 15:12:42 +0000492
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000493
Barry Warsaw42f707f1996-07-29 21:05:05 +0000494;; Menu definitions, only relevent if you have the easymenu.el package
495;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000496(defvar py-menu nil
497 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000498This menu will get created automatically if you have the `easymenu'
499package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000500
Barry Warsawc72c11c1997-08-09 06:42:08 +0000501(and (py-safe (require 'easymenu) t)
502 (easy-menu-define
503 py-menu py-mode-map "Python Mode menu"
504 '("Python"
505 ["Comment Out Region" py-comment-region (mark)]
506 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
507 "-"
508 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000509 ["Mark current def" py-mark-def-or-class t]
510 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000511 "-"
512 ["Shift region left" py-shift-region-left (mark)]
513 ["Shift region right" py-shift-region-right (mark)]
514 "-"
515 ["Execute buffer" py-execute-buffer t]
516 ["Execute region" py-execute-region (mark)]
517 ["Start interpreter..." py-shell t]
518 "-"
519 ["Go to start of block" py-goto-block-up t]
520 ["Go to start of class" (beginning-of-python-def-or-class t) t]
521 ["Move to end of class" (end-of-python-def-or-class t) t]
522 ["Move to start of def" beginning-of-python-def-or-class t]
523 ["Move to end of def" end-of-python-def-or-class t]
524 "-"
525 ["Describe mode" py-describe-mode t]
526 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000527
Barry Warsaw81437461996-08-01 19:48:02 +0000528
529
530;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
531(defvar imenu-example--python-class-regexp
532 (concat ; <<classes>>
533 "\\(" ;
534 "^[ \t]*" ; newline and maybe whitespace
535 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
536 ; possibly multiple superclasses
537 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
538 "[ \t]*:" ; and the final :
539 "\\)" ; >>classes<<
540 )
541 "Regexp for Python classes for use with the imenu package."
542 )
543
544(defvar imenu-example--python-method-regexp
545 (concat ; <<methods and functions>>
546 "\\(" ;
547 "^[ \t]*" ; new line and maybe whitespace
548 "\\(def[ \t]+" ; function definitions start with def
549 "\\([a-zA-Z0-9_]+\\)" ; name is here
550 ; function arguments...
551 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
552 "\\)" ; end of def
553 "[ \t]*:" ; and then the :
554 "\\)" ; >>methods and functions<<
555 )
556 "Regexp for Python methods/functions for use with the imenu package."
557 )
558
559(defvar imenu-example--python-method-no-arg-parens '(2 8)
560 "Indicies into groups of the Python regexp for use with imenu.
561
562Using these values will result in smaller imenu lists, as arguments to
563functions are not listed.
564
565See the variable `imenu-example--python-show-method-args-p' for more
566information.")
567
568(defvar imenu-example--python-method-arg-parens '(2 7)
569 "Indicies into groups of the Python regexp for use with imenu.
570Using these values will result in large imenu lists, as arguments to
571functions are listed.
572
573See the variable `imenu-example--python-show-method-args-p' for more
574information.")
575
576;; Note that in this format, this variable can still be used with the
577;; imenu--generic-function. Otherwise, there is no real reason to have
578;; it.
579(defvar imenu-example--generic-python-expression
580 (cons
581 (concat
582 imenu-example--python-class-regexp
583 "\\|" ; or...
584 imenu-example--python-method-regexp
585 )
586 imenu-example--python-method-no-arg-parens)
587 "Generic Python expression which may be used directly with imenu.
588Used by setting the variable `imenu-generic-expression' to this value.
589Also, see the function \\[imenu-example--create-python-index] for a
590better alternative for finding the index.")
591
592;; These next two variables are used when searching for the python
593;; class/definitions. Just saving some time in accessing the
594;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000595(defvar imenu-example--python-generic-regexp nil)
596(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000597
598
599;;;###autoload
600(eval-when-compile
601 ;; Imenu isn't used in XEmacs, so just ignore load errors
602 (condition-case ()
603 (progn
604 (require 'cl)
605 (require 'imenu))
606 (error nil)))
607
608(defun imenu-example--create-python-index ()
609 "Python interface function for imenu package.
610Finds all python classes and functions/methods. Calls function
611\\[imenu-example--create-python-index-engine]. See that function for
612the details of how this works."
613 (setq imenu-example--python-generic-regexp
614 (car imenu-example--generic-python-expression))
615 (setq imenu-example--python-generic-parens
616 (if imenu-example--python-show-method-args-p
617 imenu-example--python-method-arg-parens
618 imenu-example--python-method-no-arg-parens))
619 (goto-char (point-min))
620 (imenu-example--create-python-index-engine nil))
621
622(defun imenu-example--create-python-index-engine (&optional start-indent)
623 "Function for finding imenu definitions in Python.
624
625Finds all definitions (classes, methods, or functions) in a Python
626file for the imenu package.
627
628Returns a possibly nested alist of the form
629
630 (INDEX-NAME . INDEX-POSITION)
631
632The second element of the alist may be an alist, producing a nested
633list as in
634
635 (INDEX-NAME . INDEX-ALIST)
636
637This function should not be called directly, as it calls itself
638recursively and requires some setup. Rather this is the engine for
639the function \\[imenu-example--create-python-index].
640
641It works recursively by looking for all definitions at the current
642indention level. When it finds one, it adds it to the alist. If it
643finds a definition at a greater indentation level, it removes the
644previous definition from the alist. In it's place it adds all
645definitions found at the next indentation level. When it finds a
646definition that is less indented then the current level, it retuns the
647alist it has created thus far.
648
649The optional argument START-INDENT indicates the starting indentation
650at which to continue looking for Python classes, methods, or
651functions. If this is not supplied, the function uses the indentation
652of the first definition found."
653 (let ((index-alist '())
654 (sub-method-alist '())
655 looking-p
656 def-name prev-name
657 cur-indent def-pos
658 (class-paren (first imenu-example--python-generic-parens))
659 (def-paren (second imenu-example--python-generic-parens)))
660 (setq looking-p
661 (re-search-forward imenu-example--python-generic-regexp
662 (point-max) t))
663 (while looking-p
664 (save-excursion
665 ;; used to set def-name to this value but generic-extract-name is
666 ;; new to imenu-1.14. this way it still works with imenu-1.11
667 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
668 (let ((cur-paren (if (match-beginning class-paren)
669 class-paren def-paren)))
670 (setq def-name
671 (buffer-substring (match-beginning cur-paren)
672 (match-end cur-paren))))
673 (beginning-of-line)
674 (setq cur-indent (current-indentation)))
675
676 ;; HACK: want to go to the next correct definition location. we
677 ;; explicitly list them here. would be better to have them in a
678 ;; list.
679 (setq def-pos
680 (or (match-beginning class-paren)
681 (match-beginning def-paren)))
682
683 ;; if we don't have a starting indent level, take this one
684 (or start-indent
685 (setq start-indent cur-indent))
686
687 ;; if we don't have class name yet, take this one
688 (or prev-name
689 (setq prev-name def-name))
690
691 ;; what level is the next definition on? must be same, deeper
692 ;; or shallower indentation
693 (cond
694 ;; at the same indent level, add it to the list...
695 ((= start-indent cur-indent)
696
697 ;; if we don't have push, use the following...
698 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
699 (push (cons def-name def-pos) index-alist))
700
701 ;; deeper indented expression, recur...
702 ((< start-indent cur-indent)
703
704 ;; the point is currently on the expression we're supposed to
705 ;; start on, so go back to the last expression. The recursive
706 ;; call will find this place again and add it to the correct
707 ;; list
708 (re-search-backward imenu-example--python-generic-regexp
709 (point-min) 'move)
710 (setq sub-method-alist (imenu-example--create-python-index-engine
711 cur-indent))
712
713 (if sub-method-alist
714 ;; we put the last element on the index-alist on the start
715 ;; of the submethod alist so the user can still get to it.
716 (let ((save-elmt (pop index-alist)))
717 (push (cons (imenu-create-submenu-name prev-name)
718 (cons save-elmt sub-method-alist))
719 index-alist))))
720
721 ;; found less indented expression, we're done.
722 (t
723 (setq looking-p nil)
724 (re-search-backward imenu-example--python-generic-regexp
725 (point-min) t)))
726 (setq prev-name def-name)
727 (and looking-p
728 (setq looking-p
729 (re-search-forward imenu-example--python-generic-regexp
730 (point-max) 'move))))
731 (nreverse index-alist)))
732
Barry Warsaw42f707f1996-07-29 21:05:05 +0000733
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000734;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000735(defun python-mode ()
736 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000737To submit a problem report, enter `\\[py-submit-bug-report]' from a
738`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
739documentation. To see what version of `python-mode' you are running,
740enter `\\[py-version]'.
741
742This mode knows about Python indentation, tokens, comments and
743continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744
745COMMANDS
746\\{py-mode-map}
747VARIABLES
748
Barry Warsaw42f707f1996-07-29 21:05:05 +0000749py-indent-offset\t\tindentation increment
750py-block-comment-prefix\t\tcomment string used by comment-region
751py-python-command\t\tshell command to invoke Python interpreter
752py-scroll-process-buffer\t\talways scroll Python process buffer
753py-temp-directory\t\tdirectory used for temp files (if needed)
754py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000755 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000756 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000757 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000758 (make-local-variable 'font-lock-defaults)
759 (make-local-variable 'paragraph-separate)
760 (make-local-variable 'paragraph-start)
761 (make-local-variable 'require-final-newline)
762 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000763 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000764 (make-local-variable 'comment-start-skip)
765 (make-local-variable 'comment-column)
766 (make-local-variable 'indent-region-function)
767 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000768 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000769 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000770 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000771 (setq major-mode 'python-mode
772 mode-name "Python"
773 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000774 paragraph-separate "^[ \t]*$"
775 paragraph-start "^[ \t]*$"
776 require-final-newline t
777 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000778 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000779 comment-start-skip "# *"
780 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000781 indent-region-function 'py-indent-region
782 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000783 ;; tell add-log.el how to find the current function/method/variable
784 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000785 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000786 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000787 ;; add the menu
788 (if py-menu
789 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000790 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000791 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000792 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000793 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000794 ;;
795 ;; not sure where the magic comment has to be; to save time
796 ;; searching for a rarity, we give up if it's not found prior to the
797 ;; first executable statement.
798 ;;
799 ;; BAW - on first glance, this seems like complete hackery. Why was
800 ;; this necessary, and is it still necessary?
801 (let ((case-fold-search nil)
802 (start (point))
803 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000804 (if (re-search-forward
805 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
806 (prog2 (py-next-statement 1) (point) (goto-char 1))
807 t)
808 (progn
809 (setq new-tab-width
810 (string-to-int
811 (buffer-substring (match-beginning 1) (match-end 1))))
812 (if (= tab-width new-tab-width)
813 nil
814 (setq tab-width new-tab-width)
815 (message "Caution: tab-width changed to %d" new-tab-width)
816 (if py-beep-if-tab-change (beep)))))
817 (goto-char start))
818
Barry Warsaw755c6711996-08-01 20:02:55 +0000819 ;; install imenu
820 (setq imenu-create-index-function
821 (function imenu-example--create-python-index))
822 (if (fboundp 'imenu-add-to-menubar)
823 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
824
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000825 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000826 (if python-mode-hook
827 (run-hooks 'python-mode-hook)
828 (run-hooks 'py-mode-hook)))
829
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000830
Barry Warsawb91b7431995-03-14 15:55:20 +0000831;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000832(defun py-outdent-p ()
833 ;; returns non-nil if the current line should outdent one level
834 (save-excursion
835 (and (progn (back-to-indentation)
836 (looking-at py-outdent-re))
837 (progn (backward-to-indentation 1)
838 (while (or (looking-at py-blank-or-comment-re)
839 (bobp))
840 (backward-to-indentation 1))
841 (not (looking-at py-no-outdent-re)))
842 )))
843
Barry Warsawb91b7431995-03-14 15:55:20 +0000844(defun py-electric-colon (arg)
845 "Insert a colon.
846In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000847argument is provided, that many colons are inserted non-electrically.
848Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000849 (interactive "P")
850 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000851 ;; are we in a string or comment?
852 (if (save-excursion
853 (let ((pps (parse-partial-sexp (save-excursion
854 (beginning-of-python-def-or-class)
855 (point))
856 (point))))
857 (not (or (nth 3 pps) (nth 4 pps)))))
858 (save-excursion
859 (let ((here (point))
860 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000861 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000862 (if (and (not arg)
863 (py-outdent-p)
864 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000865 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000866 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000867 )
868 (setq outdent py-indent-offset))
869 ;; Don't indent, only outdent. This assumes that any lines that
870 ;; are already outdented relative to py-compute-indentation were
871 ;; put there on purpose. Its highly annoying to have `:' indent
872 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
873 ;; there a better way to determine this???
874 (if (< (current-indentation) indent) nil
875 (goto-char here)
876 (beginning-of-line)
877 (delete-horizontal-space)
878 (indent-to (- indent outdent))
879 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000880
881
Barry Warsawa97a3f31997-11-04 18:47:06 +0000882;; Python subprocess utilities and filters
883(defun py-execute-file (proc filename)
884 ;; Send a properly formatted execfile('FILENAME') to the underlying
885 ;; Python interpreter process FILENAME. Make that process's buffer
886 ;; visible and force display. Also make comint believe the user
887 ;; typed this string so that kill-output-from-shell does The Right
888 ;; Thing.
889 (let ((curbuf (current-buffer))
890 (procbuf (process-buffer proc))
891 (comint-scroll-to-bottom-on-output t)
892 (msg (format "## working on region in file %s...\n" filename))
893 (cmd (format "execfile('%s')\n" filename)))
894 (unwind-protect
895 (progn
896 (set-buffer procbuf)
897 (goto-char (point-max))
898 (move-marker (process-mark proc) (point))
899 (funcall (process-filter proc) proc msg))
900 (set-buffer curbuf))
901 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000902
903(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904 (let ((curbuf (current-buffer))
905 (pbuf (process-buffer pyproc))
906 (pmark (process-mark pyproc))
907 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000908 ;; make sure we switch to a different buffer at least once. if we
909 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000910 ;; window, and point is before the end, and lots of output is
911 ;; coming at a fast pace, then (a) simple cursor-movement commands
912 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
913 ;; to have a visible effect (the window just doesn't get updated,
914 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
915 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917 ;; #b makes no sense to me at all. #a almost makes sense: unless
918 ;; we actually change buffers, set_buffer_internal in buffer.c
919 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
920 ;; seems to make the Emacs command loop reluctant to update the
921 ;; display. Perhaps the default process filter in process.c's
922 ;; read_process_output has update_mode_lines++ for a similar
923 ;; reason? beats me ...
924
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000925 (unwind-protect
926 ;; make sure current buffer is restored
927 ;; BAW - we want to check to see if this still applies
928 (progn
929 ;; mysterious ugly hack
930 (if (eq curbuf pbuf)
931 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000932
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000933 (set-buffer pbuf)
934 (let* ((start (point))
935 (goback (< start pmark))
936 (goend (and (not goback) (= start (point-max))))
937 (buffer-read-only nil))
938 (goto-char pmark)
939 (insert string)
940 (move-marker pmark (point))
941 (setq file-finished
942 (and py-file-queue
943 (equal ">>> "
944 (buffer-substring
945 (prog2 (beginning-of-line) (point)
946 (goto-char pmark))
947 (point)))))
948 (if goback (goto-char start)
949 ;; else
950 (if py-scroll-process-buffer
951 (let* ((pop-up-windows t)
952 (pwin (display-buffer pbuf)))
953 (set-window-point pwin (point)))))
954 (set-buffer curbuf)
955 (if file-finished
956 (progn
957 (py-delete-file-silently (car py-file-queue))
958 (setq py-file-queue (cdr py-file-queue))
959 (if py-file-queue
960 (py-execute-file pyproc (car py-file-queue)))))
961 (and goend
962 (progn (set-buffer pbuf)
963 (goto-char (point-max))))
964 ))
965 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966
Barry Warsawa97a3f31997-11-04 18:47:06 +0000967
968;;; Subprocess commands
969
970;;;###autoload
971(defun py-shell ()
972 "Start an interactive Python interpreter in another window.
973This is like Shell mode, except that Python is running in the window
974instead of a shell. See the `Interactive Shell' and `Shell Mode'
975sections of the Emacs manual for details, especially for the key
976bindings active in the `*Python*' buffer.
977
978See the docs for variable `py-scroll-buffer' for info on scrolling
979behavior in the process window.
980
981Warning: Don't use an interactive Python if you change sys.ps1 or
982sys.ps2 from their default values, or if you're running code that
983prints `>>> ' or `... ' at the start of a line. `python-mode' can't
984distinguish your output from Python's output, and assumes that `>>> '
985at the start of a line is a prompt from Python. Similarly, the Emacs
986Shell mode code assumes that both `>>> ' and `... ' at the start of a
987line are Python prompts. Bad things can happen if you fool either
988mode.
989
990Warning: If you do any editing *in* the process buffer *while* the
991buffer is accepting output from Python, do NOT attempt to `undo' the
992changes. Some of the output (nowhere near the parts you changed!) may
993be lost if you do. This appears to be an Emacs bug, an unfortunate
994interaction between undo and process filters; the same problem exists in
995non-Python process buffers using the default (Emacs-supplied) process
996filter."
997 ;; BAW - should undo be disabled in the python process buffer, if
998 ;; this bug still exists?
999 (interactive)
1000 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001001 (switch-to-buffer-other-window
1002 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001003 (make-local-variable 'comint-prompt-regexp)
1004 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1005 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1006 (set-syntax-table py-mode-syntax-table)
1007 (local-set-key [tab] 'self-insert-command))
1008
1009
1010(defun py-clear-queue ()
1011 "Clear the queue of temporary files waiting to execute."
1012 (interactive)
1013 (let ((n (length py-file-queue)))
1014 (mapcar 'delete-file py-file-queue)
1015 (setq py-file-queue nil)
1016 (message "%d pending files de-queued." n)))
1017
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001018;; only used when (memq 'broken-temp-names py-emacs-features)
1019(defvar py-serial-number 0)
1020
Barry Warsawa97a3f31997-11-04 18:47:06 +00001021(defun py-execute-region (start end &optional async)
1022 "Execute the the region in a Python interpreter.
1023The region is first copied into a temporary file (in the directory
1024`py-temp-directory'). If there is no Python interpreter shell
1025running, this file is executed synchronously using
1026`shell-command-on-region'. If the program is long running, use an
1027optional \\[universal-argument] to run the command asynchronously in
1028its own buffer.
1029
1030If the Python interpreter shell is running, the region is execfile()'d
1031in that shell. If you try to execute regions too quickly,
1032`python-mode' will queue them up and execute them one at a time when
1033it sees a `>>> ' prompt from Python. Each time this happens, the
1034process buffer is popped into a window (if it's not already in some
1035window) so you can see it, and a comment of the form
1036
1037 \t## working on region in file <name>...
1038
1039is inserted at the end. See also the command `py-clear-queue'."
1040 (interactive "r\nP")
1041 (or (< start end)
1042 (error "Region is empty"))
1043 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001044 (temp (if (memq 'broken-temp-names py-emacs-features)
1045 (prog1
1046 (format "python-%d" py-serial-number)
1047 (setq py-serial-number (1+ py-serial-number)))
1048 (make-temp-name "python")))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001049 (file (concat (file-name-as-directory py-temp-directory) temp))
1050 (outbuf "*Python Output*"))
1051 (write-region start end file nil 'nomsg)
1052 (cond
1053 ;; always run the code in it's own asynchronous subprocess
1054 (async
1055 (let* ((buf (generate-new-buffer-name "*Python Output*")))
1056 (start-process "Python" buf py-python-command "-u" file)
1057 (pop-to-buffer buf)
1058 ))
1059 ;; if the Python interpreter shell is running, queue it up for
1060 ;; execution there.
1061 (proc
1062 ;; use the existing python shell
1063 (if (not py-file-queue)
1064 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001065 (message "File %s queued for execution" file))
Barry Warsawa9ce70f1997-11-05 16:56:51 +00001066 (push file py-file-queue))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001067 (t
1068 ;; otherwise either run it synchronously in a subprocess
1069 (shell-command-on-region start end py-python-command outbuf)
1070 ))))
1071
1072;; Code execution command
1073(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001074 "Send the contents of the buffer to a Python interpreter.
1075If there is a *Python* process buffer it is used. If a clipping
1076restriction is in effect, only the accessible portion of the buffer is
1077sent. A trailing newline will be supplied if needed.
1078
1079See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001080 (interactive "P")
1081 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001082
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001084;; Electric deletion
1085(defun py-electric-backspace (arg)
1086 "Deletes preceding character or levels of indentation.
1087Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001088with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001089
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001090If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001091
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001092Otherwise, if point is at the leftmost non-whitespace character of a
1093line that is neither a continuation line nor a non-indenting comment
1094line, or if point is at the end of a blank line, this command reduces
1095the indentation to match that of the line that opened the current
1096block of code. The line that opened the block is displayed in the
1097echo area to help you keep track of where you are. With numeric arg,
1098outdents that many blocks (but not past column zero).
1099
1100Otherwise the preceding character is deleted, converting a tab to
1101spaces if needed so that only a single column position is deleted.
1102Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001103 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001104 (if (or (/= (current-indentation) (current-column))
1105 (bolp)
1106 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001107 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001108 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001109 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001110 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001111 ;; force non-blank so py-goto-block-up doesn't ignore it
1112 (insert-char ?* 1)
1113 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001114 (let ((base-indent 0) ; indentation of base line
1115 (base-text "") ; and text of base line
1116 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001117 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001118 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001119 (condition-case nil ; in case no enclosing block
1120 (progn
1121 (py-goto-block-up 'no-mark)
1122 (setq base-indent (current-indentation)
1123 base-text (py-suck-up-leading-text)
1124 base-found-p t))
1125 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001126 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001127 (delete-char 1) ; toss the dummy character
1128 (delete-horizontal-space)
1129 (indent-to base-indent)
1130 (if base-found-p
1131 (message "Closes block: %s" base-text)))))
1132
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001133
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001134(defun py-electric-delete (arg)
1135 "Deletes preceding or following character or levels of whitespace.
1136
1137The behavior of this function depends on the variable
1138`delete-key-deletes-forward'. If this variable is nil (or does not
1139exist, as in older Emacsen), then this function behaves identical to
1140\\[c-electric-backspace].
1141
1142If `delete-key-deletes-forward' is non-nil and is supported in your
1143Emacs, then deletion occurs in the forward direction, by calling the
1144function in `py-delete-function'."
1145 (interactive "*p")
1146 (if (and (boundp 'delete-key-deletes-forward)
1147 delete-key-deletes-forward)
1148 (funcall py-delete-function arg)
1149 ;; else
1150 (py-electric-backspace arg)))
1151
1152;; required for pending-del and delsel modes
1153(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1154(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1155(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1156(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1157
1158
1159
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001160(defun py-indent-line (&optional arg)
1161 "Fix the indentation of the current line according to Python rules.
1162With \\[universal-argument], ignore outdenting rules for block
1163closing statements (e.g. return, raise, break, continue, pass)
1164
1165This function is normally bound to `indent-line-function' so
1166\\[indent-for-tab-command] will call it."
1167 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001168 (let* ((ci (current-indentation))
1169 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001170 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001171 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001172 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001173 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174 (if (/= ci need)
1175 (save-excursion
1176 (beginning-of-line)
1177 (delete-horizontal-space)
1178 (indent-to need)))
1179 (if move-to-indentation-p (back-to-indentation))))
1180
1181(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183This is just `strives to' because correct indentation can't be computed
1184from scratch for Python code. In general, deletes the whitespace before
1185point, inserts a newline, and takes an educated guess as to how you want
1186the new line indented."
1187 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001188 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001189 (if (< ci (current-column)) ; if point beyond indentation
1190 (newline-and-indent)
1191 ;; else try to act like newline-and-indent "normally" acts
1192 (beginning-of-line)
1193 (insert-char ?\n 1)
1194 (move-to-column ci))))
1195
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001196(defun py-compute-indentation (honor-block-close-p)
1197 ;; implements all the rules for indentation computation. when
1198 ;; honor-block-close-p is non-nil, statements such as return, raise,
1199 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001200 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001201 (let ((pps (parse-partial-sexp (save-excursion
1202 (beginning-of-python-def-or-class)
1203 (point))
1204 (point))))
1205 (beginning-of-line)
1206 (cond
1207 ;; are we inside a string or comment?
1208 ((or (nth 3 pps) (nth 4 pps))
1209 (save-excursion
1210 (if (not py-align-multiline-strings-p) 0
1211 ;; skip back over blank & non-indenting comment lines
1212 ;; note: will skip a blank or non-indenting comment line
1213 ;; that happens to be a continuation line too
1214 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1215 (back-to-indentation)
1216 (current-column))))
1217 ;; are we on a continuation line?
1218 ((py-continuation-line-p)
1219 (let ((startpos (point))
1220 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001221 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001222 (if open-bracket-pos
1223 (progn
1224 ;; align with first item in list; else a normal
1225 ;; indent beyond the line with the open bracket
1226 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1227 ;; is the first list item on the same line?
1228 (skip-chars-forward " \t")
1229 (if (null (memq (following-char) '(?\n ?# ?\\)))
1230 ; yes, so line up with it
1231 (current-column)
1232 ;; first list item on another line, or doesn't exist yet
1233 (forward-line 1)
1234 (while (and (< (point) startpos)
1235 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1236 (forward-line 1))
1237 (if (< (point) startpos)
1238 ;; again mimic the first list item
1239 (current-indentation)
1240 ;; else they're about to enter the first item
1241 (goto-char open-bracket-pos)
1242 (+ (current-indentation) py-indent-offset))))
1243
1244 ;; else on backslash continuation line
1245 (forward-line -1)
1246 (if (py-continuation-line-p) ; on at least 3rd line in block
1247 (current-indentation) ; so just continue the pattern
1248 ;; else started on 2nd line in block, so indent more.
1249 ;; if base line is an assignment with a start on a RHS,
1250 ;; indent to 2 beyond the leftmost "="; else skip first
1251 ;; chunk of non-whitespace characters on base line, + 1 more
1252 ;; column
1253 (end-of-line)
1254 (setq endpos (point) searching t)
1255 (back-to-indentation)
1256 (setq startpos (point))
1257 ;; look at all "=" from left to right, stopping at first
1258 ;; one not nested in a list or string
1259 (while searching
1260 (skip-chars-forward "^=" endpos)
1261 (if (= (point) endpos)
1262 (setq searching nil)
1263 (forward-char 1)
1264 (setq state (parse-partial-sexp startpos (point)))
1265 (if (and (zerop (car state)) ; not in a bracket
1266 (null (nth 3 state))) ; & not in a string
1267 (progn
1268 (setq searching nil) ; done searching in any case
1269 (setq found
1270 (not (or
1271 (eq (following-char) ?=)
1272 (memq (char-after (- (point) 2))
1273 '(?< ?> ?!)))))))))
1274 (if (or (not found) ; not an assignment
1275 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1276 (progn
1277 (goto-char startpos)
1278 (skip-chars-forward "^ \t\n")))
1279 (1+ (current-column))))))
1280
1281 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001282 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001283
Barry Warsawa7891711996-08-01 15:53:09 +00001284 ;; Dfn: "Indenting comment line". A line containing only a
1285 ;; comment, but which is treated like a statement for
1286 ;; indentation calculation purposes. Such lines are only
1287 ;; treated specially by the mode; they are not treated
1288 ;; specially by the Python interpreter.
1289
1290 ;; The rules for indenting comment lines are a line where:
1291 ;; - the first non-whitespace character is `#', and
1292 ;; - the character following the `#' is whitespace, and
1293 ;; - the line is outdented with respect to (i.e. to the left
1294 ;; of) the indentation of the preceding non-blank line.
1295
1296 ;; The first non-blank line following an indenting comment
1297 ;; line is given the same amount of indentation as the
1298 ;; indenting comment line.
1299
1300 ;; All other comment-only lines are ignored for indentation
1301 ;; purposes.
1302
1303 ;; Are we looking at a comment-only line which is *not* an
1304 ;; indenting comment line? If so, we assume that its been
1305 ;; placed at the desired indentation, so leave it alone.
1306 ;; Indenting comment lines are aligned as statements down
1307 ;; below.
1308 ((and (looking-at "[ \t]*#[^ \t\n]")
1309 ;; NOTE: this test will not be performed in older Emacsen
1310 (fboundp 'forward-comment)
1311 (<= (current-indentation)
1312 (save-excursion
1313 (forward-comment (- (point-max)))
1314 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001315 (current-indentation))
1316
1317 ;; else indentation based on that of the statement that
1318 ;; precedes us; use the first line of that statement to
1319 ;; establish the base, in case the user forced a non-std
1320 ;; indentation for the continuation lines (if any)
1321 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001322 ;; skip back over blank & non-indenting comment lines note:
1323 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001324 ;; happens to be a continuation line too. use fast Emacs 19
1325 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001326 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001327 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001328 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001329 (let (done)
1330 (while (not done)
1331 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1332 nil 'move)
1333 (setq done (or (eq py-honor-comment-indentation t)
1334 (bobp)
1335 (/= (following-char) ?#)
1336 (not (zerop (current-column)))))
1337 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001338 ;; if we landed inside a string, go to the beginning of that
1339 ;; string. this handles triple quoted, multi-line spanning
1340 ;; strings.
1341 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001342 (+ (current-indentation)
1343 (if (py-statement-opens-block-p)
1344 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001345 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001346 (- py-indent-offset)
1347 0)))
1348 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001349
1350(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001351 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001353`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001355`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356their own buffer-local copy), both those currently existing and those
1357created later in the Emacs session.
1358
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001360There's no excuse for such foolishness, but sometimes you have to deal
1361with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001362`py-indent-offset' to what it thinks it was when they created the
1363mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001364
1365Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001366looking for a line that opens a block of code. `py-indent-offset' is
1367set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001368statement following it. If the search doesn't succeed going forward,
1369it's tried again going backward."
1370 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371 (let (new-value
1372 (start (point))
1373 restart
1374 (found nil)
1375 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376 (py-goto-initial-line)
1377 (while (not (or found (eobp)))
1378 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1379 (progn
1380 (setq restart (point))
1381 (py-goto-initial-line)
1382 (if (py-statement-opens-block-p)
1383 (setq found t)
1384 (goto-char restart)))))
1385 (if found
1386 ()
1387 (goto-char start)
1388 (py-goto-initial-line)
1389 (while (not (or found (bobp)))
1390 (setq found
1391 (and
1392 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1393 (or (py-goto-initial-line) t) ; always true -- side effect
1394 (py-statement-opens-block-p)))))
1395 (setq colon-indent (current-indentation)
1396 found (and found (zerop (py-next-statement 1)))
1397 new-value (- (current-indentation) colon-indent))
1398 (goto-char start)
1399 (if found
1400 (progn
1401 (funcall (if global 'kill-local-variable 'make-local-variable)
1402 'py-indent-offset)
1403 (setq py-indent-offset new-value)
1404 (message "%s value of py-indent-offset set to %d"
1405 (if global "Global" "Local")
1406 py-indent-offset))
1407 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1408
1409(defun py-shift-region (start end count)
1410 (save-excursion
1411 (goto-char end) (beginning-of-line) (setq end (point))
1412 (goto-char start) (beginning-of-line) (setq start (point))
1413 (indent-rigidly start end count)))
1414
1415(defun py-shift-region-left (start end &optional count)
1416 "Shift region of Python code to the left.
1417The lines from the line containing the start of the current region up
1418to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001419shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001420
1421If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001422many columns. With no active region, outdent only the current line.
1423You cannot outdent the region if any line is already at column zero."
1424 (interactive
1425 (let ((p (point))
1426 (m (mark))
1427 (arg current-prefix-arg))
1428 (if m
1429 (list (min p m) (max p m) arg)
1430 (list p (save-excursion (forward-line 1) (point)) arg))))
1431 ;; if any line is at column zero, don't shift the region
1432 (save-excursion
1433 (goto-char start)
1434 (while (< (point) end)
1435 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001436 (if (and (zerop (current-column))
1437 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001438 (error "Region is at left edge."))
1439 (forward-line 1)))
1440 (py-shift-region start end (- (prefix-numeric-value
1441 (or count py-indent-offset))))
1442 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001443
1444(defun py-shift-region-right (start end &optional count)
1445 "Shift region of Python code to the right.
1446The lines from the line containing the start of the current region up
1447to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001448shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449
1450If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001451many columns. With no active region, indent only the current line."
1452 (interactive
1453 (let ((p (point))
1454 (m (mark))
1455 (arg current-prefix-arg))
1456 (if m
1457 (list (min p m) (max p m) arg)
1458 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001460 (or count py-indent-offset)))
1461 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001462
1463(defun py-indent-region (start end &optional indent-offset)
1464 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001465
Barry Warsaw7ae77681994-12-12 20:38:05 +00001466The lines from the line containing the start of the current region up
1467to (but not including) the line containing the end of the region are
1468reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001469character in the first column, the first line is left alone and the
1470rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001471region is reindented with respect to the (closest code or indenting
1472comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001473
1474This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001475control structures are introduced or removed, or to reformat code
1476using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001477
1478If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480used.
1481
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001482Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001483is called! This function does not compute proper indentation from
1484scratch (that's impossible in Python), it merely adjusts the existing
1485indentation to be correct in context.
1486
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001487Warning: This function really has no idea what to do with
1488non-indenting comment lines, and shifts them as if they were indenting
1489comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001490
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001491Special cases: whitespace is deleted from blank lines; continuation
1492lines are shifted by the same amount their initial line was shifted,
1493in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001494initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001495 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001496 (save-excursion
1497 (goto-char end) (beginning-of-line) (setq end (point-marker))
1498 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001499 (let ((py-indent-offset (prefix-numeric-value
1500 (or indent-offset py-indent-offset)))
1501 (indents '(-1)) ; stack of active indent levels
1502 (target-column 0) ; column to which to indent
1503 (base-shifted-by 0) ; amount last base line was shifted
1504 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001505 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001506 0))
1507 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001508 (while (< (point) end)
1509 (setq ci (current-indentation))
1510 ;; figure out appropriate target column
1511 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001512 ((or (eq (following-char) ?#) ; comment in column 1
1513 (looking-at "[ \t]*$")) ; entirely blank
1514 (setq target-column 0))
1515 ((py-continuation-line-p) ; shift relative to base line
1516 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001517 (t ; new base line
1518 (if (> ci (car indents)) ; going deeper; push it
1519 (setq indents (cons ci indents))
1520 ;; else we should have seen this indent before
1521 (setq indents (memq ci indents)) ; pop deeper indents
1522 (if (null indents)
1523 (error "Bad indentation in region, at line %d"
1524 (save-restriction
1525 (widen)
1526 (1+ (count-lines 1 (point)))))))
1527 (setq target-column (+ indent-base
1528 (* py-indent-offset
1529 (- (length indents) 2))))
1530 (setq base-shifted-by (- target-column ci))))
1531 ;; shift as needed
1532 (if (/= ci target-column)
1533 (progn
1534 (delete-horizontal-space)
1535 (indent-to target-column)))
1536 (forward-line 1))))
1537 (set-marker end nil))
1538
Barry Warsawa7891711996-08-01 15:53:09 +00001539(defun py-comment-region (beg end &optional arg)
1540 "Like `comment-region' but uses double hash (`#') comment starter."
1541 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001542 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001543 (comment-region beg end arg)))
1544
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001545
1546;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547(defun py-previous-statement (count)
1548 "Go to the start of previous Python statement.
1549If the statement at point is the i'th Python statement, goes to the
1550start of statement i-COUNT. If there is no such statement, goes to the
1551first statement. Returns count of statements left to move.
1552`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001554 (if (< count 0) (py-next-statement (- count))
1555 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001557 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001558 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559 (> count 0)
1560 (zerop (forward-line -1))
1561 (py-goto-statement-at-or-above))
1562 (setq count (1- count)))
1563 (if (> count 0) (goto-char start)))
1564 count))
1565
1566(defun py-next-statement (count)
1567 "Go to the start of next Python statement.
1568If the statement at point is the i'th Python statement, goes to the
1569start of statement i+COUNT. If there is no such statement, goes to the
1570last statement. Returns count of statements left to move. `Statements'
1571do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001572 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573 (if (< count 0) (py-previous-statement (- count))
1574 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001575 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001576 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001577 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578 (> count 0)
1579 (py-goto-statement-below))
1580 (setq count (1- count)))
1581 (if (> count 0) (goto-char start)))
1582 count))
1583
1584(defun py-goto-block-up (&optional nomark)
1585 "Move up to start of current block.
1586Go to the statement that starts the smallest enclosing block; roughly
1587speaking, this will be the closest preceding statement that ends with a
1588colon and is indented less than the statement you started on. If
1589successful, also sets the mark to the starting point.
1590
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001591`\\[py-mark-block]' can be used afterward to mark the whole code
1592block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001593
1594If called from a program, the mark will not be set if optional argument
1595NOMARK is not nil."
1596 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001597 (let ((start (point))
1598 (found nil)
1599 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600 (py-goto-initial-line)
1601 ;; if on blank or non-indenting comment line, use the preceding stmt
1602 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1603 (progn
1604 (py-goto-statement-at-or-above)
1605 (setq found (py-statement-opens-block-p))))
1606 ;; search back for colon line indented less
1607 (setq initial-indent (current-indentation))
1608 (if (zerop initial-indent)
1609 ;; force fast exit
1610 (goto-char (point-min)))
1611 (while (not (or found (bobp)))
1612 (setq found
1613 (and
1614 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1615 (or (py-goto-initial-line) t) ; always true -- side effect
1616 (< (current-indentation) initial-indent)
1617 (py-statement-opens-block-p))))
1618 (if found
1619 (progn
1620 (or nomark (push-mark start))
1621 (back-to-indentation))
1622 (goto-char start)
1623 (error "Enclosing block not found"))))
1624
1625(defun beginning-of-python-def-or-class (&optional class)
1626 "Move point to start of def (or class, with prefix arg).
1627
1628Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001629arg, looks for a `class' instead. The docs assume the `def' case;
1630just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001631
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001632If point is in a def statement already, and after the `d', simply
1633moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001634
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001635Else (point is not in a def statement, or at or before the `d' of a
1636def statement), searches for the closest preceding def statement, and
1637leaves point at its start. If no such statement can be found, leaves
1638point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001639
1640Returns t iff a def statement is found by these rules.
1641
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001642Note that doing this command repeatedly will take you closer to the
1643start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001644
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001645If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001646`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001647 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001648 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1649 (start-of-line (progn (beginning-of-line) (point)))
1650 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001651 (if (or (/= start-of-stmt start-of-line)
1652 (not at-or-before-p))
1653 (end-of-line)) ; OK to match on this line
1654 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001655 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
1657(defun end-of-python-def-or-class (&optional class)
1658 "Move point beyond end of def (or class, with prefix arg) body.
1659
1660By default, looks for an appropriate `def'. If you supply a prefix arg,
1661looks for a `class' instead. The docs assume the `def' case; just
1662substitute `class' for `def' for the other case.
1663
1664If point is in a def statement already, this is the def we use.
1665
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666Else if the def found by `\\[beginning-of-python-def-or-class]'
1667contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001668
1669Else we search forward for the closest following def, and use that.
1670
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671If a def can be found by these rules, point is moved to the start of
1672the line immediately following the def block, and the position of the
1673start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674
1675Else point is moved to the end of the buffer, and nil is returned.
1676
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001677Note that doing this command repeatedly will take you closer to the
1678end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001680If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001681`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001682 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001683 (let ((start (progn (py-goto-initial-line) (point)))
1684 (which (if class "class" "def"))
1685 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001686 ;; move point to start of appropriate def/class
1687 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1688 (setq state 'at-beginning)
1689 ;; else see if beginning-of-python-def-or-class hits container
1690 (if (and (beginning-of-python-def-or-class class)
1691 (progn (py-goto-beyond-block)
1692 (> (point) start)))
1693 (setq state 'at-end)
1694 ;; else search forward
1695 (goto-char start)
1696 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1697 (progn (setq state 'at-beginning)
1698 (beginning-of-line)))))
1699 (cond
1700 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1701 ((eq state 'at-end) t)
1702 ((eq state 'not-found) nil)
1703 (t (error "internal error in end-of-python-def-or-class")))))
1704
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001705
1706;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001707(defun py-mark-block (&optional extend just-move)
1708 "Mark following block of lines. With prefix arg, mark structure.
1709Easier to use than explain. It sets the region to an `interesting'
1710block of succeeding lines. If point is on a blank line, it goes down to
1711the next non-blank line. That will be the start of the region. The end
1712of the region depends on the kind of line at the start:
1713
1714 - If a comment, the region will include all succeeding comment lines up
1715 to (but not including) the next non-comment line (if any).
1716
1717 - Else if a prefix arg is given, and the line begins one of these
1718 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001719
1720 if elif else try except finally for while def class
1721
Barry Warsaw7ae77681994-12-12 20:38:05 +00001722 the region will be set to the body of the structure, including
1723 following blocks that `belong' to it, but excluding trailing blank
1724 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001725 and all (if any) of the following `except' and `finally' blocks
1726 that belong to the `try' structure will be in the region. Ditto
1727 for if/elif/else, for/else and while/else structures, and (a bit
1728 degenerate, since they're always one-block structures) def and
1729 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001730
1731 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001732 block (see list above), and the block is not a `one-liner' (i.e.,
1733 the statement ends with a colon, not with code), the region will
1734 include all succeeding lines up to (but not including) the next
1735 code statement (if any) that's indented no more than the starting
1736 line, except that trailing blank and comment lines are excluded.
1737 E.g., if the starting line begins a multi-statement `def'
1738 structure, the region will be set to the full function definition,
1739 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001740
1741 - Else the region will include all succeeding lines up to (but not
1742 including) the next blank line, or code or indenting-comment line
1743 indented strictly less than the starting line. Trailing indenting
1744 comment lines are included in this case, but not trailing blank
1745 lines.
1746
1747A msg identifying the location of the mark is displayed in the echo
1748area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1749
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001750If called from a program, optional argument EXTEND plays the role of
1751the prefix arg, and if optional argument JUST-MOVE is not nil, just
1752moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001753 (interactive "P") ; raw prefix arg
1754 (py-goto-initial-line)
1755 ;; skip over blank lines
1756 (while (and
1757 (looking-at "[ \t]*$") ; while blank line
1758 (not (eobp))) ; & somewhere to go
1759 (forward-line 1))
1760 (if (eobp)
1761 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001762 (let ((initial-pos (point))
1763 (initial-indent (current-indentation))
1764 last-pos ; position of last stmt in region
1765 (followers
1766 '((if elif else) (elif elif else) (else)
1767 (try except finally) (except except) (finally)
1768 (for else) (while else)
1769 (def) (class) ) )
1770 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771
1772 (cond
1773 ;; if comment line, suck up the following comment lines
1774 ((looking-at "[ \t]*#")
1775 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1776 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1777 (setq last-pos (point)))
1778
1779 ;; else if line is a block line and EXTEND given, suck up
1780 ;; the whole structure
1781 ((and extend
1782 (setq first-symbol (py-suck-up-first-keyword) )
1783 (assq first-symbol followers))
1784 (while (and
1785 (or (py-goto-beyond-block) t) ; side effect
1786 (forward-line -1) ; side effect
1787 (setq last-pos (point)) ; side effect
1788 (py-goto-statement-below)
1789 (= (current-indentation) initial-indent)
1790 (setq next-symbol (py-suck-up-first-keyword))
1791 (memq next-symbol (cdr (assq first-symbol followers))))
1792 (setq first-symbol next-symbol)))
1793
1794 ;; else if line *opens* a block, search for next stmt indented <=
1795 ((py-statement-opens-block-p)
1796 (while (and
1797 (setq last-pos (point)) ; always true -- side effect
1798 (py-goto-statement-below)
1799 (> (current-indentation) initial-indent))
1800 nil))
1801
1802 ;; else plain code line; stop at next blank line, or stmt or
1803 ;; indenting comment line indented <
1804 (t
1805 (while (and
1806 (setq last-pos (point)) ; always true -- side effect
1807 (or (py-goto-beyond-final-line) t)
1808 (not (looking-at "[ \t]*$")) ; stop at blank line
1809 (or
1810 (>= (current-indentation) initial-indent)
1811 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1812 nil)))
1813
1814 ;; skip to end of last stmt
1815 (goto-char last-pos)
1816 (py-goto-beyond-final-line)
1817
1818 ;; set mark & display
1819 (if just-move
1820 () ; just return
1821 (push-mark (point) 'no-msg)
1822 (forward-line -1)
1823 (message "Mark set after: %s" (py-suck-up-leading-text))
1824 (goto-char initial-pos))))
1825
Barry Warsaw2518c671997-11-05 00:51:08 +00001826(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827 "Set region to body of def (or class, with prefix arg) enclosing point.
1828Pushes the current mark, then point, on the mark ring (all language
1829modes do this, but although it's handy it's never documented ...).
1830
1831In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001832hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1833`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
1835And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001836Turned out that was more confusing than useful: the `goto start' and
1837`goto end' commands are usually used to search through a file, and
1838people expect them to act a lot like `search backward' and `search
1839forward' string-search commands. But because Python `def' and `class'
1840can nest to arbitrary levels, finding the smallest def containing
1841point cannot be done via a simple backward search: the def containing
1842point may not be the closest preceding def, or even the closest
1843preceding def that's indented less. The fancy algorithm required is
1844appropriate for the usual uses of this `mark' command, but not for the
1845`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847So the def marked by this command may not be the one either of the
1848`goto' commands find: If point is on a blank or non-indenting comment
1849line, moves back to start of the closest preceding code statement or
1850indenting comment line. If this is a `def' statement, that's the def
1851we use. Else searches for the smallest enclosing `def' block and uses
1852that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854When an enclosing def is found: The mark is left immediately beyond
1855the last line of the def block. Point is left at the start of the
1856def, except that: if the def is preceded by a number of comment lines
1857followed by (at most) one optional blank line, point is left at the
1858start of the comments; else if the def is preceded by a blank line,
1859point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860
1861The intent is to mark the containing def/class and its associated
1862documentation, to make moving and duplicating functions and classes
1863pleasant."
1864 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865 (let ((start (point))
1866 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001867 (push-mark start)
1868 (if (not (py-go-up-tree-to-keyword which))
1869 (progn (goto-char start)
1870 (error "Enclosing %s not found" which))
1871 ;; else enclosing def/class found
1872 (setq start (point))
1873 (py-goto-beyond-block)
1874 (push-mark (point))
1875 (goto-char start)
1876 (if (zerop (forward-line -1)) ; if there is a preceding line
1877 (progn
1878 (if (looking-at "[ \t]*$") ; it's blank
1879 (setq start (point)) ; so reset start point
1880 (goto-char start)) ; else try again
1881 (if (zerop (forward-line -1))
1882 (if (looking-at "[ \t]*#") ; a comment
1883 ;; look back for non-comment line
1884 ;; tricky: note that the regexp matches a blank
1885 ;; line, cuz \n is in the 2nd character class
1886 (and
1887 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1888 (forward-line 1))
1889 ;; no comment, so go back
1890 (goto-char start))))))))
1891
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001892;; ripped from cc-mode
1893(defun py-forward-into-nomenclature (&optional arg)
1894 "Move forward to end of a nomenclature section or word.
1895With arg, to it arg times.
1896
1897A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1898 (interactive "p")
1899 (let ((case-fold-search nil))
1900 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001901 (re-search-forward
1902 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1903 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001904 (while (and (< arg 0)
1905 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001906 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001907 (point-min) 0))
1908 (forward-char 1)
1909 (setq arg (1+ arg)))))
1910 (py-keep-region-active))
1911
1912(defun py-backward-into-nomenclature (&optional arg)
1913 "Move backward to beginning of a nomenclature section or word.
1914With optional ARG, move that many times. If ARG is negative, move
1915forward.
1916
1917A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1918 (interactive "p")
1919 (py-forward-into-nomenclature (- arg))
1920 (py-keep-region-active))
1921
1922
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001923
1924;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001925
1926;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001927;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1928;; out of the right places, along with the keys they're on & current
1929;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930(defun py-dump-help-string (str)
1931 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001932 (let ((locals (buffer-local-variables))
1933 funckind funcname func funcdoc
1934 (start 0) mstart end
1935 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001936 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1937 (setq mstart (match-beginning 0) end (match-end 0)
1938 funckind (substring str (match-beginning 1) (match-end 1))
1939 funcname (substring str (match-beginning 2) (match-end 2))
1940 func (intern funcname))
1941 (princ (substitute-command-keys (substring str start mstart)))
1942 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943 ((equal funckind "c") ; command
1944 (setq funcdoc (documentation func)
1945 keys (concat
1946 "Key(s): "
1947 (mapconcat 'key-description
1948 (where-is-internal func py-mode-map)
1949 ", "))))
1950 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001951 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001952 keys (if (assq func locals)
1953 (concat
1954 "Local/Global values: "
1955 (prin1-to-string (symbol-value func))
1956 " / "
1957 (prin1-to-string (default-value func)))
1958 (concat
1959 "Value: "
1960 (prin1-to-string (symbol-value func))))))
1961 (t ; unexpected
1962 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001963 (princ (format "\n-> %s:\t%s\t%s\n\n"
1964 (if (equal funckind "c") "Command" "Variable")
1965 funcname keys))
1966 (princ funcdoc)
1967 (terpri)
1968 (setq start end))
1969 (princ (substitute-command-keys (substring str start))))
1970 (print-help-return-message)))
1971
1972(defun py-describe-mode ()
1973 "Dump long form of Python-mode docs."
1974 (interactive)
1975 (py-dump-help-string "Major mode for editing Python files.
1976Knows about Python indentation, tokens, comments and continuation lines.
1977Paragraphs are separated by blank lines only.
1978
1979Major sections below begin with the string `@'; specific function and
1980variable docs begin with `->'.
1981
1982@EXECUTING PYTHON CODE
1983
1984\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1985\\[py-execute-region]\tsends the current region
1986\\[py-shell]\tstarts a Python interpreter window; this will be used by
1987\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1988%c:py-execute-buffer
1989%c:py-execute-region
1990%c:py-shell
1991
1992@VARIABLES
1993
1994py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001995py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001996
1997py-python-command\tshell command to invoke Python interpreter
1998py-scroll-process-buffer\talways scroll Python process buffer
1999py-temp-directory\tdirectory used for temp files (if needed)
2000
2001py-beep-if-tab-change\tring the bell if tab-width is changed
2002%v:py-indent-offset
2003%v:py-block-comment-prefix
2004%v:py-python-command
2005%v:py-scroll-process-buffer
2006%v:py-temp-directory
2007%v:py-beep-if-tab-change
2008
2009@KINDS OF LINES
2010
2011Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002012preceding line ends with a backslash that's not part of a comment, or
2013the paren/bracket/brace nesting level at the start of the line is
2014non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015
2016An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002017possibly blanks or tabs), a `comment line' (leftmost non-blank
2018character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002019
2020Comment Lines
2021
2022Although all comment lines are treated alike by Python, Python mode
2023recognizes two kinds that act differently with respect to indentation.
2024
2025An `indenting comment line' is a comment line with a blank, tab or
2026nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002027treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002028indenting comment line will be indented like the comment line. All
2029other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030following the initial `#') are `non-indenting comment lines', and
2031their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002032
2033Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002034whenever possible. Non-indenting comment lines are useful in cases
2035like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002036
2037\ta = b # a very wordy single-line comment that ends up being
2038\t #... continued onto another line
2039
2040\tif a == b:
2041##\t\tprint 'panic!' # old code we've `commented out'
2042\t\treturn a
2043
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002044Since the `#...' and `##' comment lines have a non-whitespace
2045character following the initial `#', Python mode ignores them when
2046computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002047
2048Continuation Lines and Statements
2049
2050The Python-mode commands generally work on statements instead of on
2051individual lines, where a `statement' is a comment or blank line, or a
2052code line and all of its following continuation lines (if any)
2053considered as a single logical unit. The commands in this mode
2054generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002055statement containing point, even if point happens to be in the middle
2056of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002057
2058
2059@INDENTATION
2060
2061Primarily for entering new code:
2062\t\\[indent-for-tab-command]\t indent line appropriately
2063\t\\[py-newline-and-indent]\t insert newline, then indent
2064\t\\[py-delete-char]\t reduce indentation, or delete single character
2065
2066Primarily for reindenting existing code:
2067\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2068\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2069
2070\t\\[py-indent-region]\t reindent region to match its context
2071\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2072\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2073
2074Unlike most programming languages, Python uses indentation, and only
2075indentation, to specify block structure. Hence the indentation supplied
2076automatically by Python-mode is just an educated guess: only you know
2077the block structure you intend, so only you can supply correct
2078indentation.
2079
2080The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2081the indentation of preceding statements. E.g., assuming
2082py-indent-offset is 4, after you enter
2083\tif a > 0: \\[py-newline-and-indent]
2084the cursor will be moved to the position of the `_' (_ is not a
2085character in the file, it's just used here to indicate the location of
2086the cursor):
2087\tif a > 0:
2088\t _
2089If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2090to
2091\tif a > 0:
2092\t c = d
2093\t _
2094Python-mode cannot know whether that's what you intended, or whether
2095\tif a > 0:
2096\t c = d
2097\t_
2098was your intent. In general, Python-mode either reproduces the
2099indentation of the (closest code or indenting-comment) preceding
2100statement, or adds an extra py-indent-offset blanks if the preceding
2101statement has `:' as its last significant (non-whitespace and non-
2102comment) character. If the suggested indentation is too much, use
2103\\[py-delete-char] to reduce it.
2104
2105Continuation lines are given extra indentation. If you don't like the
2106suggested indentation, change it to something you do like, and Python-
2107mode will strive to indent later lines of the statement in the same way.
2108
2109If a line is a continuation line by virtue of being in an unclosed
2110paren/bracket/brace structure (`list', for short), the suggested
2111indentation depends on whether the current line contains the first item
2112in the list. If it does, it's indented py-indent-offset columns beyond
2113the indentation of the line containing the open bracket. If you don't
2114like that, change it by hand. The remaining items in the list will mimic
2115whatever indentation you give to the first item.
2116
2117If a line is a continuation line because the line preceding it ends with
2118a backslash, the third and following lines of the statement inherit their
2119indentation from the line preceding them. The indentation of the second
2120line in the statement depends on the form of the first (base) line: if
2121the base line is an assignment statement with anything more interesting
2122than the backslash following the leftmost assigning `=', the second line
2123is indented two columns beyond that `='. Else it's indented to two
2124columns beyond the leftmost solid chunk of non-whitespace characters on
2125the base line.
2126
2127Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2128repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2129structure you intend.
2130%c:indent-for-tab-command
2131%c:py-newline-and-indent
2132%c:py-delete-char
2133
2134
2135The next function may be handy when editing code you didn't write:
2136%c:py-guess-indent-offset
2137
2138
2139The remaining `indent' functions apply to a region of Python code. They
2140assume the block structure (equals indentation, in Python) of the region
2141is correct, and alter the indentation in various ways while preserving
2142the block structure:
2143%c:py-indent-region
2144%c:py-shift-region-left
2145%c:py-shift-region-right
2146
2147@MARKING & MANIPULATING REGIONS OF CODE
2148
2149\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002150\\[py-mark-def-or-class]\t mark smallest enclosing def
2151\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002152\\[comment-region]\t comment out region of code
2153\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002155%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002156%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002157
2158@MOVING POINT
2159
2160\\[py-previous-statement]\t move to statement preceding point
2161\\[py-next-statement]\t move to statement following point
2162\\[py-goto-block-up]\t move up to start of current block
2163\\[beginning-of-python-def-or-class]\t move to start of def
2164\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2165\\[end-of-python-def-or-class]\t move to end of def
2166\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2167
2168The first two move to one statement beyond the statement that contains
2169point. A numeric prefix argument tells them to move that many
2170statements instead. Blank lines, comment lines, and continuation lines
2171do not count as `statements' for these commands. So, e.g., you can go
2172to the first code statement in a file by entering
2173\t\\[beginning-of-buffer]\t to move to the top of the file
2174\t\\[py-next-statement]\t to skip over initial comments and blank lines
2175Or do `\\[py-previous-statement]' with a huge prefix argument.
2176%c:py-previous-statement
2177%c:py-next-statement
2178%c:py-goto-block-up
2179%c:beginning-of-python-def-or-class
2180%c:end-of-python-def-or-class
2181
2182@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2183
2184`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2185
2186`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2187overall class and def structure of a module.
2188
2189`\\[back-to-indentation]' moves point to a line's first non-blank character.
2190
2191`\\[indent-relative]' is handy for creating odd indentation.
2192
2193@OTHER EMACS HINTS
2194
2195If you don't like the default value of a variable, change its value to
2196whatever you do like by putting a `setq' line in your .emacs file.
2197E.g., to set the indentation increment to 4, put this line in your
2198.emacs:
2199\t(setq py-indent-offset 4)
2200To see the value of a variable, do `\\[describe-variable]' and enter the variable
2201name at the prompt.
2202
2203When entering a key sequence like `C-c C-n', it is not necessary to
2204release the CONTROL key after doing the `C-c' part -- it suffices to
2205press the CONTROL key, press and release `c' (while still holding down
2206CONTROL), press and release `n' (while still holding down CONTROL), &
2207then release CONTROL.
2208
2209Entering Python mode calls with no arguments the value of the variable
2210`python-mode-hook', if that value exists and is not nil; for backward
2211compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2212the Elisp manual for details.
2213
2214Obscure: When python-mode is first loaded, it looks for all bindings
2215to newline-and-indent in the global keymap, and shadows them with
2216local bindings to py-newline-and-indent."))
2217
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002218
2219;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002220(defvar py-parse-state-re
2221 (concat
2222 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2223 "\\|"
2224 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002225
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226;; returns the parse state at point (see parse-partial-sexp docs)
2227(defun py-parse-state ()
2228 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002229 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002230 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002231 (while (not done)
2232 ;; back up to the first preceding line (if any; else start of
2233 ;; buffer) that begins with a popular Python keyword, or a
2234 ;; non- whitespace and non-comment character. These are good
2235 ;; places to start parsing to see whether where we started is
2236 ;; at a non-zero nesting level. It may be slow for people who
2237 ;; write huge code blocks or huge lists ... tough beans.
2238 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002239 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002240 (beginning-of-line)
2241 (save-excursion
2242 (setq pps (parse-partial-sexp (point) here)))
2243 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002244 (setq done (or (zerop ci)
2245 (not (nth 3 pps))
2246 (bobp)))
2247 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002248 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002249
2250;; if point is at a non-zero nesting level, returns the number of the
2251;; character that opens the smallest enclosing unclosed list; else
2252;; returns nil.
2253(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002254 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002255 (if (zerop (car status))
2256 nil ; not in a nest
2257 (car (cdr status))))) ; char# of open bracket
2258
2259;; t iff preceding line ends with backslash that's not in a comment
2260(defun py-backslash-continuation-line-p ()
2261 (save-excursion
2262 (beginning-of-line)
2263 (and
2264 ;; use a cheap test first to avoid the regexp if possible
2265 ;; use 'eq' because char-after may return nil
2266 (eq (char-after (- (point) 2)) ?\\ )
2267 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002268 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002269 (looking-at py-continued-re))))
2270
2271;; t iff current line is a continuation line
2272(defun py-continuation-line-p ()
2273 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002274 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002275 (or (py-backslash-continuation-line-p)
2276 (py-nesting-level))))
2277
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002278;; go to initial line of current statement; usually this is the line
2279;; we're on, but if we're on the 2nd or following lines of a
2280;; continuation block, we need to go up to the first line of the
2281;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002282;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002283;; Tricky: We want to avoid quadratic-time behavior for long continued
2284;; blocks, whether of the backslash or open-bracket varieties, or a
2285;; mix of the two. The following manages to do that in the usual
2286;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002287(defun py-goto-initial-line ()
2288 (let ( open-bracket-pos )
2289 (while (py-continuation-line-p)
2290 (beginning-of-line)
2291 (if (py-backslash-continuation-line-p)
2292 (while (py-backslash-continuation-line-p)
2293 (forward-line -1))
2294 ;; else zip out of nested brackets/braces/parens
2295 (while (setq open-bracket-pos (py-nesting-level))
2296 (goto-char open-bracket-pos)))))
2297 (beginning-of-line))
2298
2299;; go to point right beyond final line of current statement; usually
2300;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301;; statement we need to skip over the continuation lines. Tricky:
2302;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002303(defun py-goto-beyond-final-line ()
2304 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002305 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306 (while (and (py-continuation-line-p)
2307 (not (eobp)))
2308 ;; skip over the backslash flavor
2309 (while (and (py-backslash-continuation-line-p)
2310 (not (eobp)))
2311 (forward-line 1))
2312 ;; if in nest, zip to the end of the nest
2313 (setq state (py-parse-state))
2314 (if (and (not (zerop (car state)))
2315 (not (eobp)))
2316 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002317 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002318 (forward-line 1))))))
2319
2320;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002321;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322(defun py-statement-opens-block-p ()
2323 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002324 (let ((start (point))
2325 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2326 (searching t)
2327 (answer nil)
2328 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329 (goto-char start)
2330 (while searching
2331 ;; look for a colon with nothing after it except whitespace, and
2332 ;; maybe a comment
2333 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2334 finish t)
2335 (if (eq (point) finish) ; note: no `else' clause; just
2336 ; keep searching if we're not at
2337 ; the end yet
2338 ;; sure looks like it opens a block -- but it might
2339 ;; be in a comment
2340 (progn
2341 (setq searching nil) ; search is done either way
2342 (setq state (parse-partial-sexp start
2343 (match-beginning 0)))
2344 (setq answer (not (nth 4 state)))))
2345 ;; search failed: couldn't find another interesting colon
2346 (setq searching nil)))
2347 answer)))
2348
Barry Warsawf831d811996-07-31 20:42:59 +00002349(defun py-statement-closes-block-p ()
2350 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002351 ;; starts with `return', `raise', `break', `continue', and `pass'.
2352 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002353 (let ((here (point)))
2354 (back-to-indentation)
2355 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002356 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002357 (goto-char here))))
2358
Barry Warsaw7ae77681994-12-12 20:38:05 +00002359;; go to point right beyond final line of block begun by the current
2360;; line. This is the same as where py-goto-beyond-final-line goes
2361;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002362;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002363(defun py-goto-beyond-block ()
2364 (if (py-statement-opens-block-p)
2365 (py-mark-block nil 'just-move)
2366 (py-goto-beyond-final-line)))
2367
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002368;; go to start of first statement (not blank or comment or
2369;; continuation line) at or preceding point. returns t if there is
2370;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002371(defun py-goto-statement-at-or-above ()
2372 (py-goto-initial-line)
2373 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002374 ;; skip back over blank & comment lines
2375 ;; note: will skip a blank or comment line that happens to be
2376 ;; a continuation line too
2377 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2378 (progn (py-goto-initial-line) t)
2379 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002380 t))
2381
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002382;; go to start of first statement (not blank or comment or
2383;; continuation line) following the statement containing point returns
2384;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002385(defun py-goto-statement-below ()
2386 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002387 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002388 (py-goto-beyond-final-line)
2389 (while (and
2390 (looking-at py-blank-or-comment-re)
2391 (not (eobp)))
2392 (forward-line 1))
2393 (if (eobp)
2394 (progn (goto-char start) nil)
2395 t)))
2396
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002397;; go to start of statement, at or preceding point, starting with
2398;; keyword KEY. Skips blank lines and non-indenting comments upward
2399;; first. If that statement starts with KEY, done, else go back to
2400;; first enclosing block starting with KEY. If successful, leaves
2401;; point at the start of the KEY line & returns t. Else leaves point
2402;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002403(defun py-go-up-tree-to-keyword (key)
2404 ;; skip blanks and non-indenting #
2405 (py-goto-initial-line)
2406 (while (and
2407 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2408 (zerop (forward-line -1))) ; go back
2409 nil)
2410 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002411 (let* ((re (concat "[ \t]*" key "\\b"))
2412 (case-fold-search nil) ; let* so looking-at sees this
2413 (found (looking-at re))
2414 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002415 (while (not (or found dead))
2416 (condition-case nil ; in case no enclosing block
2417 (py-goto-block-up 'no-mark)
2418 (error (setq dead t)))
2419 (or dead (setq found (looking-at re))))
2420 (beginning-of-line)
2421 found))
2422
2423;; return string in buffer from start of indentation to end of line;
2424;; prefix "..." if leading whitespace was skipped
2425(defun py-suck-up-leading-text ()
2426 (save-excursion
2427 (back-to-indentation)
2428 (concat
2429 (if (bolp) "" "...")
2430 (buffer-substring (point) (progn (end-of-line) (point))))))
2431
2432;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2433;; as a Lisp symbol; return nil if none
2434(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002435 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002436 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2437 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2438 nil)))
2439
Barry Warsaw7ae77681994-12-12 20:38:05 +00002440(defun py-delete-file-silently (fname)
2441 (condition-case nil
2442 (delete-file fname)
2443 (error nil)))
2444
2445(defun py-kill-emacs-hook ()
2446 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002447 (py-safe (while py-file-queue
2448 (py-delete-file-silently (car py-file-queue))
2449 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002450
Barry Warsawb3e81d51996-09-04 15:12:42 +00002451(defun py-current-defun ()
2452 ;; tell add-log.el how to find the current function/method/variable
2453 (save-excursion
2454 (if (re-search-backward py-defun-start-re nil t)
2455 (or (match-string 3)
2456 (let ((method (match-string 2)))
2457 (if (and (not (zerop (length (match-string 1))))
2458 (re-search-backward py-class-start-re nil t))
2459 (concat (match-string 1) "." method)
2460 method)))
2461 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002462
2463
Barry Warsawfec75d61995-07-05 23:26:15 +00002464(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002465 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002466
Barry Warsaw850437a1995-03-08 21:50:28 +00002467(defun py-version ()
2468 "Echo the current version of `python-mode' in the minibuffer."
2469 (interactive)
2470 (message "Using `python-mode' version %s" py-version)
2471 (py-keep-region-active))
2472
2473;; only works under Emacs 19
2474;(eval-when-compile
2475; (require 'reporter))
2476
2477(defun py-submit-bug-report (enhancement-p)
2478 "Submit via mail a bug report on `python-mode'.
2479With \\[universal-argument] just submit an enhancement request."
2480 (interactive
2481 (list (not (y-or-n-p
2482 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002483 (let ((reporter-prompt-for-summary-p (if enhancement-p
2484 "(Very) brief summary: "
2485 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002486 (require 'reporter)
2487 (reporter-submit-bug-report
2488 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002489 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002490 ;; varlist
2491 (if enhancement-p nil
2492 '(py-python-command
2493 py-indent-offset
2494 py-block-comment-prefix
2495 py-scroll-process-buffer
2496 py-temp-directory
2497 py-beep-if-tab-change))
2498 nil ;pre-hooks
2499 nil ;post-hooks
2500 "Dear Barry,") ;salutation
2501 (if enhancement-p nil
2502 (set-mark (point))
2503 (insert
2504"Please replace this text with a sufficiently large code sample\n\
2505and an exact recipe so that I can reproduce your problem. Failure\n\
2506to do so may mean a greater delay in fixing your bug.\n\n")
2507 (exchange-point-and-mark)
2508 (py-keep-region-active))))
2509
2510
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002511;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002512(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002513
2514
2515
2516(provide 'python-mode)
2517;;; python-mode.el ends here