blob: 2625646edde004bcaef34939d16a54f5219bb714 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsawc72c11c1997-08-09 06:42:08 +000011(defconst py-version "3.0"
12 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsawaffc0ca1997-11-03 16:59:38 +000027;; Note: this version of python-mode.el is no longer compatible with
28;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
29;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
30;; you may need to acquire the Custom library.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
Barry Warsawaffc0ca1997-11-03 16:59:38 +000032;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
33;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000034;; but it is compatible with 19.34 and the current 20 series Emacsen.
35;; By default, in XEmacs when you visit a .py file, it is put in
36;; Python mode. In Emacs, you need to add the following to your
37;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000039;; (autoload 'python-mode "python-mode" "Python editing mode." t)
40;; (setq auto-mode-alist
41;; (cons '("\\.py$" . python-mode) auto-mode-alist))
42;; (setq interpreter-mode-alist
43;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000044;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000045;; Assuming python-mode.el is on your load-path, it will be invoked
46;; when you visit a .py file, or a file with a first line that looks
47;; like:
48;;
49;; #! /usr/bin/env python
50
Barry Warsaw44b72201996-07-05 20:11:35 +000051;; If you want font-lock support for Python source code (a.k.a. syntax
52;; coloring, highlighting), add this to your .emacs file:
53;;
54;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000055;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000056;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000057
Barry Warsawaffc0ca1997-11-03 16:59:38 +000058;; To submit bug reports, use C-c C-b. Please include a complete, but
59;; concise code sample and a recipe for reproducing the bug. Send
60;; suggestions and other comments to python-mode@python.org.
61
62;; When in a Python mode buffer, do a C-h m for more help. It's
63;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; Here's a brief to do list:
66;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000067;; - Better integration with gud-mode for debugging.
68;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000069;; - possibly force indent-tabs-mode == nil, and add a
70;; write-file-hooks that runs untabify on the whole buffer (to work
71;; around potential tab/space mismatch problems). In practice this
72;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000073;; - have py-execute-region on indented code act as if the region is
74;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000075;; - Add a py-goto-error or some such that would scan an exception in
76;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsaw7b0f5681995-03-08 21:33:04 +000078;;; Code:
79
Barry Warsawc72c11c1997-08-09 06:42:08 +000080(require 'custom)
81
Barry Warsaw7b0f5681995-03-08 21:33:04 +000082
83;; user definable variables
84;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000085
Barry Warsawc72c11c1997-08-09 06:42:08 +000086(defgroup python nil
87 "Support for the Python programming language, <http://www.python.org/>"
88 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000089
Barry Warsawc72c11c1997-08-09 06:42:08 +000090(defcustom py-python-command "python"
91 "*Shell command used to start Python interpreter."
92 :type 'string
93 :group 'python)
94
95(defcustom py-indent-offset 4
96 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +000098when you're editing someone else's Python code."
99 :type 'integer
100 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000101
Barry Warsawc72c11c1997-08-09 06:42:08 +0000102(defcustom py-align-multiline-strings-p t
103 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000104When this flag is non-nil, continuation lines are lined up under the
105preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000106lines are aligned to column zero."
107 :type '(choice (const :tag "Align under preceding line" t)
108 (const :tag "Align to column zero" nil))
109 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000110
Barry Warsawc72c11c1997-08-09 06:42:08 +0000111(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000112 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000113This should follow the convention for non-indenting comment lines so
114that the indentation commands won't get confused (i.e., the string
115should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000116`...' is arbitrary)."
117 :type 'string
118 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000119
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000121 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000122
Barry Warsaw6d627751996-03-06 18:41:38 +0000123When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000125
126When t, lines that begin with a single `#' are a hint to subsequent
127line indentation. If the previous line is such a comment line (as
128opposed to one that starts with `py-block-comment-prefix'), then it's
129indentation is used as a hint for this line's indentation. Lines that
130begin with `py-block-comment-prefix' are ignored for indentation
131purposes.
132
133When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000134indentation hints, unless the comment character is in column zero."
135 :type '(choice
136 (const :tag "Skip all comment lines (fast)" nil)
137 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000138 (const :tag "Single # `sets' indentation except at column zero"
139 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140 )
141 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000142
Barry Warsawc72c11c1997-08-09 06:42:08 +0000143(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000144 "*Scroll Python process buffer as output arrives.
145If nil, the Python process buffer acts, with respect to scrolling, like
146Shell-mode buffers normally act. This is surprisingly complicated and
147so won't be explained here; in fact, you can't get the whole story
148without studying the Emacs C code.
149
150If non-nil, the behavior is different in two respects (which are
151slightly inaccurate in the interest of brevity):
152
153 - If the buffer is in a window, and you left point at its end, the
154 window will scroll as new output arrives, and point will move to the
155 buffer's end, even if the window is not the selected window (that
156 being the one the cursor is in). The usual behavior for shell-mode
157 windows is not to scroll, and to leave point where it was, if the
158 buffer is in a window other than the selected window.
159
160 - If the buffer is not visible in any window, and you left point at
161 its end, the buffer will be popped into a window as soon as more
162 output arrives. This is handy if you have a long-running
163 computation and don't want to tie up screen area waiting for the
164 output. The usual behavior for a shell-mode buffer is to stay
165 invisible until you explicitly visit it.
166
167Note the `and if you left point at its end' clauses in both of the
168above: you can `turn off' the special behaviors while output is in
169progress, by visiting the Python buffer and moving point to anywhere
170besides the end. Then the buffer won't scroll, point will remain where
171you leave it, and if you hide the buffer it will stay hidden until you
172visit it again. You can enable and disable the special behaviors as
173often as you like, while output is in progress, by (respectively) moving
174point to, or away from, the end of the buffer.
175
176Warning: If you expect a large amount of output, you'll probably be
177happier setting this option to nil.
178
179Obscure: `End of buffer' above should really say `at or beyond the
180process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000181told <grin>."
182 :type 'boolean
183 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000184
Barry Warsaw516b6201997-08-09 06:43:20 +0000185(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000186 (let ((ok '(lambda (x)
187 (and x
188 (setq x (expand-file-name x)) ; always true
189 (file-directory-p x)
190 (file-writable-p x)
191 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000192 (or (funcall ok (getenv "TMPDIR"))
193 (funcall ok "/usr/tmp")
194 (funcall ok "/tmp")
195 (funcall ok ".")
196 (error
197 "Couldn't find a usable temp directory -- set py-temp-directory")))
198 "*Directory used for temp files created by a *Python* process.
199By default, the first directory from this list that exists and that you
200can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201/usr/tmp, /tmp, or the current directory."
202 :type 'string
203 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000204
Barry Warsaw516b6201997-08-09 06:43:20 +0000205(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000206 "*Ring the bell if tab-width is changed.
207If a comment of the form
208
209 \t# vi:set tabsize=<number>:
210
211is found before the first code line when the file is entered, and the
212current value of (the general Emacs variable) `tab-width' does not
213equal <number>, `tab-width' is set to <number>, a message saying so is
214displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000215the Emacs bell is also rung as a warning."
216 :type 'boolean
217 :group 'python)
218
219
220;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
221;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
222
Barry Warsawc12c62e1997-09-04 04:18:07 +0000223(defconst py-emacs-features ()
224 "A list of features extant in the Emacs you are using.
225There are many flavors of Emacs out there, each with different
226features supporting those needed by CC Mode. Here's the current
227supported list, along with the values for this variable:
228
229 XEmacs 19: ()
230 XEmacs 20: ()
231 Emacs 19: ()
232")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000233
Barry Warsawfb07f401997-02-24 03:37:22 +0000234(defvar python-font-lock-keywords
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000235 (let* ((keywords '("and" "assert" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000236 "continue" "def" "del" "elif"
237 "else:" "except" "except:" "exec"
238 "finally:" "for" "from" "global"
239 "if" "import" "in" "is"
240 "lambda" "not" "or" "pass"
241 "print" "raise" "return" "try:"
242 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000243 ))
244 (kwregex (mapconcat 'identity keywords "\\|")))
245 (list
246 ;; keywords not at beginning of line
247 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
248 ;; keywords at beginning of line. i don't think regexps are
249 ;; powerful enough to handle these two cases in one regexp.
250 ;; prove me wrong!
251 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
252 ;; classes
253 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
254 1 font-lock-type-face)
255 ;; functions
256 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
257 1 font-lock-function-name-face)
258 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000259 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000260(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
261
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000262
Barry Warsaw81437461996-08-01 19:48:02 +0000263(defvar imenu-example--python-show-method-args-p nil
264 "*Controls echoing of arguments of functions & methods in the imenu buffer.
265When non-nil, arguments are printed.")
266
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000267(make-variable-buffer-local 'py-indent-offset)
268
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269;; have to bind py-file-queue before installing the kill-emacs hook
270(defvar py-file-queue nil
271 "Queue of Python temp files awaiting execution.
272Currently-active file is at the head of the list.")
273
Barry Warsawc72c11c1997-08-09 06:42:08 +0000274(defvar py-delete-function 'backward-delete-char-untabify
275 "*Function called by `py-delete-char' when deleting characters.")
276
277(defvar py-backspace-function 'backward-delete-char-untabify
278 "*Function called by `py-backspace-command' when deleting characters.")
279
280
281;; Constants
282
283;; Regexp matching a Python string literal
284(defconst py-stringlit-re
285 (concat
286 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
287 "\\|" ; or
288 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
289
290;; Regexp matching Python lines that are continued via backslash.
291;; This is tricky because a trailing backslash does not mean
292;; continuation if it's in a comment
293(defconst py-continued-re
294 (concat
295 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
296 "\\\\$"))
297
298;; Regexp matching blank or comment lines.
299(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
300
301;; Regexp matching clauses to be outdented one level.
302(defconst py-outdent-re
303 (concat "\\(" (mapconcat 'identity
304 '("else:"
305 "except\\(\\s +.*\\)?:"
306 "finally:"
307 "elif\\s +.*:")
308 "\\|")
309 "\\)"))
310
311
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000312;; Regexp matching keywords which typically close a block
313(defconst py-block-closing-keywords-re
314 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
315
Barry Warsawc72c11c1997-08-09 06:42:08 +0000316;; Regexp matching lines to not outdent after.
317(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000318 (concat
319 "\\("
320 (mapconcat 'identity
321 (list "try:"
322 "except\\(\\s +.*\\)?:"
323 "while\\s +.*:"
324 "for\\s +.*:"
325 "if\\s +.*:"
326 "elif\\s +.*:"
327 (concat py-block-closing-keywords-re "[ \t\n]")
328 )
329 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000330 "\\)"))
331
332;; Regexp matching a function, method or variable assignment. If you
333;; change this, you probably have to change `py-current-defun' as
334;; well. This is only used by `py-current-defun' to find the name for
335;; add-log.el.
336(defvar py-defun-start-re
337 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
338
339;; Regexp for finding a class name. If you change this, you probably
340;; have to change `py-current-defun' as well. This is only used by
341;; `py-current-defun' to find the name for add-log.el.
342(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
343
344
345
346;; Utilities
347
348(defmacro py-safe (&rest body)
349 ;; safely execute BODY, return nil if an error occurred
350 (` (condition-case nil
351 (progn (,@ body))
352 (error nil))))
353
354(defsubst py-keep-region-active ()
355 ;; Do whatever is necessary to keep the region active in XEmacs.
356 ;; Ignore byte-compiler warnings you might see. Also note that
357 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
358 ;; to take explicit action.
359 (and (boundp 'zmacs-region-stays)
360 (setq zmacs-region-stays t)))
361
362
363;; Major mode boilerplate
364
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365;; define a mode-specific abbrev table for those who use such things
366(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000367 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000368(define-abbrev-table 'python-mode-abbrev-table nil)
369
Barry Warsaw7ae77681994-12-12 20:38:05 +0000370(defvar python-mode-hook nil
371 "*Hook called by `python-mode'.")
372
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000373;; in previous version of python-mode.el, the hook was incorrectly
374;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000375(and (fboundp 'make-obsolete-variable)
376 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
377
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378(defvar py-mode-map ()
379 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000380(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000381 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000382 (setq py-mode-map (make-sparse-keymap))
383
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000384 ;; shadow global bindings for newline-and-indent w/ the py- version.
385 ;; BAW - this is extremely bad form, but I'm not going to change it
386 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387 (mapcar (function (lambda (key)
388 (define-key
389 py-mode-map key 'py-newline-and-indent)))
390 (where-is-internal 'newline-and-indent))
391
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000392 ;; BAW - you could do it this way, but its not considered proper
393 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000394 (mapcar (function
395 (lambda (x)
396 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000397 '((":" . py-electric-colon)
398 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399 ("\C-c|" . py-execute-region)
400 ("\C-c!" . py-shell)
401 ("\177" . py-delete-char)
402 ("\n" . py-newline-and-indent)
403 ("\C-c:" . py-guess-indent-offset)
404 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000405 ("\C-c\C-l" . py-shift-region-left)
406 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000407 ("\C-c<" . py-shift-region-left)
408 ("\C-c>" . py-shift-region-right)
409 ("\C-c\C-n" . py-next-statement)
410 ("\C-c\C-p" . py-previous-statement)
411 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000412 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000413 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 ("\C-c?" . py-describe-mode)
415 ("\C-c\C-hm" . py-describe-mode)
416 ("\e\C-a" . beginning-of-python-def-or-class)
417 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000418 ( "\e\C-h" . mark-python-def-or-class)))
419 ;; should do all keybindings this way
420 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
421 (define-key py-mode-map "\C-c\C-v" 'py-version)
422 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000423
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000424(defvar py-mode-syntax-table nil
425 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000426(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000427 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000428 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000429 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
430 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
431 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
432 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
433 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
434 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
435 ;; Add operator symbols misassigned in the std table
436 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
437 (modify-syntax-entry ?\% "." py-mode-syntax-table)
438 (modify-syntax-entry ?\& "." py-mode-syntax-table)
439 (modify-syntax-entry ?\* "." py-mode-syntax-table)
440 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
441 (modify-syntax-entry ?\- "." py-mode-syntax-table)
442 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
443 (modify-syntax-entry ?\< "." py-mode-syntax-table)
444 (modify-syntax-entry ?\= "." py-mode-syntax-table)
445 (modify-syntax-entry ?\> "." py-mode-syntax-table)
446 (modify-syntax-entry ?\| "." py-mode-syntax-table)
447 ;; For historical reasons, underscore is word class instead of
448 ;; symbol class. GNU conventions say it should be symbol class, but
449 ;; there's a natural conflict between what major mode authors want
450 ;; and what users expect from `forward-word' and `backward-word'.
451 ;; Guido and I have hashed this out and have decided to keep
452 ;; underscore in word class. If you're tempted to change it, try
453 ;; binding M-f and M-b to py-forward-into-nomenclature and
454 ;; py-backward-into-nomenclature instead.
455 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
456 ;; Both single quote and double quote are string delimiters
457 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
458 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
459 ;; backquote is open and close paren
460 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
461 ;; comment delimiters
462 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
463 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
464 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000465
Barry Warsawb3e81d51996-09-04 15:12:42 +0000466
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000467
Barry Warsaw42f707f1996-07-29 21:05:05 +0000468;; Menu definitions, only relevent if you have the easymenu.el package
469;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000470(defvar py-menu nil
471 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000472This menu will get created automatically if you have the `easymenu'
473package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000474
Barry Warsawc72c11c1997-08-09 06:42:08 +0000475(and (py-safe (require 'easymenu) t)
476 (easy-menu-define
477 py-menu py-mode-map "Python Mode menu"
478 '("Python"
479 ["Comment Out Region" py-comment-region (mark)]
480 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
481 "-"
482 ["Mark current block" py-mark-block t]
483 ["Mark current def" mark-python-def-or-class t]
484 ["Mark current class" (mark-python-def-or-class t) t]
485 "-"
486 ["Shift region left" py-shift-region-left (mark)]
487 ["Shift region right" py-shift-region-right (mark)]
488 "-"
489 ["Execute buffer" py-execute-buffer t]
490 ["Execute region" py-execute-region (mark)]
491 ["Start interpreter..." py-shell t]
492 "-"
493 ["Go to start of block" py-goto-block-up t]
494 ["Go to start of class" (beginning-of-python-def-or-class t) t]
495 ["Move to end of class" (end-of-python-def-or-class t) t]
496 ["Move to start of def" beginning-of-python-def-or-class t]
497 ["Move to end of def" end-of-python-def-or-class t]
498 "-"
499 ["Describe mode" py-describe-mode t]
500 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000501
Barry Warsaw81437461996-08-01 19:48:02 +0000502
503
504;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
505(defvar imenu-example--python-class-regexp
506 (concat ; <<classes>>
507 "\\(" ;
508 "^[ \t]*" ; newline and maybe whitespace
509 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
510 ; possibly multiple superclasses
511 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
512 "[ \t]*:" ; and the final :
513 "\\)" ; >>classes<<
514 )
515 "Regexp for Python classes for use with the imenu package."
516 )
517
518(defvar imenu-example--python-method-regexp
519 (concat ; <<methods and functions>>
520 "\\(" ;
521 "^[ \t]*" ; new line and maybe whitespace
522 "\\(def[ \t]+" ; function definitions start with def
523 "\\([a-zA-Z0-9_]+\\)" ; name is here
524 ; function arguments...
525 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
526 "\\)" ; end of def
527 "[ \t]*:" ; and then the :
528 "\\)" ; >>methods and functions<<
529 )
530 "Regexp for Python methods/functions for use with the imenu package."
531 )
532
533(defvar imenu-example--python-method-no-arg-parens '(2 8)
534 "Indicies into groups of the Python regexp for use with imenu.
535
536Using these values will result in smaller imenu lists, as arguments to
537functions are not listed.
538
539See the variable `imenu-example--python-show-method-args-p' for more
540information.")
541
542(defvar imenu-example--python-method-arg-parens '(2 7)
543 "Indicies into groups of the Python regexp for use with imenu.
544Using these values will result in large imenu lists, as arguments to
545functions are listed.
546
547See the variable `imenu-example--python-show-method-args-p' for more
548information.")
549
550;; Note that in this format, this variable can still be used with the
551;; imenu--generic-function. Otherwise, there is no real reason to have
552;; it.
553(defvar imenu-example--generic-python-expression
554 (cons
555 (concat
556 imenu-example--python-class-regexp
557 "\\|" ; or...
558 imenu-example--python-method-regexp
559 )
560 imenu-example--python-method-no-arg-parens)
561 "Generic Python expression which may be used directly with imenu.
562Used by setting the variable `imenu-generic-expression' to this value.
563Also, see the function \\[imenu-example--create-python-index] for a
564better alternative for finding the index.")
565
566;; These next two variables are used when searching for the python
567;; class/definitions. Just saving some time in accessing the
568;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000569(defvar imenu-example--python-generic-regexp nil)
570(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000571
572
573;;;###autoload
574(eval-when-compile
575 ;; Imenu isn't used in XEmacs, so just ignore load errors
576 (condition-case ()
577 (progn
578 (require 'cl)
579 (require 'imenu))
580 (error nil)))
581
582(defun imenu-example--create-python-index ()
583 "Python interface function for imenu package.
584Finds all python classes and functions/methods. Calls function
585\\[imenu-example--create-python-index-engine]. See that function for
586the details of how this works."
587 (setq imenu-example--python-generic-regexp
588 (car imenu-example--generic-python-expression))
589 (setq imenu-example--python-generic-parens
590 (if imenu-example--python-show-method-args-p
591 imenu-example--python-method-arg-parens
592 imenu-example--python-method-no-arg-parens))
593 (goto-char (point-min))
594 (imenu-example--create-python-index-engine nil))
595
596(defun imenu-example--create-python-index-engine (&optional start-indent)
597 "Function for finding imenu definitions in Python.
598
599Finds all definitions (classes, methods, or functions) in a Python
600file for the imenu package.
601
602Returns a possibly nested alist of the form
603
604 (INDEX-NAME . INDEX-POSITION)
605
606The second element of the alist may be an alist, producing a nested
607list as in
608
609 (INDEX-NAME . INDEX-ALIST)
610
611This function should not be called directly, as it calls itself
612recursively and requires some setup. Rather this is the engine for
613the function \\[imenu-example--create-python-index].
614
615It works recursively by looking for all definitions at the current
616indention level. When it finds one, it adds it to the alist. If it
617finds a definition at a greater indentation level, it removes the
618previous definition from the alist. In it's place it adds all
619definitions found at the next indentation level. When it finds a
620definition that is less indented then the current level, it retuns the
621alist it has created thus far.
622
623The optional argument START-INDENT indicates the starting indentation
624at which to continue looking for Python classes, methods, or
625functions. If this is not supplied, the function uses the indentation
626of the first definition found."
627 (let ((index-alist '())
628 (sub-method-alist '())
629 looking-p
630 def-name prev-name
631 cur-indent def-pos
632 (class-paren (first imenu-example--python-generic-parens))
633 (def-paren (second imenu-example--python-generic-parens)))
634 (setq looking-p
635 (re-search-forward imenu-example--python-generic-regexp
636 (point-max) t))
637 (while looking-p
638 (save-excursion
639 ;; used to set def-name to this value but generic-extract-name is
640 ;; new to imenu-1.14. this way it still works with imenu-1.11
641 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
642 (let ((cur-paren (if (match-beginning class-paren)
643 class-paren def-paren)))
644 (setq def-name
645 (buffer-substring (match-beginning cur-paren)
646 (match-end cur-paren))))
647 (beginning-of-line)
648 (setq cur-indent (current-indentation)))
649
650 ;; HACK: want to go to the next correct definition location. we
651 ;; explicitly list them here. would be better to have them in a
652 ;; list.
653 (setq def-pos
654 (or (match-beginning class-paren)
655 (match-beginning def-paren)))
656
657 ;; if we don't have a starting indent level, take this one
658 (or start-indent
659 (setq start-indent cur-indent))
660
661 ;; if we don't have class name yet, take this one
662 (or prev-name
663 (setq prev-name def-name))
664
665 ;; what level is the next definition on? must be same, deeper
666 ;; or shallower indentation
667 (cond
668 ;; at the same indent level, add it to the list...
669 ((= start-indent cur-indent)
670
671 ;; if we don't have push, use the following...
672 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
673 (push (cons def-name def-pos) index-alist))
674
675 ;; deeper indented expression, recur...
676 ((< start-indent cur-indent)
677
678 ;; the point is currently on the expression we're supposed to
679 ;; start on, so go back to the last expression. The recursive
680 ;; call will find this place again and add it to the correct
681 ;; list
682 (re-search-backward imenu-example--python-generic-regexp
683 (point-min) 'move)
684 (setq sub-method-alist (imenu-example--create-python-index-engine
685 cur-indent))
686
687 (if sub-method-alist
688 ;; we put the last element on the index-alist on the start
689 ;; of the submethod alist so the user can still get to it.
690 (let ((save-elmt (pop index-alist)))
691 (push (cons (imenu-create-submenu-name prev-name)
692 (cons save-elmt sub-method-alist))
693 index-alist))))
694
695 ;; found less indented expression, we're done.
696 (t
697 (setq looking-p nil)
698 (re-search-backward imenu-example--python-generic-regexp
699 (point-min) t)))
700 (setq prev-name def-name)
701 (and looking-p
702 (setq looking-p
703 (re-search-forward imenu-example--python-generic-regexp
704 (point-max) 'move))))
705 (nreverse index-alist)))
706
Barry Warsaw42f707f1996-07-29 21:05:05 +0000707
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000709(defun python-mode ()
710 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000711To submit a problem report, enter `\\[py-submit-bug-report]' from a
712`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
713documentation. To see what version of `python-mode' you are running,
714enter `\\[py-version]'.
715
716This mode knows about Python indentation, tokens, comments and
717continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000718
719COMMANDS
720\\{py-mode-map}
721VARIABLES
722
Barry Warsaw42f707f1996-07-29 21:05:05 +0000723py-indent-offset\t\tindentation increment
724py-block-comment-prefix\t\tcomment string used by comment-region
725py-python-command\t\tshell command to invoke Python interpreter
726py-scroll-process-buffer\t\talways scroll Python process buffer
727py-temp-directory\t\tdirectory used for temp files (if needed)
728py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000729 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000730 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000731 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000732 (make-local-variable 'font-lock-defaults)
733 (make-local-variable 'paragraph-separate)
734 (make-local-variable 'paragraph-start)
735 (make-local-variable 'require-final-newline)
736 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000737 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000738 (make-local-variable 'comment-start-skip)
739 (make-local-variable 'comment-column)
740 (make-local-variable 'indent-region-function)
741 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000742 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000743 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000745 (setq major-mode 'python-mode
746 mode-name "Python"
747 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000748 paragraph-separate "^[ \t]*$"
749 paragraph-start "^[ \t]*$"
750 require-final-newline t
751 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000752 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000753 comment-start-skip "# *"
754 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000755 indent-region-function 'py-indent-region
756 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000757 ;; tell add-log.el how to find the current function/method/variable
758 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000759 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000760 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000761 ;; add the menu
762 (if py-menu
763 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000764 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000765 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000766 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000767 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000768 ;;
769 ;; not sure where the magic comment has to be; to save time
770 ;; searching for a rarity, we give up if it's not found prior to the
771 ;; first executable statement.
772 ;;
773 ;; BAW - on first glance, this seems like complete hackery. Why was
774 ;; this necessary, and is it still necessary?
775 (let ((case-fold-search nil)
776 (start (point))
777 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000778 (if (re-search-forward
779 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
780 (prog2 (py-next-statement 1) (point) (goto-char 1))
781 t)
782 (progn
783 (setq new-tab-width
784 (string-to-int
785 (buffer-substring (match-beginning 1) (match-end 1))))
786 (if (= tab-width new-tab-width)
787 nil
788 (setq tab-width new-tab-width)
789 (message "Caution: tab-width changed to %d" new-tab-width)
790 (if py-beep-if-tab-change (beep)))))
791 (goto-char start))
792
Barry Warsaw755c6711996-08-01 20:02:55 +0000793 ;; install imenu
794 (setq imenu-create-index-function
795 (function imenu-example--create-python-index))
796 (if (fboundp 'imenu-add-to-menubar)
797 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
798
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000799 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000800 (if python-mode-hook
801 (run-hooks 'python-mode-hook)
802 (run-hooks 'py-mode-hook)))
803
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000804
Barry Warsawb91b7431995-03-14 15:55:20 +0000805;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000806(defun py-outdent-p ()
807 ;; returns non-nil if the current line should outdent one level
808 (save-excursion
809 (and (progn (back-to-indentation)
810 (looking-at py-outdent-re))
811 (progn (backward-to-indentation 1)
812 (while (or (looking-at py-blank-or-comment-re)
813 (bobp))
814 (backward-to-indentation 1))
815 (not (looking-at py-no-outdent-re)))
816 )))
817
Barry Warsawb91b7431995-03-14 15:55:20 +0000818(defun py-electric-colon (arg)
819 "Insert a colon.
820In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000821argument is provided, that many colons are inserted non-electrically.
822Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000823 (interactive "P")
824 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000825 ;; are we in a string or comment?
826 (if (save-excursion
827 (let ((pps (parse-partial-sexp (save-excursion
828 (beginning-of-python-def-or-class)
829 (point))
830 (point))))
831 (not (or (nth 3 pps) (nth 4 pps)))))
832 (save-excursion
833 (let ((here (point))
834 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000835 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000836 (if (and (not arg)
837 (py-outdent-p)
838 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000839 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000840 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000841 )
842 (setq outdent py-indent-offset))
843 ;; Don't indent, only outdent. This assumes that any lines that
844 ;; are already outdented relative to py-compute-indentation were
845 ;; put there on purpose. Its highly annoying to have `:' indent
846 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
847 ;; there a better way to determine this???
848 (if (< (current-indentation) indent) nil
849 (goto-char here)
850 (beginning-of-line)
851 (delete-horizontal-space)
852 (indent-to (- indent outdent))
853 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000854
855
Barry Warsawa97a3f31997-11-04 18:47:06 +0000856;; Python subprocess utilities and filters
857(defun py-execute-file (proc filename)
858 ;; Send a properly formatted execfile('FILENAME') to the underlying
859 ;; Python interpreter process FILENAME. Make that process's buffer
860 ;; visible and force display. Also make comint believe the user
861 ;; typed this string so that kill-output-from-shell does The Right
862 ;; Thing.
863 (let ((curbuf (current-buffer))
864 (procbuf (process-buffer proc))
865 (comint-scroll-to-bottom-on-output t)
866 (msg (format "## working on region in file %s...\n" filename))
867 (cmd (format "execfile('%s')\n" filename)))
868 (unwind-protect
869 (progn
870 (set-buffer procbuf)
871 (goto-char (point-max))
872 (move-marker (process-mark proc) (point))
873 (funcall (process-filter proc) proc msg))
874 (set-buffer curbuf))
875 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876
877(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000878 (let ((curbuf (current-buffer))
879 (pbuf (process-buffer pyproc))
880 (pmark (process-mark pyproc))
881 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882 ;; make sure we switch to a different buffer at least once. if we
883 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000884 ;; window, and point is before the end, and lots of output is
885 ;; coming at a fast pace, then (a) simple cursor-movement commands
886 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
887 ;; to have a visible effect (the window just doesn't get updated,
888 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
889 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000890 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000891 ;; #b makes no sense to me at all. #a almost makes sense: unless
892 ;; we actually change buffers, set_buffer_internal in buffer.c
893 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
894 ;; seems to make the Emacs command loop reluctant to update the
895 ;; display. Perhaps the default process filter in process.c's
896 ;; read_process_output has update_mode_lines++ for a similar
897 ;; reason? beats me ...
898
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000899 (unwind-protect
900 ;; make sure current buffer is restored
901 ;; BAW - we want to check to see if this still applies
902 (progn
903 ;; mysterious ugly hack
904 (if (eq curbuf pbuf)
905 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000907 (set-buffer pbuf)
908 (let* ((start (point))
909 (goback (< start pmark))
910 (goend (and (not goback) (= start (point-max))))
911 (buffer-read-only nil))
912 (goto-char pmark)
913 (insert string)
914 (move-marker pmark (point))
915 (setq file-finished
916 (and py-file-queue
917 (equal ">>> "
918 (buffer-substring
919 (prog2 (beginning-of-line) (point)
920 (goto-char pmark))
921 (point)))))
922 (if goback (goto-char start)
923 ;; else
924 (if py-scroll-process-buffer
925 (let* ((pop-up-windows t)
926 (pwin (display-buffer pbuf)))
927 (set-window-point pwin (point)))))
928 (set-buffer curbuf)
929 (if file-finished
930 (progn
931 (py-delete-file-silently (car py-file-queue))
932 (setq py-file-queue (cdr py-file-queue))
933 (if py-file-queue
934 (py-execute-file pyproc (car py-file-queue)))))
935 (and goend
936 (progn (set-buffer pbuf)
937 (goto-char (point-max))))
938 ))
939 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940
Barry Warsawa97a3f31997-11-04 18:47:06 +0000941
942;;; Subprocess commands
943
944;;;###autoload
945(defun py-shell ()
946 "Start an interactive Python interpreter in another window.
947This is like Shell mode, except that Python is running in the window
948instead of a shell. See the `Interactive Shell' and `Shell Mode'
949sections of the Emacs manual for details, especially for the key
950bindings active in the `*Python*' buffer.
951
952See the docs for variable `py-scroll-buffer' for info on scrolling
953behavior in the process window.
954
955Warning: Don't use an interactive Python if you change sys.ps1 or
956sys.ps2 from their default values, or if you're running code that
957prints `>>> ' or `... ' at the start of a line. `python-mode' can't
958distinguish your output from Python's output, and assumes that `>>> '
959at the start of a line is a prompt from Python. Similarly, the Emacs
960Shell mode code assumes that both `>>> ' and `... ' at the start of a
961line are Python prompts. Bad things can happen if you fool either
962mode.
963
964Warning: If you do any editing *in* the process buffer *while* the
965buffer is accepting output from Python, do NOT attempt to `undo' the
966changes. Some of the output (nowhere near the parts you changed!) may
967be lost if you do. This appears to be an Emacs bug, an unfortunate
968interaction between undo and process filters; the same problem exists in
969non-Python process buffers using the default (Emacs-supplied) process
970filter."
971 ;; BAW - should undo be disabled in the python process buffer, if
972 ;; this bug still exists?
973 (interactive)
974 (require 'comint)
975 (switch-to-buffer-other-window (make-comint "Python" py-python-command "-i"))
976 (make-local-variable 'comint-prompt-regexp)
977 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
978 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
979 (set-syntax-table py-mode-syntax-table)
980 (local-set-key [tab] 'self-insert-command))
981
982
983(defun py-clear-queue ()
984 "Clear the queue of temporary files waiting to execute."
985 (interactive)
986 (let ((n (length py-file-queue)))
987 (mapcar 'delete-file py-file-queue)
988 (setq py-file-queue nil)
989 (message "%d pending files de-queued." n)))
990
991(defun py-execute-region (start end &optional async)
992 "Execute the the region in a Python interpreter.
993The region is first copied into a temporary file (in the directory
994`py-temp-directory'). If there is no Python interpreter shell
995running, this file is executed synchronously using
996`shell-command-on-region'. If the program is long running, use an
997optional \\[universal-argument] to run the command asynchronously in
998its own buffer.
999
1000If the Python interpreter shell is running, the region is execfile()'d
1001in that shell. If you try to execute regions too quickly,
1002`python-mode' will queue them up and execute them one at a time when
1003it sees a `>>> ' prompt from Python. Each time this happens, the
1004process buffer is popped into a window (if it's not already in some
1005window) so you can see it, and a comment of the form
1006
1007 \t## working on region in file <name>...
1008
1009is inserted at the end. See also the command `py-clear-queue'."
1010 (interactive "r\nP")
1011 (or (< start end)
1012 (error "Region is empty"))
1013 (let* ((proc (get-process "Python"))
1014 (temp (make-temp-name "python"))
1015 (file (concat (file-name-as-directory py-temp-directory) temp))
1016 (outbuf "*Python Output*"))
1017 (write-region start end file nil 'nomsg)
1018 (cond
1019 ;; always run the code in it's own asynchronous subprocess
1020 (async
1021 (let* ((buf (generate-new-buffer-name "*Python Output*")))
1022 (start-process "Python" buf py-python-command "-u" file)
1023 (pop-to-buffer buf)
1024 ))
1025 ;; if the Python interpreter shell is running, queue it up for
1026 ;; execution there.
1027 (proc
1028 ;; use the existing python shell
1029 (if (not py-file-queue)
1030 (py-execute-file proc file)
1031 (push file py-file-queue)
1032 (message "File %s queued for execution" file))
1033 )
1034 (t
1035 ;; otherwise either run it synchronously in a subprocess
1036 (shell-command-on-region start end py-python-command outbuf)
1037 ))))
1038
1039;; Code execution command
1040(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041 "Send the contents of the buffer to a Python interpreter.
1042If there is a *Python* process buffer it is used. If a clipping
1043restriction is in effect, only the accessible portion of the buffer is
1044sent. A trailing newline will be supplied if needed.
1045
1046See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001047 (interactive "P")
1048 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001049
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001050
1051;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001052(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001053 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001054
Barry Warsaw7ae77681994-12-12 20:38:05 +00001055If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001056Deletion is performed by calling the function in `py-delete-function'
1057with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001058
1059Else if point is at the leftmost non-blank character of a line that is
1060neither a continuation line nor a non-indenting comment line, or if
1061point is at the end of a blank line, reduces the indentation to match
1062that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001063opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001064of where you are. With numeric count, outdents that many blocks (but
1065not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001066
1067Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001068needed so that only a single column position is deleted. Numeric
1069argument delets that many characters."
1070 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001071 (if (or (/= (current-indentation) (current-column))
1072 (bolp)
1073 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001074 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001076 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001077 ;; else indent the same as the colon line that opened the block
1078
1079 ;; force non-blank so py-goto-block-up doesn't ignore it
1080 (insert-char ?* 1)
1081 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001082 (let ((base-indent 0) ; indentation of base line
1083 (base-text "") ; and text of base line
1084 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001085 (save-excursion
1086 (while (< 0 count)
1087 (condition-case nil ; in case no enclosing block
1088 (progn
1089 (py-goto-block-up 'no-mark)
1090 (setq base-indent (current-indentation)
1091 base-text (py-suck-up-leading-text)
1092 base-found-p t))
1093 (error nil))
1094 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001095 (delete-char 1) ; toss the dummy character
1096 (delete-horizontal-space)
1097 (indent-to base-indent)
1098 (if base-found-p
1099 (message "Closes block: %s" base-text)))))
1100
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001101;; required for pending-del and delsel modes
1102(put 'py-delete-char 'delete-selection 'supersede)
1103(put 'py-delete-char 'pending-delete 'supersede)
1104
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001105(defun py-indent-line (&optional arg)
1106 "Fix the indentation of the current line according to Python rules.
1107With \\[universal-argument], ignore outdenting rules for block
1108closing statements (e.g. return, raise, break, continue, pass)
1109
1110This function is normally bound to `indent-line-function' so
1111\\[indent-for-tab-command] will call it."
1112 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001113 (let* ((ci (current-indentation))
1114 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001115 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001116 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001117 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001118 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001119 (if (/= ci need)
1120 (save-excursion
1121 (beginning-of-line)
1122 (delete-horizontal-space)
1123 (indent-to need)))
1124 (if move-to-indentation-p (back-to-indentation))))
1125
1126(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001127 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001128This is just `strives to' because correct indentation can't be computed
1129from scratch for Python code. In general, deletes the whitespace before
1130point, inserts a newline, and takes an educated guess as to how you want
1131the new line indented."
1132 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001133 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134 (if (< ci (current-column)) ; if point beyond indentation
1135 (newline-and-indent)
1136 ;; else try to act like newline-and-indent "normally" acts
1137 (beginning-of-line)
1138 (insert-char ?\n 1)
1139 (move-to-column ci))))
1140
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001141(defun py-compute-indentation (honor-block-close-p)
1142 ;; implements all the rules for indentation computation. when
1143 ;; honor-block-close-p is non-nil, statements such as return, raise,
1144 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001145 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001146 (let ((pps (parse-partial-sexp (save-excursion
1147 (beginning-of-python-def-or-class)
1148 (point))
1149 (point))))
1150 (beginning-of-line)
1151 (cond
1152 ;; are we inside a string or comment?
1153 ((or (nth 3 pps) (nth 4 pps))
1154 (save-excursion
1155 (if (not py-align-multiline-strings-p) 0
1156 ;; skip back over blank & non-indenting comment lines
1157 ;; note: will skip a blank or non-indenting comment line
1158 ;; that happens to be a continuation line too
1159 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1160 (back-to-indentation)
1161 (current-column))))
1162 ;; are we on a continuation line?
1163 ((py-continuation-line-p)
1164 (let ((startpos (point))
1165 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001166 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001167 (if open-bracket-pos
1168 (progn
1169 ;; align with first item in list; else a normal
1170 ;; indent beyond the line with the open bracket
1171 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1172 ;; is the first list item on the same line?
1173 (skip-chars-forward " \t")
1174 (if (null (memq (following-char) '(?\n ?# ?\\)))
1175 ; yes, so line up with it
1176 (current-column)
1177 ;; first list item on another line, or doesn't exist yet
1178 (forward-line 1)
1179 (while (and (< (point) startpos)
1180 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1181 (forward-line 1))
1182 (if (< (point) startpos)
1183 ;; again mimic the first list item
1184 (current-indentation)
1185 ;; else they're about to enter the first item
1186 (goto-char open-bracket-pos)
1187 (+ (current-indentation) py-indent-offset))))
1188
1189 ;; else on backslash continuation line
1190 (forward-line -1)
1191 (if (py-continuation-line-p) ; on at least 3rd line in block
1192 (current-indentation) ; so just continue the pattern
1193 ;; else started on 2nd line in block, so indent more.
1194 ;; if base line is an assignment with a start on a RHS,
1195 ;; indent to 2 beyond the leftmost "="; else skip first
1196 ;; chunk of non-whitespace characters on base line, + 1 more
1197 ;; column
1198 (end-of-line)
1199 (setq endpos (point) searching t)
1200 (back-to-indentation)
1201 (setq startpos (point))
1202 ;; look at all "=" from left to right, stopping at first
1203 ;; one not nested in a list or string
1204 (while searching
1205 (skip-chars-forward "^=" endpos)
1206 (if (= (point) endpos)
1207 (setq searching nil)
1208 (forward-char 1)
1209 (setq state (parse-partial-sexp startpos (point)))
1210 (if (and (zerop (car state)) ; not in a bracket
1211 (null (nth 3 state))) ; & not in a string
1212 (progn
1213 (setq searching nil) ; done searching in any case
1214 (setq found
1215 (not (or
1216 (eq (following-char) ?=)
1217 (memq (char-after (- (point) 2))
1218 '(?< ?> ?!)))))))))
1219 (if (or (not found) ; not an assignment
1220 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1221 (progn
1222 (goto-char startpos)
1223 (skip-chars-forward "^ \t\n")))
1224 (1+ (current-column))))))
1225
1226 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001227 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001228
Barry Warsawa7891711996-08-01 15:53:09 +00001229 ;; Dfn: "Indenting comment line". A line containing only a
1230 ;; comment, but which is treated like a statement for
1231 ;; indentation calculation purposes. Such lines are only
1232 ;; treated specially by the mode; they are not treated
1233 ;; specially by the Python interpreter.
1234
1235 ;; The rules for indenting comment lines are a line where:
1236 ;; - the first non-whitespace character is `#', and
1237 ;; - the character following the `#' is whitespace, and
1238 ;; - the line is outdented with respect to (i.e. to the left
1239 ;; of) the indentation of the preceding non-blank line.
1240
1241 ;; The first non-blank line following an indenting comment
1242 ;; line is given the same amount of indentation as the
1243 ;; indenting comment line.
1244
1245 ;; All other comment-only lines are ignored for indentation
1246 ;; purposes.
1247
1248 ;; Are we looking at a comment-only line which is *not* an
1249 ;; indenting comment line? If so, we assume that its been
1250 ;; placed at the desired indentation, so leave it alone.
1251 ;; Indenting comment lines are aligned as statements down
1252 ;; below.
1253 ((and (looking-at "[ \t]*#[^ \t\n]")
1254 ;; NOTE: this test will not be performed in older Emacsen
1255 (fboundp 'forward-comment)
1256 (<= (current-indentation)
1257 (save-excursion
1258 (forward-comment (- (point-max)))
1259 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001260 (current-indentation))
1261
1262 ;; else indentation based on that of the statement that
1263 ;; precedes us; use the first line of that statement to
1264 ;; establish the base, in case the user forced a non-std
1265 ;; indentation for the continuation lines (if any)
1266 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001267 ;; skip back over blank & non-indenting comment lines note:
1268 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001269 ;; happens to be a continuation line too. use fast Emacs 19
1270 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001271 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001272 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001273 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001274 (let (done)
1275 (while (not done)
1276 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1277 nil 'move)
1278 (setq done (or (eq py-honor-comment-indentation t)
1279 (bobp)
1280 (/= (following-char) ?#)
1281 (not (zerop (current-column)))))
1282 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001283 ;; if we landed inside a string, go to the beginning of that
1284 ;; string. this handles triple quoted, multi-line spanning
1285 ;; strings.
1286 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001287 (+ (current-indentation)
1288 (if (py-statement-opens-block-p)
1289 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001290 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001291 (- py-indent-offset)
1292 0)))
1293 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001294
1295(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001296 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001297By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001298`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001299Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001300`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001301their own buffer-local copy), both those currently existing and those
1302created later in the Emacs session.
1303
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001304Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001305There's no excuse for such foolishness, but sometimes you have to deal
1306with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001307`py-indent-offset' to what it thinks it was when they created the
1308mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001309
1310Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001311looking for a line that opens a block of code. `py-indent-offset' is
1312set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001313statement following it. If the search doesn't succeed going forward,
1314it's tried again going backward."
1315 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001316 (let (new-value
1317 (start (point))
1318 restart
1319 (found nil)
1320 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001321 (py-goto-initial-line)
1322 (while (not (or found (eobp)))
1323 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1324 (progn
1325 (setq restart (point))
1326 (py-goto-initial-line)
1327 (if (py-statement-opens-block-p)
1328 (setq found t)
1329 (goto-char restart)))))
1330 (if found
1331 ()
1332 (goto-char start)
1333 (py-goto-initial-line)
1334 (while (not (or found (bobp)))
1335 (setq found
1336 (and
1337 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1338 (or (py-goto-initial-line) t) ; always true -- side effect
1339 (py-statement-opens-block-p)))))
1340 (setq colon-indent (current-indentation)
1341 found (and found (zerop (py-next-statement 1)))
1342 new-value (- (current-indentation) colon-indent))
1343 (goto-char start)
1344 (if found
1345 (progn
1346 (funcall (if global 'kill-local-variable 'make-local-variable)
1347 'py-indent-offset)
1348 (setq py-indent-offset new-value)
1349 (message "%s value of py-indent-offset set to %d"
1350 (if global "Global" "Local")
1351 py-indent-offset))
1352 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1353
1354(defun py-shift-region (start end count)
1355 (save-excursion
1356 (goto-char end) (beginning-of-line) (setq end (point))
1357 (goto-char start) (beginning-of-line) (setq start (point))
1358 (indent-rigidly start end count)))
1359
1360(defun py-shift-region-left (start end &optional count)
1361 "Shift region of Python code to the left.
1362The lines from the line containing the start of the current region up
1363to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001364shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365
1366If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001367many columns. With no active region, outdent only the current line.
1368You cannot outdent the region if any line is already at column zero."
1369 (interactive
1370 (let ((p (point))
1371 (m (mark))
1372 (arg current-prefix-arg))
1373 (if m
1374 (list (min p m) (max p m) arg)
1375 (list p (save-excursion (forward-line 1) (point)) arg))))
1376 ;; if any line is at column zero, don't shift the region
1377 (save-excursion
1378 (goto-char start)
1379 (while (< (point) end)
1380 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001381 (if (and (zerop (current-column))
1382 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001383 (error "Region is at left edge."))
1384 (forward-line 1)))
1385 (py-shift-region start end (- (prefix-numeric-value
1386 (or count py-indent-offset))))
1387 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001388
1389(defun py-shift-region-right (start end &optional count)
1390 "Shift region of Python code to the right.
1391The lines from the line containing the start of the current region up
1392to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001393shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001394
1395If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001396many columns. With no active region, indent only the current line."
1397 (interactive
1398 (let ((p (point))
1399 (m (mark))
1400 (arg current-prefix-arg))
1401 (if m
1402 (list (min p m) (max p m) arg)
1403 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001404 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001405 (or count py-indent-offset)))
1406 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001407
1408(defun py-indent-region (start end &optional indent-offset)
1409 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001410
Barry Warsaw7ae77681994-12-12 20:38:05 +00001411The lines from the line containing the start of the current region up
1412to (but not including) the line containing the end of the region are
1413reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001414character in the first column, the first line is left alone and the
1415rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001416region is reindented with respect to the (closest code or indenting
1417comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418
1419This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001420control structures are introduced or removed, or to reformat code
1421using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422
1423If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001424the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001425used.
1426
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001427Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001428is called! This function does not compute proper indentation from
1429scratch (that's impossible in Python), it merely adjusts the existing
1430indentation to be correct in context.
1431
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001432Warning: This function really has no idea what to do with
1433non-indenting comment lines, and shifts them as if they were indenting
1434comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001435
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001436Special cases: whitespace is deleted from blank lines; continuation
1437lines are shifted by the same amount their initial line was shifted,
1438in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001439initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001440 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001441 (save-excursion
1442 (goto-char end) (beginning-of-line) (setq end (point-marker))
1443 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001444 (let ((py-indent-offset (prefix-numeric-value
1445 (or indent-offset py-indent-offset)))
1446 (indents '(-1)) ; stack of active indent levels
1447 (target-column 0) ; column to which to indent
1448 (base-shifted-by 0) ; amount last base line was shifted
1449 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001450 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001451 0))
1452 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001453 (while (< (point) end)
1454 (setq ci (current-indentation))
1455 ;; figure out appropriate target column
1456 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457 ((or (eq (following-char) ?#) ; comment in column 1
1458 (looking-at "[ \t]*$")) ; entirely blank
1459 (setq target-column 0))
1460 ((py-continuation-line-p) ; shift relative to base line
1461 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001462 (t ; new base line
1463 (if (> ci (car indents)) ; going deeper; push it
1464 (setq indents (cons ci indents))
1465 ;; else we should have seen this indent before
1466 (setq indents (memq ci indents)) ; pop deeper indents
1467 (if (null indents)
1468 (error "Bad indentation in region, at line %d"
1469 (save-restriction
1470 (widen)
1471 (1+ (count-lines 1 (point)))))))
1472 (setq target-column (+ indent-base
1473 (* py-indent-offset
1474 (- (length indents) 2))))
1475 (setq base-shifted-by (- target-column ci))))
1476 ;; shift as needed
1477 (if (/= ci target-column)
1478 (progn
1479 (delete-horizontal-space)
1480 (indent-to target-column)))
1481 (forward-line 1))))
1482 (set-marker end nil))
1483
Barry Warsawa7891711996-08-01 15:53:09 +00001484(defun py-comment-region (beg end &optional arg)
1485 "Like `comment-region' but uses double hash (`#') comment starter."
1486 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001487 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001488 (comment-region beg end arg)))
1489
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001490
1491;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001492(defun py-previous-statement (count)
1493 "Go to the start of previous Python statement.
1494If the statement at point is the i'th Python statement, goes to the
1495start of statement i-COUNT. If there is no such statement, goes to the
1496first statement. Returns count of statements left to move.
1497`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001498 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001499 (if (< count 0) (py-next-statement (- count))
1500 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001501 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001502 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001504 (> count 0)
1505 (zerop (forward-line -1))
1506 (py-goto-statement-at-or-above))
1507 (setq count (1- count)))
1508 (if (> count 0) (goto-char start)))
1509 count))
1510
1511(defun py-next-statement (count)
1512 "Go to the start of next Python statement.
1513If the statement at point is the i'th Python statement, goes to the
1514start of statement i+COUNT. If there is no such statement, goes to the
1515last statement. Returns count of statements left to move. `Statements'
1516do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001518 (if (< count 0) (py-previous-statement (- count))
1519 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001520 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001521 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001522 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001523 (> count 0)
1524 (py-goto-statement-below))
1525 (setq count (1- count)))
1526 (if (> count 0) (goto-char start)))
1527 count))
1528
1529(defun py-goto-block-up (&optional nomark)
1530 "Move up to start of current block.
1531Go to the statement that starts the smallest enclosing block; roughly
1532speaking, this will be the closest preceding statement that ends with a
1533colon and is indented less than the statement you started on. If
1534successful, also sets the mark to the starting point.
1535
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001536`\\[py-mark-block]' can be used afterward to mark the whole code
1537block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001538
1539If called from a program, the mark will not be set if optional argument
1540NOMARK is not nil."
1541 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542 (let ((start (point))
1543 (found nil)
1544 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545 (py-goto-initial-line)
1546 ;; if on blank or non-indenting comment line, use the preceding stmt
1547 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1548 (progn
1549 (py-goto-statement-at-or-above)
1550 (setq found (py-statement-opens-block-p))))
1551 ;; search back for colon line indented less
1552 (setq initial-indent (current-indentation))
1553 (if (zerop initial-indent)
1554 ;; force fast exit
1555 (goto-char (point-min)))
1556 (while (not (or found (bobp)))
1557 (setq found
1558 (and
1559 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1560 (or (py-goto-initial-line) t) ; always true -- side effect
1561 (< (current-indentation) initial-indent)
1562 (py-statement-opens-block-p))))
1563 (if found
1564 (progn
1565 (or nomark (push-mark start))
1566 (back-to-indentation))
1567 (goto-char start)
1568 (error "Enclosing block not found"))))
1569
1570(defun beginning-of-python-def-or-class (&optional class)
1571 "Move point to start of def (or class, with prefix arg).
1572
1573Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001574arg, looks for a `class' instead. The docs assume the `def' case;
1575just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001576
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001577If point is in a def statement already, and after the `d', simply
1578moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001579
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580Else (point is not in a def statement, or at or before the `d' of a
1581def statement), searches for the closest preceding def statement, and
1582leaves point at its start. If no such statement can be found, leaves
1583point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001584
1585Returns t iff a def statement is found by these rules.
1586
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001587Note that doing this command repeatedly will take you closer to the
1588start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001589
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001590If you want to mark the current def/class, see
1591`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001592 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001593 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1594 (start-of-line (progn (beginning-of-line) (point)))
1595 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001596 (if (or (/= start-of-stmt start-of-line)
1597 (not at-or-before-p))
1598 (end-of-line)) ; OK to match on this line
1599 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001600 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001601
1602(defun end-of-python-def-or-class (&optional class)
1603 "Move point beyond end of def (or class, with prefix arg) body.
1604
1605By default, looks for an appropriate `def'. If you supply a prefix arg,
1606looks for a `class' instead. The docs assume the `def' case; just
1607substitute `class' for `def' for the other case.
1608
1609If point is in a def statement already, this is the def we use.
1610
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001611Else if the def found by `\\[beginning-of-python-def-or-class]'
1612contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613
1614Else we search forward for the closest following def, and use that.
1615
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001616If a def can be found by these rules, point is moved to the start of
1617the line immediately following the def block, and the position of the
1618start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001619
1620Else point is moved to the end of the buffer, and nil is returned.
1621
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001622Note that doing this command repeatedly will take you closer to the
1623end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001624
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001625If you want to mark the current def/class, see
1626`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001627 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628 (let ((start (progn (py-goto-initial-line) (point)))
1629 (which (if class "class" "def"))
1630 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001631 ;; move point to start of appropriate def/class
1632 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1633 (setq state 'at-beginning)
1634 ;; else see if beginning-of-python-def-or-class hits container
1635 (if (and (beginning-of-python-def-or-class class)
1636 (progn (py-goto-beyond-block)
1637 (> (point) start)))
1638 (setq state 'at-end)
1639 ;; else search forward
1640 (goto-char start)
1641 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1642 (progn (setq state 'at-beginning)
1643 (beginning-of-line)))))
1644 (cond
1645 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1646 ((eq state 'at-end) t)
1647 ((eq state 'not-found) nil)
1648 (t (error "internal error in end-of-python-def-or-class")))))
1649
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001650
1651;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001652(defun py-mark-block (&optional extend just-move)
1653 "Mark following block of lines. With prefix arg, mark structure.
1654Easier to use than explain. It sets the region to an `interesting'
1655block of succeeding lines. If point is on a blank line, it goes down to
1656the next non-blank line. That will be the start of the region. The end
1657of the region depends on the kind of line at the start:
1658
1659 - If a comment, the region will include all succeeding comment lines up
1660 to (but not including) the next non-comment line (if any).
1661
1662 - Else if a prefix arg is given, and the line begins one of these
1663 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664
1665 if elif else try except finally for while def class
1666
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667 the region will be set to the body of the structure, including
1668 following blocks that `belong' to it, but excluding trailing blank
1669 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001670 and all (if any) of the following `except' and `finally' blocks
1671 that belong to the `try' structure will be in the region. Ditto
1672 for if/elif/else, for/else and while/else structures, and (a bit
1673 degenerate, since they're always one-block structures) def and
1674 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675
1676 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001677 block (see list above), and the block is not a `one-liner' (i.e.,
1678 the statement ends with a colon, not with code), the region will
1679 include all succeeding lines up to (but not including) the next
1680 code statement (if any) that's indented no more than the starting
1681 line, except that trailing blank and comment lines are excluded.
1682 E.g., if the starting line begins a multi-statement `def'
1683 structure, the region will be set to the full function definition,
1684 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001685
1686 - Else the region will include all succeeding lines up to (but not
1687 including) the next blank line, or code or indenting-comment line
1688 indented strictly less than the starting line. Trailing indenting
1689 comment lines are included in this case, but not trailing blank
1690 lines.
1691
1692A msg identifying the location of the mark is displayed in the echo
1693area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1694
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001695If called from a program, optional argument EXTEND plays the role of
1696the prefix arg, and if optional argument JUST-MOVE is not nil, just
1697moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001698 (interactive "P") ; raw prefix arg
1699 (py-goto-initial-line)
1700 ;; skip over blank lines
1701 (while (and
1702 (looking-at "[ \t]*$") ; while blank line
1703 (not (eobp))) ; & somewhere to go
1704 (forward-line 1))
1705 (if (eobp)
1706 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001707 (let ((initial-pos (point))
1708 (initial-indent (current-indentation))
1709 last-pos ; position of last stmt in region
1710 (followers
1711 '((if elif else) (elif elif else) (else)
1712 (try except finally) (except except) (finally)
1713 (for else) (while else)
1714 (def) (class) ) )
1715 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001716
1717 (cond
1718 ;; if comment line, suck up the following comment lines
1719 ((looking-at "[ \t]*#")
1720 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1721 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1722 (setq last-pos (point)))
1723
1724 ;; else if line is a block line and EXTEND given, suck up
1725 ;; the whole structure
1726 ((and extend
1727 (setq first-symbol (py-suck-up-first-keyword) )
1728 (assq first-symbol followers))
1729 (while (and
1730 (or (py-goto-beyond-block) t) ; side effect
1731 (forward-line -1) ; side effect
1732 (setq last-pos (point)) ; side effect
1733 (py-goto-statement-below)
1734 (= (current-indentation) initial-indent)
1735 (setq next-symbol (py-suck-up-first-keyword))
1736 (memq next-symbol (cdr (assq first-symbol followers))))
1737 (setq first-symbol next-symbol)))
1738
1739 ;; else if line *opens* a block, search for next stmt indented <=
1740 ((py-statement-opens-block-p)
1741 (while (and
1742 (setq last-pos (point)) ; always true -- side effect
1743 (py-goto-statement-below)
1744 (> (current-indentation) initial-indent))
1745 nil))
1746
1747 ;; else plain code line; stop at next blank line, or stmt or
1748 ;; indenting comment line indented <
1749 (t
1750 (while (and
1751 (setq last-pos (point)) ; always true -- side effect
1752 (or (py-goto-beyond-final-line) t)
1753 (not (looking-at "[ \t]*$")) ; stop at blank line
1754 (or
1755 (>= (current-indentation) initial-indent)
1756 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1757 nil)))
1758
1759 ;; skip to end of last stmt
1760 (goto-char last-pos)
1761 (py-goto-beyond-final-line)
1762
1763 ;; set mark & display
1764 (if just-move
1765 () ; just return
1766 (push-mark (point) 'no-msg)
1767 (forward-line -1)
1768 (message "Mark set after: %s" (py-suck-up-leading-text))
1769 (goto-char initial-pos))))
1770
1771(defun mark-python-def-or-class (&optional class)
1772 "Set region to body of def (or class, with prefix arg) enclosing point.
1773Pushes the current mark, then point, on the mark ring (all language
1774modes do this, but although it's handy it's never documented ...).
1775
1776In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1778`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779
1780And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001781Turned out that was more confusing than useful: the `goto start' and
1782`goto end' commands are usually used to search through a file, and
1783people expect them to act a lot like `search backward' and `search
1784forward' string-search commands. But because Python `def' and `class'
1785can nest to arbitrary levels, finding the smallest def containing
1786point cannot be done via a simple backward search: the def containing
1787point may not be the closest preceding def, or even the closest
1788preceding def that's indented less. The fancy algorithm required is
1789appropriate for the usual uses of this `mark' command, but not for the
1790`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792So the def marked by this command may not be the one either of the
1793`goto' commands find: If point is on a blank or non-indenting comment
1794line, moves back to start of the closest preceding code statement or
1795indenting comment line. If this is a `def' statement, that's the def
1796we use. Else searches for the smallest enclosing `def' block and uses
1797that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001798
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001799When an enclosing def is found: The mark is left immediately beyond
1800the last line of the def block. Point is left at the start of the
1801def, except that: if the def is preceded by a number of comment lines
1802followed by (at most) one optional blank line, point is left at the
1803start of the comments; else if the def is preceded by a blank line,
1804point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805
1806The intent is to mark the containing def/class and its associated
1807documentation, to make moving and duplicating functions and classes
1808pleasant."
1809 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001810 (let ((start (point))
1811 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001812 (push-mark start)
1813 (if (not (py-go-up-tree-to-keyword which))
1814 (progn (goto-char start)
1815 (error "Enclosing %s not found" which))
1816 ;; else enclosing def/class found
1817 (setq start (point))
1818 (py-goto-beyond-block)
1819 (push-mark (point))
1820 (goto-char start)
1821 (if (zerop (forward-line -1)) ; if there is a preceding line
1822 (progn
1823 (if (looking-at "[ \t]*$") ; it's blank
1824 (setq start (point)) ; so reset start point
1825 (goto-char start)) ; else try again
1826 (if (zerop (forward-line -1))
1827 (if (looking-at "[ \t]*#") ; a comment
1828 ;; look back for non-comment line
1829 ;; tricky: note that the regexp matches a blank
1830 ;; line, cuz \n is in the 2nd character class
1831 (and
1832 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1833 (forward-line 1))
1834 ;; no comment, so go back
1835 (goto-char start))))))))
1836
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001837;; ripped from cc-mode
1838(defun py-forward-into-nomenclature (&optional arg)
1839 "Move forward to end of a nomenclature section or word.
1840With arg, to it arg times.
1841
1842A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1843 (interactive "p")
1844 (let ((case-fold-search nil))
1845 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001846 (re-search-forward
1847 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1848 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001849 (while (and (< arg 0)
1850 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001851 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001852 (point-min) 0))
1853 (forward-char 1)
1854 (setq arg (1+ arg)))))
1855 (py-keep-region-active))
1856
1857(defun py-backward-into-nomenclature (&optional arg)
1858 "Move backward to beginning of a nomenclature section or word.
1859With optional ARG, move that many times. If ARG is negative, move
1860forward.
1861
1862A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1863 (interactive "p")
1864 (py-forward-into-nomenclature (- arg))
1865 (py-keep-region-active))
1866
1867
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001868
1869;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001870
1871;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1873;; out of the right places, along with the keys they're on & current
1874;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001875(defun py-dump-help-string (str)
1876 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 (let ((locals (buffer-local-variables))
1878 funckind funcname func funcdoc
1879 (start 0) mstart end
1880 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1882 (setq mstart (match-beginning 0) end (match-end 0)
1883 funckind (substring str (match-beginning 1) (match-end 1))
1884 funcname (substring str (match-beginning 2) (match-end 2))
1885 func (intern funcname))
1886 (princ (substitute-command-keys (substring str start mstart)))
1887 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001888 ((equal funckind "c") ; command
1889 (setq funcdoc (documentation func)
1890 keys (concat
1891 "Key(s): "
1892 (mapconcat 'key-description
1893 (where-is-internal func py-mode-map)
1894 ", "))))
1895 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001896 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897 keys (if (assq func locals)
1898 (concat
1899 "Local/Global values: "
1900 (prin1-to-string (symbol-value func))
1901 " / "
1902 (prin1-to-string (default-value func)))
1903 (concat
1904 "Value: "
1905 (prin1-to-string (symbol-value func))))))
1906 (t ; unexpected
1907 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001908 (princ (format "\n-> %s:\t%s\t%s\n\n"
1909 (if (equal funckind "c") "Command" "Variable")
1910 funcname keys))
1911 (princ funcdoc)
1912 (terpri)
1913 (setq start end))
1914 (princ (substitute-command-keys (substring str start))))
1915 (print-help-return-message)))
1916
1917(defun py-describe-mode ()
1918 "Dump long form of Python-mode docs."
1919 (interactive)
1920 (py-dump-help-string "Major mode for editing Python files.
1921Knows about Python indentation, tokens, comments and continuation lines.
1922Paragraphs are separated by blank lines only.
1923
1924Major sections below begin with the string `@'; specific function and
1925variable docs begin with `->'.
1926
1927@EXECUTING PYTHON CODE
1928
1929\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1930\\[py-execute-region]\tsends the current region
1931\\[py-shell]\tstarts a Python interpreter window; this will be used by
1932\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1933%c:py-execute-buffer
1934%c:py-execute-region
1935%c:py-shell
1936
1937@VARIABLES
1938
1939py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001940py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941
1942py-python-command\tshell command to invoke Python interpreter
1943py-scroll-process-buffer\talways scroll Python process buffer
1944py-temp-directory\tdirectory used for temp files (if needed)
1945
1946py-beep-if-tab-change\tring the bell if tab-width is changed
1947%v:py-indent-offset
1948%v:py-block-comment-prefix
1949%v:py-python-command
1950%v:py-scroll-process-buffer
1951%v:py-temp-directory
1952%v:py-beep-if-tab-change
1953
1954@KINDS OF LINES
1955
1956Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001957preceding line ends with a backslash that's not part of a comment, or
1958the paren/bracket/brace nesting level at the start of the line is
1959non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001960
1961An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001962possibly blanks or tabs), a `comment line' (leftmost non-blank
1963character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964
1965Comment Lines
1966
1967Although all comment lines are treated alike by Python, Python mode
1968recognizes two kinds that act differently with respect to indentation.
1969
1970An `indenting comment line' is a comment line with a blank, tab or
1971nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001972treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001973indenting comment line will be indented like the comment line. All
1974other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975following the initial `#') are `non-indenting comment lines', and
1976their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001977
1978Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001979whenever possible. Non-indenting comment lines are useful in cases
1980like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981
1982\ta = b # a very wordy single-line comment that ends up being
1983\t #... continued onto another line
1984
1985\tif a == b:
1986##\t\tprint 'panic!' # old code we've `commented out'
1987\t\treturn a
1988
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001989Since the `#...' and `##' comment lines have a non-whitespace
1990character following the initial `#', Python mode ignores them when
1991computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001992
1993Continuation Lines and Statements
1994
1995The Python-mode commands generally work on statements instead of on
1996individual lines, where a `statement' is a comment or blank line, or a
1997code line and all of its following continuation lines (if any)
1998considered as a single logical unit. The commands in this mode
1999generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000statement containing point, even if point happens to be in the middle
2001of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002002
2003
2004@INDENTATION
2005
2006Primarily for entering new code:
2007\t\\[indent-for-tab-command]\t indent line appropriately
2008\t\\[py-newline-and-indent]\t insert newline, then indent
2009\t\\[py-delete-char]\t reduce indentation, or delete single character
2010
2011Primarily for reindenting existing code:
2012\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2013\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2014
2015\t\\[py-indent-region]\t reindent region to match its context
2016\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2017\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2018
2019Unlike most programming languages, Python uses indentation, and only
2020indentation, to specify block structure. Hence the indentation supplied
2021automatically by Python-mode is just an educated guess: only you know
2022the block structure you intend, so only you can supply correct
2023indentation.
2024
2025The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2026the indentation of preceding statements. E.g., assuming
2027py-indent-offset is 4, after you enter
2028\tif a > 0: \\[py-newline-and-indent]
2029the cursor will be moved to the position of the `_' (_ is not a
2030character in the file, it's just used here to indicate the location of
2031the cursor):
2032\tif a > 0:
2033\t _
2034If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2035to
2036\tif a > 0:
2037\t c = d
2038\t _
2039Python-mode cannot know whether that's what you intended, or whether
2040\tif a > 0:
2041\t c = d
2042\t_
2043was your intent. In general, Python-mode either reproduces the
2044indentation of the (closest code or indenting-comment) preceding
2045statement, or adds an extra py-indent-offset blanks if the preceding
2046statement has `:' as its last significant (non-whitespace and non-
2047comment) character. If the suggested indentation is too much, use
2048\\[py-delete-char] to reduce it.
2049
2050Continuation lines are given extra indentation. If you don't like the
2051suggested indentation, change it to something you do like, and Python-
2052mode will strive to indent later lines of the statement in the same way.
2053
2054If a line is a continuation line by virtue of being in an unclosed
2055paren/bracket/brace structure (`list', for short), the suggested
2056indentation depends on whether the current line contains the first item
2057in the list. If it does, it's indented py-indent-offset columns beyond
2058the indentation of the line containing the open bracket. If you don't
2059like that, change it by hand. The remaining items in the list will mimic
2060whatever indentation you give to the first item.
2061
2062If a line is a continuation line because the line preceding it ends with
2063a backslash, the third and following lines of the statement inherit their
2064indentation from the line preceding them. The indentation of the second
2065line in the statement depends on the form of the first (base) line: if
2066the base line is an assignment statement with anything more interesting
2067than the backslash following the leftmost assigning `=', the second line
2068is indented two columns beyond that `='. Else it's indented to two
2069columns beyond the leftmost solid chunk of non-whitespace characters on
2070the base line.
2071
2072Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2073repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2074structure you intend.
2075%c:indent-for-tab-command
2076%c:py-newline-and-indent
2077%c:py-delete-char
2078
2079
2080The next function may be handy when editing code you didn't write:
2081%c:py-guess-indent-offset
2082
2083
2084The remaining `indent' functions apply to a region of Python code. They
2085assume the block structure (equals indentation, in Python) of the region
2086is correct, and alter the indentation in various ways while preserving
2087the block structure:
2088%c:py-indent-region
2089%c:py-shift-region-left
2090%c:py-shift-region-right
2091
2092@MARKING & MANIPULATING REGIONS OF CODE
2093
2094\\[py-mark-block]\t mark block of lines
2095\\[mark-python-def-or-class]\t mark smallest enclosing def
2096\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002097\\[comment-region]\t comment out region of code
2098\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002099%c:py-mark-block
2100%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002101%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002102
2103@MOVING POINT
2104
2105\\[py-previous-statement]\t move to statement preceding point
2106\\[py-next-statement]\t move to statement following point
2107\\[py-goto-block-up]\t move up to start of current block
2108\\[beginning-of-python-def-or-class]\t move to start of def
2109\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2110\\[end-of-python-def-or-class]\t move to end of def
2111\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2112
2113The first two move to one statement beyond the statement that contains
2114point. A numeric prefix argument tells them to move that many
2115statements instead. Blank lines, comment lines, and continuation lines
2116do not count as `statements' for these commands. So, e.g., you can go
2117to the first code statement in a file by entering
2118\t\\[beginning-of-buffer]\t to move to the top of the file
2119\t\\[py-next-statement]\t to skip over initial comments and blank lines
2120Or do `\\[py-previous-statement]' with a huge prefix argument.
2121%c:py-previous-statement
2122%c:py-next-statement
2123%c:py-goto-block-up
2124%c:beginning-of-python-def-or-class
2125%c:end-of-python-def-or-class
2126
2127@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2128
2129`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2130
2131`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2132overall class and def structure of a module.
2133
2134`\\[back-to-indentation]' moves point to a line's first non-blank character.
2135
2136`\\[indent-relative]' is handy for creating odd indentation.
2137
2138@OTHER EMACS HINTS
2139
2140If you don't like the default value of a variable, change its value to
2141whatever you do like by putting a `setq' line in your .emacs file.
2142E.g., to set the indentation increment to 4, put this line in your
2143.emacs:
2144\t(setq py-indent-offset 4)
2145To see the value of a variable, do `\\[describe-variable]' and enter the variable
2146name at the prompt.
2147
2148When entering a key sequence like `C-c C-n', it is not necessary to
2149release the CONTROL key after doing the `C-c' part -- it suffices to
2150press the CONTROL key, press and release `c' (while still holding down
2151CONTROL), press and release `n' (while still holding down CONTROL), &
2152then release CONTROL.
2153
2154Entering Python mode calls with no arguments the value of the variable
2155`python-mode-hook', if that value exists and is not nil; for backward
2156compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2157the Elisp manual for details.
2158
2159Obscure: When python-mode is first loaded, it looks for all bindings
2160to newline-and-indent in the global keymap, and shadows them with
2161local bindings to py-newline-and-indent."))
2162
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002163
2164;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002165(defvar py-parse-state-re
2166 (concat
2167 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2168 "\\|"
2169 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002170
Barry Warsaw7ae77681994-12-12 20:38:05 +00002171;; returns the parse state at point (see parse-partial-sexp docs)
2172(defun py-parse-state ()
2173 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002174 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002175 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002176 (while (not done)
2177 ;; back up to the first preceding line (if any; else start of
2178 ;; buffer) that begins with a popular Python keyword, or a
2179 ;; non- whitespace and non-comment character. These are good
2180 ;; places to start parsing to see whether where we started is
2181 ;; at a non-zero nesting level. It may be slow for people who
2182 ;; write huge code blocks or huge lists ... tough beans.
2183 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002184 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002185 (beginning-of-line)
2186 (save-excursion
2187 (setq pps (parse-partial-sexp (point) here)))
2188 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002189 (setq done (or (zerop ci)
2190 (not (nth 3 pps))
2191 (bobp)))
2192 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002193 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194
2195;; if point is at a non-zero nesting level, returns the number of the
2196;; character that opens the smallest enclosing unclosed list; else
2197;; returns nil.
2198(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002199 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200 (if (zerop (car status))
2201 nil ; not in a nest
2202 (car (cdr status))))) ; char# of open bracket
2203
2204;; t iff preceding line ends with backslash that's not in a comment
2205(defun py-backslash-continuation-line-p ()
2206 (save-excursion
2207 (beginning-of-line)
2208 (and
2209 ;; use a cheap test first to avoid the regexp if possible
2210 ;; use 'eq' because char-after may return nil
2211 (eq (char-after (- (point) 2)) ?\\ )
2212 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002213 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002214 (looking-at py-continued-re))))
2215
2216;; t iff current line is a continuation line
2217(defun py-continuation-line-p ()
2218 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002219 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002220 (or (py-backslash-continuation-line-p)
2221 (py-nesting-level))))
2222
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002223;; go to initial line of current statement; usually this is the line
2224;; we're on, but if we're on the 2nd or following lines of a
2225;; continuation block, we need to go up to the first line of the
2226;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002228;; Tricky: We want to avoid quadratic-time behavior for long continued
2229;; blocks, whether of the backslash or open-bracket varieties, or a
2230;; mix of the two. The following manages to do that in the usual
2231;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002232(defun py-goto-initial-line ()
2233 (let ( open-bracket-pos )
2234 (while (py-continuation-line-p)
2235 (beginning-of-line)
2236 (if (py-backslash-continuation-line-p)
2237 (while (py-backslash-continuation-line-p)
2238 (forward-line -1))
2239 ;; else zip out of nested brackets/braces/parens
2240 (while (setq open-bracket-pos (py-nesting-level))
2241 (goto-char open-bracket-pos)))))
2242 (beginning-of-line))
2243
2244;; go to point right beyond final line of current statement; usually
2245;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002246;; statement we need to skip over the continuation lines. Tricky:
2247;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002248(defun py-goto-beyond-final-line ()
2249 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002250 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002251 (while (and (py-continuation-line-p)
2252 (not (eobp)))
2253 ;; skip over the backslash flavor
2254 (while (and (py-backslash-continuation-line-p)
2255 (not (eobp)))
2256 (forward-line 1))
2257 ;; if in nest, zip to the end of the nest
2258 (setq state (py-parse-state))
2259 (if (and (not (zerop (car state)))
2260 (not (eobp)))
2261 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002262 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002263 (forward-line 1))))))
2264
2265;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002266;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002267(defun py-statement-opens-block-p ()
2268 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002269 (let ((start (point))
2270 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2271 (searching t)
2272 (answer nil)
2273 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002274 (goto-char start)
2275 (while searching
2276 ;; look for a colon with nothing after it except whitespace, and
2277 ;; maybe a comment
2278 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2279 finish t)
2280 (if (eq (point) finish) ; note: no `else' clause; just
2281 ; keep searching if we're not at
2282 ; the end yet
2283 ;; sure looks like it opens a block -- but it might
2284 ;; be in a comment
2285 (progn
2286 (setq searching nil) ; search is done either way
2287 (setq state (parse-partial-sexp start
2288 (match-beginning 0)))
2289 (setq answer (not (nth 4 state)))))
2290 ;; search failed: couldn't find another interesting colon
2291 (setq searching nil)))
2292 answer)))
2293
Barry Warsawf831d811996-07-31 20:42:59 +00002294(defun py-statement-closes-block-p ()
2295 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002296 ;; starts with `return', `raise', `break', `continue', and `pass'.
2297 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002298 (let ((here (point)))
2299 (back-to-indentation)
2300 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002301 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002302 (goto-char here))))
2303
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304;; go to point right beyond final line of block begun by the current
2305;; line. This is the same as where py-goto-beyond-final-line goes
2306;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002308(defun py-goto-beyond-block ()
2309 (if (py-statement-opens-block-p)
2310 (py-mark-block nil 'just-move)
2311 (py-goto-beyond-final-line)))
2312
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002313;; go to start of first statement (not blank or comment or
2314;; continuation line) at or preceding point. returns t if there is
2315;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002316(defun py-goto-statement-at-or-above ()
2317 (py-goto-initial-line)
2318 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002319 ;; skip back over blank & comment lines
2320 ;; note: will skip a blank or comment line that happens to be
2321 ;; a continuation line too
2322 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2323 (progn (py-goto-initial-line) t)
2324 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002325 t))
2326
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002327;; go to start of first statement (not blank or comment or
2328;; continuation line) following the statement containing point returns
2329;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002330(defun py-goto-statement-below ()
2331 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002332 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333 (py-goto-beyond-final-line)
2334 (while (and
2335 (looking-at py-blank-or-comment-re)
2336 (not (eobp)))
2337 (forward-line 1))
2338 (if (eobp)
2339 (progn (goto-char start) nil)
2340 t)))
2341
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002342;; go to start of statement, at or preceding point, starting with
2343;; keyword KEY. Skips blank lines and non-indenting comments upward
2344;; first. If that statement starts with KEY, done, else go back to
2345;; first enclosing block starting with KEY. If successful, leaves
2346;; point at the start of the KEY line & returns t. Else leaves point
2347;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002348(defun py-go-up-tree-to-keyword (key)
2349 ;; skip blanks and non-indenting #
2350 (py-goto-initial-line)
2351 (while (and
2352 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2353 (zerop (forward-line -1))) ; go back
2354 nil)
2355 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002356 (let* ((re (concat "[ \t]*" key "\\b"))
2357 (case-fold-search nil) ; let* so looking-at sees this
2358 (found (looking-at re))
2359 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002360 (while (not (or found dead))
2361 (condition-case nil ; in case no enclosing block
2362 (py-goto-block-up 'no-mark)
2363 (error (setq dead t)))
2364 (or dead (setq found (looking-at re))))
2365 (beginning-of-line)
2366 found))
2367
2368;; return string in buffer from start of indentation to end of line;
2369;; prefix "..." if leading whitespace was skipped
2370(defun py-suck-up-leading-text ()
2371 (save-excursion
2372 (back-to-indentation)
2373 (concat
2374 (if (bolp) "" "...")
2375 (buffer-substring (point) (progn (end-of-line) (point))))))
2376
2377;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2378;; as a Lisp symbol; return nil if none
2379(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002380 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002381 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2382 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2383 nil)))
2384
Barry Warsaw7ae77681994-12-12 20:38:05 +00002385(defun py-delete-file-silently (fname)
2386 (condition-case nil
2387 (delete-file fname)
2388 (error nil)))
2389
2390(defun py-kill-emacs-hook ()
2391 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002392 (py-safe (while py-file-queue
2393 (py-delete-file-silently (car py-file-queue))
2394 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002395
Barry Warsawb3e81d51996-09-04 15:12:42 +00002396(defun py-current-defun ()
2397 ;; tell add-log.el how to find the current function/method/variable
2398 (save-excursion
2399 (if (re-search-backward py-defun-start-re nil t)
2400 (or (match-string 3)
2401 (let ((method (match-string 2)))
2402 (if (and (not (zerop (length (match-string 1))))
2403 (re-search-backward py-class-start-re nil t))
2404 (concat (match-string 1) "." method)
2405 method)))
2406 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002407
2408
Barry Warsawfec75d61995-07-05 23:26:15 +00002409(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002410 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002411
Barry Warsaw850437a1995-03-08 21:50:28 +00002412(defun py-version ()
2413 "Echo the current version of `python-mode' in the minibuffer."
2414 (interactive)
2415 (message "Using `python-mode' version %s" py-version)
2416 (py-keep-region-active))
2417
2418;; only works under Emacs 19
2419;(eval-when-compile
2420; (require 'reporter))
2421
2422(defun py-submit-bug-report (enhancement-p)
2423 "Submit via mail a bug report on `python-mode'.
2424With \\[universal-argument] just submit an enhancement request."
2425 (interactive
2426 (list (not (y-or-n-p
2427 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002428 (let ((reporter-prompt-for-summary-p (if enhancement-p
2429 "(Very) brief summary: "
2430 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002431 (require 'reporter)
2432 (reporter-submit-bug-report
2433 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002434 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002435 ;; varlist
2436 (if enhancement-p nil
2437 '(py-python-command
2438 py-indent-offset
2439 py-block-comment-prefix
2440 py-scroll-process-buffer
2441 py-temp-directory
2442 py-beep-if-tab-change))
2443 nil ;pre-hooks
2444 nil ;post-hooks
2445 "Dear Barry,") ;salutation
2446 (if enhancement-p nil
2447 (set-mark (point))
2448 (insert
2449"Please replace this text with a sufficiently large code sample\n\
2450and an exact recipe so that I can reproduce your problem. Failure\n\
2451to do so may mean a greater delay in fixing your bug.\n\n")
2452 (exchange-point-and-mark)
2453 (py-keep-region-active))))
2454
2455
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002456;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002457(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002458
2459
2460
2461(provide 'python-mode)
2462;;; python-mode.el ends here