blob: c0da4139230d4f70d9be2ab6b82e469db6fc8e66 [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 Warsaw4669d7e1996-03-22 16:13:24 +00005;; Author: 1995-1996 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
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 Warsaw755c6711996-08-01 20:02:55 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; left the net for a while and in the interim, Barry Warsaw has
25;; undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
27;; At some point this mode will undergo a rewrite to bring it more in
Barry Warsaw755c6711996-08-01 20:02:55 +000028;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
29;; 18 support. But all in all, the mode works exceedingly well, and
30;; I've simply been tweaking it as I go along. Ain't it wonderful
31;; that Python has a much more sane syntax than C? (or <shudder> C++?!
32;; :-). I can say that; I maintain cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000033
34;; The following statements, placed in your .emacs file or
35;; site-init.el, will cause this file to be autoloaded, and
36;; python-mode invoked, when visiting .py files (assuming this file is
37;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000039;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000040;; (setq auto-mode-alist
41;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000042;;
43;; If you want font-lock support for Python source code (a.k.a. syntax
44;; coloring, highlighting), add this to your .emacs file:
45;;
46;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000047;;
48;; But you better be sure you're version of Emacs supports
49;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
50;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000051
Barry Warsaw3fcaf611996-08-01 20:11:51 +000052;; Here's a brief list of recent additions/improvements/changes:
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000053;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000054;; - Wrapping and indentation within triple quote strings now works.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000055;; - `Standard' bug reporting mechanism (use C-c C-b)
56;; - py-mark-block was moved to C-c C-m
57;; - C-c C-v shows you the python-mode version
Barry Warsaw3fcaf611996-08-01 20:11:51 +000058;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000059;; - proper interaction with pending-del and del-sel modes.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000060;; - Better support for outdenting: py-electric-colon (:) and
61;; py-indent-line (TAB) improvements; one level of outdentation
62;; added after a return, raise, break, or continue statement
63;; - New py-electric-colon (:) command for improved outdenting Also
64;; py-indent-line (TAB) should handle outdented lines better
Barry Warsaw03970731996-07-03 23:12:52 +000065;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000066;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
67;; M-f and M-b respectively.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000068;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
69;; - py-indent-offset now defaults to 4
70;; - new variable py-honor-comment-indentation
71;; - comment-region bound to C-c #
72;; - py-delete-char obeys numeric arguments
73;; - Small modification to rule for "indenting comment lines", such
74;; lines must now also be indented less than or equal to the
75;; indentation of the previous statement.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000076
Barry Warsaw7b0f5681995-03-08 21:33:04 +000077;; Here's a brief to do list:
78;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079;; - Better integration with gud-mode for debugging.
80;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000081;; - possibly force indent-tabs-mode == nil, and add a
82;; write-file-hooks that runs untabify on the whole buffer (to work
83;; around potential tab/space mismatch problems). In practice this
84;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000085;; - have py-execute-region on indented code act as if the region is
86;; left justified. Avoids syntax errors.
Barry Warsaw7ae77681994-12-12 20:38:05 +000087
Barry Warsaw7b0f5681995-03-08 21:33:04 +000088;; If you can think of more things you'd like to see, drop me a line.
89;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
90;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000091;; Note that I only test things on XEmacs 19 and to some degree on
92;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
93;; send me your patches. Byte compiler complaints can probably be
94;; safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000095
Barry Warsaw7b0f5681995-03-08 21:33:04 +000096;;; Code:
97
98
99;; user definable variables
100;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000101
102(defvar py-python-command "python"
103 "*Shell command used to start Python interpreter.")
104
Barry Warsaw17914f41995-11-03 18:25:15 +0000105(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +0000106 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000107Note that `\\[py-guess-indent-offset]' can usually guess a good value
108when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000109
Barry Warsaw095e9c61995-09-19 20:01:42 +0000110(defvar py-align-multiline-strings-p t
111 "*Flag describing how multiline triple quoted strings are aligned.
112When this flag is non-nil, continuation lines are lined up under the
113preceding line's indentation. When this flag is nil, continuation
114lines are aligned to column zero.")
115
Barry Warsaw3fcaf611996-08-01 20:11:51 +0000116(defvar py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000117 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000118This should follow the convention for non-indenting comment lines so
119that the indentation commands won't get confused (i.e., the string
120should be of the form `#x...' where `x' is not a blank or a tab, and
121`...' is arbitrary).")
122
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000123(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000124 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000125
Barry Warsaw6d627751996-03-06 18:41:38 +0000126When nil, all comment lines are skipped for indentation purposes, and
127in Emacs 19, a faster algorithm is used.
128
129When t, lines that begin with a single `#' are a hint to subsequent
130line indentation. If the previous line is such a comment line (as
131opposed to one that starts with `py-block-comment-prefix'), then it's
132indentation is used as a hint for this line's indentation. Lines that
133begin with `py-block-comment-prefix' are ignored for indentation
134purposes.
135
136When not nil or t, comment lines that begin with a `#' are used as
137indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000138
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139(defvar py-scroll-process-buffer t
140 "*Scroll Python process buffer as output arrives.
141If nil, the Python process buffer acts, with respect to scrolling, like
142Shell-mode buffers normally act. This is surprisingly complicated and
143so won't be explained here; in fact, you can't get the whole story
144without studying the Emacs C code.
145
146If non-nil, the behavior is different in two respects (which are
147slightly inaccurate in the interest of brevity):
148
149 - If the buffer is in a window, and you left point at its end, the
150 window will scroll as new output arrives, and point will move to the
151 buffer's end, even if the window is not the selected window (that
152 being the one the cursor is in). The usual behavior for shell-mode
153 windows is not to scroll, and to leave point where it was, if the
154 buffer is in a window other than the selected window.
155
156 - If the buffer is not visible in any window, and you left point at
157 its end, the buffer will be popped into a window as soon as more
158 output arrives. This is handy if you have a long-running
159 computation and don't want to tie up screen area waiting for the
160 output. The usual behavior for a shell-mode buffer is to stay
161 invisible until you explicitly visit it.
162
163Note the `and if you left point at its end' clauses in both of the
164above: you can `turn off' the special behaviors while output is in
165progress, by visiting the Python buffer and moving point to anywhere
166besides the end. Then the buffer won't scroll, point will remain where
167you leave it, and if you hide the buffer it will stay hidden until you
168visit it again. You can enable and disable the special behaviors as
169often as you like, while output is in progress, by (respectively) moving
170point to, or away from, the end of the buffer.
171
172Warning: If you expect a large amount of output, you'll probably be
173happier setting this option to nil.
174
175Obscure: `End of buffer' above should really say `at or beyond the
176process mark', but if you know what that means you didn't need to be
177told <grin>.")
178
179(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000180 (let ((ok '(lambda (x)
181 (and x
182 (setq x (expand-file-name x)) ; always true
183 (file-directory-p x)
184 (file-writable-p x)
185 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000186 (or (funcall ok (getenv "TMPDIR"))
187 (funcall ok "/usr/tmp")
188 (funcall ok "/tmp")
189 (funcall ok ".")
190 (error
191 "Couldn't find a usable temp directory -- set py-temp-directory")))
192 "*Directory used for temp files created by a *Python* process.
193By default, the first directory from this list that exists and that you
194can write into: the value (if any) of the environment variable TMPDIR,
195/usr/tmp, /tmp, or the current directory.")
196
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000197(defvar py-beep-if-tab-change t
198 "*Ring the bell if tab-width is changed.
199If a comment of the form
200
201 \t# vi:set tabsize=<number>:
202
203is found before the first code line when the file is entered, and the
204current value of (the general Emacs variable) `tab-width' does not
205equal <number>, `tab-width' is set to <number>, a message saying so is
206displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
207the Emacs bell is also rung as a warning.")
208
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000209(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000210 (let* ((keywords '("access" "and" "break" "class"
211 "continue" "def" "del" "elif"
212 "else:" "except" "except:" "exec"
213 "finally:" "for" "from" "global"
214 "if" "import" "in" "is"
215 "lambda" "not" "or" "pass"
216 "print" "raise" "return" "try:"
217 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000218 ))
219 (kwregex (mapconcat 'identity keywords "\\|")))
220 (list
221 ;; keywords not at beginning of line
222 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
223 ;; keywords at beginning of line. i don't think regexps are
224 ;; powerful enough to handle these two cases in one regexp.
225 ;; prove me wrong!
226 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
227 ;; classes
228 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
229 1 font-lock-type-face)
230 ;; functions
231 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
232 1 font-lock-function-name-face)
233 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000234 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000235
Barry Warsaw81437461996-08-01 19:48:02 +0000236(defvar imenu-example--python-show-method-args-p nil
237 "*Controls echoing of arguments of functions & methods in the imenu buffer.
238When non-nil, arguments are printed.")
239
240
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000241
242;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
243;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
244
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000245(make-variable-buffer-local 'py-indent-offset)
246
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000247;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
248;; seems to be the standard way of checking this.
249;; BAW - This is *not* the right solution. When at all possible,
250;; instead of testing for the version of Emacs, use feature tests.
251
252(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
253(setq py-this-is-emacs-19-p
254 (and
255 (not py-this-is-lucid-emacs-p)
256 (string-match "^19\\." emacs-version)))
257
Barry Warsaw7ae77681994-12-12 20:38:05 +0000258;; have to bind py-file-queue before installing the kill-emacs hook
259(defvar py-file-queue nil
260 "Queue of Python temp files awaiting execution.
261Currently-active file is at the head of the list.")
262
263;; define a mode-specific abbrev table for those who use such things
264(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000265 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000266(define-abbrev-table 'python-mode-abbrev-table nil)
267
Barry Warsaw7ae77681994-12-12 20:38:05 +0000268(defvar python-mode-hook nil
269 "*Hook called by `python-mode'.")
270
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000271;; in previous version of python-mode.el, the hook was incorrectly
272;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000273(and (fboundp 'make-obsolete-variable)
274 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
275
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276(defvar py-mode-map ()
277 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000278
Barry Warsaw7ae77681994-12-12 20:38:05 +0000279(if py-mode-map
280 ()
281 (setq py-mode-map (make-sparse-keymap))
282
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 ;; shadow global bindings for newline-and-indent w/ the py- version.
284 ;; BAW - this is extremely bad form, but I'm not going to change it
285 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000286 (mapcar (function (lambda (key)
287 (define-key
288 py-mode-map key 'py-newline-and-indent)))
289 (where-is-internal 'newline-and-indent))
290
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 ;; BAW - you could do it this way, but its not considered proper
292 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000293 (mapcar (function
294 (lambda (x)
295 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000296 '((":" . py-electric-colon)
297 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298 ("\C-c|" . py-execute-region)
299 ("\C-c!" . py-shell)
300 ("\177" . py-delete-char)
301 ("\n" . py-newline-and-indent)
302 ("\C-c:" . py-guess-indent-offset)
303 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000304 ("\C-c\C-l" . py-shift-region-left)
305 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000306 ("\C-c<" . py-shift-region-left)
307 ("\C-c>" . py-shift-region-right)
308 ("\C-c\C-n" . py-next-statement)
309 ("\C-c\C-p" . py-previous-statement)
310 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000311 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000312 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000313 ("\C-c?" . py-describe-mode)
314 ("\C-c\C-hm" . py-describe-mode)
315 ("\e\C-a" . beginning-of-python-def-or-class)
316 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000317 ( "\e\C-h" . mark-python-def-or-class)))
318 ;; should do all keybindings this way
319 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
320 (define-key py-mode-map "\C-c\C-v" 'py-version)
321 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000322
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000323(defvar py-mode-syntax-table nil
324 "Syntax table used in `python-mode' buffers.")
325
Barry Warsaw7ae77681994-12-12 20:38:05 +0000326(if py-mode-syntax-table
327 ()
328 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000329 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000330 (mapcar (function
331 (lambda (x) (modify-syntax-entry
332 (car x) (cdr x) py-mode-syntax-table)))
333 '(( ?\( . "()" ) ( ?\) . ")(" )
334 ( ?\[ . "(]" ) ( ?\] . ")[" )
335 ( ?\{ . "(}" ) ( ?\} . "){" )
336 ;; fix operator symbols misassigned in the std table
337 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
338 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
339 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
340 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000341 ;; for historical reasons, underscore is word class
342 ;; instead of symbol class. it should be symbol class,
343 ;; but if you're tempted to change it, try binding M-f and
344 ;; M-b to py-forward-into-nomenclature and
345 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000346 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000347 ( ?\' . "\"") ; single quote is string quote
348 ( ?\" . "\"" ) ; double quote is string quote too
349 ( ?\` . "$") ; backquote is open and close paren
350 ( ?\# . "<") ; hash starts comment
351 ( ?\n . ">")))) ; newline ends comment
352
353(defconst py-stringlit-re
354 (concat
355 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
356 "\\|" ; or
357 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000358 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000359
360;; this is tricky because a trailing backslash does not mean
361;; continuation if it's in a comment
362(defconst py-continued-re
363 (concat
364 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
365 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000366 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000367
368(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000369 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000370
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000371(defconst py-outdent-re
372 (concat "\\(" (mapconcat 'identity
373 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000374 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000375 "finally:"
376 "elif\\s +.*:")
377 "\\|")
378 "\\)")
379 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000380
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000381(defconst py-no-outdent-re
382 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000383 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000384 "except\\(\\s +.*\\)?:"
385 "while\\s +.*:"
386 "for\\s +.*:"
387 "if\\s +.*:"
388 "elif\\s +.*:")
389 "\\|")
390 "\\)")
391 "Regexp matching lines to not outdent after.")
392
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393
Barry Warsaw42f707f1996-07-29 21:05:05 +0000394;; Menu definitions, only relevent if you have the easymenu.el package
395;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000396(defvar py-menu nil
397 "Menu for Python Mode.
398
399This menu will get created automatically if you have the easymenu
400package. Note that the latest XEmacs 19 and Emacs 19 versions contain
401this package.")
402
Barry Warsaw42f707f1996-07-29 21:05:05 +0000403(if (condition-case nil
404 (require 'easymenu)
405 (error nil))
406 (easy-menu-define
407 py-menu py-mode-map "Python Mode menu"
408 '("Python"
409 ["Comment Out Region" comment-region (mark)]
410 ["Uncomment Region" (comment-region (point) (mark) '(4)) (mark)]
411 "-"
412 ["Mark current block" py-mark-block t]
413 ["Mark current def" mark-python-def-or-class t]
414 ["Mark current class" (mark-python-def-or-class t) t]
415 "-"
416 ["Shift region left" py-shift-region-left (mark)]
417 ["Shift region right" py-shift-region-right (mark)]
418 "-"
419 ["Execute buffer" py-execute-buffer t]
420 ["Execute region" py-execute-region (mark)]
421 ["Start interpreter..." py-shell t]
422 "-"
423 ["Go to start of block" py-goto-block-up t]
424 ["Go to start of class" (beginning-of-python-def-or-class t) t]
425 ["Move to end of class" (end-of-python-def-or-class t) t]
426 ["Move to start of def" beginning-of-python-def-or-class t]
427 ["Move to end of def" end-of-python-def-or-class t]
428 "-"
429 ["Describe mode" py-describe-mode t]
430 )))
431
Barry Warsaw81437461996-08-01 19:48:02 +0000432
433
434;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
435(defvar imenu-example--python-class-regexp
436 (concat ; <<classes>>
437 "\\(" ;
438 "^[ \t]*" ; newline and maybe whitespace
439 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
440 ; possibly multiple superclasses
441 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
442 "[ \t]*:" ; and the final :
443 "\\)" ; >>classes<<
444 )
445 "Regexp for Python classes for use with the imenu package."
446 )
447
448(defvar imenu-example--python-method-regexp
449 (concat ; <<methods and functions>>
450 "\\(" ;
451 "^[ \t]*" ; new line and maybe whitespace
452 "\\(def[ \t]+" ; function definitions start with def
453 "\\([a-zA-Z0-9_]+\\)" ; name is here
454 ; function arguments...
455 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
456 "\\)" ; end of def
457 "[ \t]*:" ; and then the :
458 "\\)" ; >>methods and functions<<
459 )
460 "Regexp for Python methods/functions for use with the imenu package."
461 )
462
463(defvar imenu-example--python-method-no-arg-parens '(2 8)
464 "Indicies into groups of the Python regexp for use with imenu.
465
466Using these values will result in smaller imenu lists, as arguments to
467functions are not listed.
468
469See the variable `imenu-example--python-show-method-args-p' for more
470information.")
471
472(defvar imenu-example--python-method-arg-parens '(2 7)
473 "Indicies into groups of the Python regexp for use with imenu.
474Using these values will result in large imenu lists, as arguments to
475functions are listed.
476
477See the variable `imenu-example--python-show-method-args-p' for more
478information.")
479
480;; Note that in this format, this variable can still be used with the
481;; imenu--generic-function. Otherwise, there is no real reason to have
482;; it.
483(defvar imenu-example--generic-python-expression
484 (cons
485 (concat
486 imenu-example--python-class-regexp
487 "\\|" ; or...
488 imenu-example--python-method-regexp
489 )
490 imenu-example--python-method-no-arg-parens)
491 "Generic Python expression which may be used directly with imenu.
492Used by setting the variable `imenu-generic-expression' to this value.
493Also, see the function \\[imenu-example--create-python-index] for a
494better alternative for finding the index.")
495
496;; These next two variables are used when searching for the python
497;; class/definitions. Just saving some time in accessing the
498;; generic-python-expression, really.
499(defvar imenu-example--python-generic-regexp)
500(defvar imenu-example--python-generic-parens)
501
502
503;;;###autoload
504(eval-when-compile
505 ;; Imenu isn't used in XEmacs, so just ignore load errors
506 (condition-case ()
507 (progn
508 (require 'cl)
509 (require 'imenu))
510 (error nil)))
511
512(defun imenu-example--create-python-index ()
513 "Python interface function for imenu package.
514Finds all python classes and functions/methods. Calls function
515\\[imenu-example--create-python-index-engine]. See that function for
516the details of how this works."
517 (setq imenu-example--python-generic-regexp
518 (car imenu-example--generic-python-expression))
519 (setq imenu-example--python-generic-parens
520 (if imenu-example--python-show-method-args-p
521 imenu-example--python-method-arg-parens
522 imenu-example--python-method-no-arg-parens))
523 (goto-char (point-min))
524 (imenu-example--create-python-index-engine nil))
525
526(defun imenu-example--create-python-index-engine (&optional start-indent)
527 "Function for finding imenu definitions in Python.
528
529Finds all definitions (classes, methods, or functions) in a Python
530file for the imenu package.
531
532Returns a possibly nested alist of the form
533
534 (INDEX-NAME . INDEX-POSITION)
535
536The second element of the alist may be an alist, producing a nested
537list as in
538
539 (INDEX-NAME . INDEX-ALIST)
540
541This function should not be called directly, as it calls itself
542recursively and requires some setup. Rather this is the engine for
543the function \\[imenu-example--create-python-index].
544
545It works recursively by looking for all definitions at the current
546indention level. When it finds one, it adds it to the alist. If it
547finds a definition at a greater indentation level, it removes the
548previous definition from the alist. In it's place it adds all
549definitions found at the next indentation level. When it finds a
550definition that is less indented then the current level, it retuns the
551alist it has created thus far.
552
553The optional argument START-INDENT indicates the starting indentation
554at which to continue looking for Python classes, methods, or
555functions. If this is not supplied, the function uses the indentation
556of the first definition found."
557 (let ((index-alist '())
558 (sub-method-alist '())
559 looking-p
560 def-name prev-name
561 cur-indent def-pos
562 (class-paren (first imenu-example--python-generic-parens))
563 (def-paren (second imenu-example--python-generic-parens)))
564 (setq looking-p
565 (re-search-forward imenu-example--python-generic-regexp
566 (point-max) t))
567 (while looking-p
568 (save-excursion
569 ;; used to set def-name to this value but generic-extract-name is
570 ;; new to imenu-1.14. this way it still works with imenu-1.11
571 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
572 (let ((cur-paren (if (match-beginning class-paren)
573 class-paren def-paren)))
574 (setq def-name
575 (buffer-substring (match-beginning cur-paren)
576 (match-end cur-paren))))
577 (beginning-of-line)
578 (setq cur-indent (current-indentation)))
579
580 ;; HACK: want to go to the next correct definition location. we
581 ;; explicitly list them here. would be better to have them in a
582 ;; list.
583 (setq def-pos
584 (or (match-beginning class-paren)
585 (match-beginning def-paren)))
586
587 ;; if we don't have a starting indent level, take this one
588 (or start-indent
589 (setq start-indent cur-indent))
590
591 ;; if we don't have class name yet, take this one
592 (or prev-name
593 (setq prev-name def-name))
594
595 ;; what level is the next definition on? must be same, deeper
596 ;; or shallower indentation
597 (cond
598 ;; at the same indent level, add it to the list...
599 ((= start-indent cur-indent)
600
601 ;; if we don't have push, use the following...
602 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
603 (push (cons def-name def-pos) index-alist))
604
605 ;; deeper indented expression, recur...
606 ((< start-indent cur-indent)
607
608 ;; the point is currently on the expression we're supposed to
609 ;; start on, so go back to the last expression. The recursive
610 ;; call will find this place again and add it to the correct
611 ;; list
612 (re-search-backward imenu-example--python-generic-regexp
613 (point-min) 'move)
614 (setq sub-method-alist (imenu-example--create-python-index-engine
615 cur-indent))
616
617 (if sub-method-alist
618 ;; we put the last element on the index-alist on the start
619 ;; of the submethod alist so the user can still get to it.
620 (let ((save-elmt (pop index-alist)))
621 (push (cons (imenu-create-submenu-name prev-name)
622 (cons save-elmt sub-method-alist))
623 index-alist))))
624
625 ;; found less indented expression, we're done.
626 (t
627 (setq looking-p nil)
628 (re-search-backward imenu-example--python-generic-regexp
629 (point-min) t)))
630 (setq prev-name def-name)
631 (and looking-p
632 (setq looking-p
633 (re-search-forward imenu-example--python-generic-regexp
634 (point-max) 'move))))
635 (nreverse index-alist)))
636
Barry Warsaw42f707f1996-07-29 21:05:05 +0000637
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000638;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000639(defun python-mode ()
640 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000641To submit a problem report, enter `\\[py-submit-bug-report]' from a
642`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
643documentation. To see what version of `python-mode' you are running,
644enter `\\[py-version]'.
645
646This mode knows about Python indentation, tokens, comments and
647continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000648
649COMMANDS
650\\{py-mode-map}
651VARIABLES
652
Barry Warsaw42f707f1996-07-29 21:05:05 +0000653py-indent-offset\t\tindentation increment
654py-block-comment-prefix\t\tcomment string used by comment-region
655py-python-command\t\tshell command to invoke Python interpreter
656py-scroll-process-buffer\t\talways scroll Python process buffer
657py-temp-directory\t\tdirectory used for temp files (if needed)
658py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000659 (interactive)
660 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000661 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000662 (setq major-mode 'python-mode
663 mode-name "Python"
664 local-abbrev-table python-mode-abbrev-table)
665 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000666 ;; add the menu
667 (if py-menu
668 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000669 ;; Emacs 19 requires this
670 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
671 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000672 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000673 (mapcar (function (lambda (x)
674 (make-local-variable (car x))
675 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000676 '((paragraph-separate . "^[ \t]*$")
677 (paragraph-start . "^[ \t]*$")
678 (require-final-newline . t)
Barry Warsawa7891711996-08-01 15:53:09 +0000679 (comment-start . "# ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000680 (comment-start-skip . "# *")
681 (comment-column . 40)
682 (indent-region-function . py-indent-region)
683 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000684 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000685 ;;
686 ;; not sure where the magic comment has to be; to save time
687 ;; searching for a rarity, we give up if it's not found prior to the
688 ;; first executable statement.
689 ;;
690 ;; BAW - on first glance, this seems like complete hackery. Why was
691 ;; this necessary, and is it still necessary?
692 (let ((case-fold-search nil)
693 (start (point))
694 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000695 (if (re-search-forward
696 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
697 (prog2 (py-next-statement 1) (point) (goto-char 1))
698 t)
699 (progn
700 (setq new-tab-width
701 (string-to-int
702 (buffer-substring (match-beginning 1) (match-end 1))))
703 (if (= tab-width new-tab-width)
704 nil
705 (setq tab-width new-tab-width)
706 (message "Caution: tab-width changed to %d" new-tab-width)
707 (if py-beep-if-tab-change (beep)))))
708 (goto-char start))
709
Barry Warsaw755c6711996-08-01 20:02:55 +0000710 ;; install imenu
711 (setq imenu-create-index-function
712 (function imenu-example--create-python-index))
713 (if (fboundp 'imenu-add-to-menubar)
714 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
715
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000716 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000717 (if python-mode-hook
718 (run-hooks 'python-mode-hook)
719 (run-hooks 'py-mode-hook)))
720
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000721
Barry Warsaw826255b1996-03-22 16:09:34 +0000722(defun py-keep-region-active ()
Barry Warsawce60bc71996-08-01 18:17:14 +0000723 ;; do whatever is necessary to keep the region active in XEmacs.
724 ;; Ignore byte-compiler warnings you might see. Also note that
725 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
726 ;; require us to take explicit action.
Barry Warsaw826255b1996-03-22 16:09:34 +0000727 (and (boundp 'zmacs-region-stays)
728 (setq zmacs-region-stays t)))
729
Barry Warsawce60bc71996-08-01 18:17:14 +0000730
Barry Warsawb91b7431995-03-14 15:55:20 +0000731;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000732(defun py-outdent-p ()
733 ;; returns non-nil if the current line should outdent one level
734 (save-excursion
735 (and (progn (back-to-indentation)
736 (looking-at py-outdent-re))
737 (progn (backward-to-indentation 1)
738 (while (or (looking-at py-blank-or-comment-re)
739 (bobp))
740 (backward-to-indentation 1))
741 (not (looking-at py-no-outdent-re)))
742 )))
743
744
Barry Warsawb91b7431995-03-14 15:55:20 +0000745(defun py-electric-colon (arg)
746 "Insert a colon.
747In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000748argument is provided, that many colons are inserted non-electrically.
749Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000750 (interactive "P")
751 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000752 ;; are we in a string or comment?
753 (if (save-excursion
754 (let ((pps (parse-partial-sexp (save-excursion
755 (beginning-of-python-def-or-class)
756 (point))
757 (point))))
758 (not (or (nth 3 pps) (nth 4 pps)))))
759 (save-excursion
760 (let ((here (point))
761 (outdent 0)
762 (indent (py-compute-indentation)))
763 (if (and (not arg)
764 (py-outdent-p)
765 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000766 (py-next-statement -1)
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000767 (py-compute-indentation)))
768 )
769 (setq outdent py-indent-offset))
770 ;; Don't indent, only outdent. This assumes that any lines that
771 ;; are already outdented relative to py-compute-indentation were
772 ;; put there on purpose. Its highly annoying to have `:' indent
773 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
774 ;; there a better way to determine this???
775 (if (< (current-indentation) indent) nil
776 (goto-char here)
777 (beginning-of-line)
778 (delete-horizontal-space)
779 (indent-to (- indent outdent))
780 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000781
782
Barry Warsaw7ae77681994-12-12 20:38:05 +0000783;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000784(defun py-shell ()
785 "Start an interactive Python interpreter in another window.
786This is like Shell mode, except that Python is running in the window
787instead of a shell. See the `Interactive Shell' and `Shell Mode'
788sections of the Emacs manual for details, especially for the key
789bindings active in the `*Python*' buffer.
790
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000791See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000792behavior in the process window.
793
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000794Warning: Don't use an interactive Python if you change sys.ps1 or
795sys.ps2 from their default values, or if you're running code that
796prints `>>> ' or `... ' at the start of a line. `python-mode' can't
797distinguish your output from Python's output, and assumes that `>>> '
798at the start of a line is a prompt from Python. Similarly, the Emacs
799Shell mode code assumes that both `>>> ' and `... ' at the start of a
800line are Python prompts. Bad things can happen if you fool either
801mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000802
803Warning: If you do any editing *in* the process buffer *while* the
804buffer is accepting output from Python, do NOT attempt to `undo' the
805changes. Some of the output (nowhere near the parts you changed!) may
806be lost if you do. This appears to be an Emacs bug, an unfortunate
807interaction between undo and process filters; the same problem exists in
808non-Python process buffers using the default (Emacs-supplied) process
809filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000810 ;; BAW - should undo be disabled in the python process buffer, if
811 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812 (interactive)
813 (if py-this-is-emacs-19-p
814 (progn
815 (require 'comint)
816 (switch-to-buffer-other-window
817 (make-comint "Python" py-python-command)))
818 (progn
819 (require 'shell)
820 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000821 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000822 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000823 (make-local-variable 'shell-prompt-pattern)
824 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
825 (set-process-filter (get-buffer-process (current-buffer))
826 'py-process-filter)
827 (set-syntax-table py-mode-syntax-table))
828
829(defun py-execute-region (start end)
830 "Send the region between START and END to a Python interpreter.
831If there is a *Python* process it is used.
832
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000833Hint: If you want to execute part of a Python file several times
834\(e.g., perhaps you're developing a function and want to flesh it out
835a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
836the region of interest, and send the code to a *Python* process via
837`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000838
839Following are subtleties to note when using a *Python* process:
840
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000841If a *Python* process is used, the region is copied into a temporary
842file (in directory `py-temp-directory'), and an `execfile' command is
843sent to Python naming that file. If you send regions faster than
844Python can execute them, `python-mode' will save them into distinct
845temp files, and execute the next one in the queue the next time it
846sees a `>>> ' prompt from Python. Each time this happens, the process
847buffer is popped into a window (if it's not already in some window) so
848you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000849
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000850 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000851
852is inserted at the end.
853
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000854Caution: No more than 26 regions can be pending at any given time.
855This limit is (indirectly) inherited from libc's mktemp(3).
856`python-mode' does not try to protect you from exceeding the limit.
857It's extremely unlikely that you'll get anywhere close to the limit in
858practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000859
860See the `\\[py-shell]' docs for additional warnings."
861 (interactive "r")
862 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000863 (let ((pyproc (get-process "Python"))
864 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000865 (if (null pyproc)
866 (shell-command-on-region start end py-python-command)
867 ;; else feed it thru a temp file
868 (setq fname (py-make-temp-name))
869 (write-region start end fname nil 'no-msg)
870 (setq py-file-queue (append py-file-queue (list fname)))
871 (if (cdr py-file-queue)
872 (message "File %s queued for execution" fname)
873 ;; else
874 (py-execute-file pyproc fname)))))
875
876(defun py-execute-file (pyproc fname)
877 (py-append-to-process-buffer
878 pyproc
879 (format "## working on region in file %s ...\n" fname))
880 (process-send-string pyproc (format "execfile('%s')\n" fname)))
881
882(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000883 (let ((curbuf (current-buffer))
884 (pbuf (process-buffer pyproc))
885 (pmark (process-mark pyproc))
886 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887
888 ;; make sure we switch to a different buffer at least once. if we
889 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000890 ;; window, and point is before the end, and lots of output is
891 ;; coming at a fast pace, then (a) simple cursor-movement commands
892 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
893 ;; to have a visible effect (the window just doesn't get updated,
894 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
895 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 ;; #b makes no sense to me at all. #a almost makes sense: unless
898 ;; we actually change buffers, set_buffer_internal in buffer.c
899 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
900 ;; seems to make the Emacs command loop reluctant to update the
901 ;; display. Perhaps the default process filter in process.c's
902 ;; read_process_output has update_mode_lines++ for a similar
903 ;; reason? beats me ...
904
905 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906 (if (eq curbuf pbuf) ; mysterious ugly hack
907 (set-buffer (get-buffer-create "*scratch*")))
908
909 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000910 (let* ((start (point))
911 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000912 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000913 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000914 (goto-char pmark)
915 (insert string)
916 (move-marker pmark (point))
917 (setq file-finished
918 (and py-file-queue
919 (equal ">>> "
920 (buffer-substring
921 (prog2 (beginning-of-line) (point)
922 (goto-char pmark))
923 (point)))))
924 (if goback (goto-char start)
925 ;; else
926 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000927 (let* ((pop-up-windows t)
928 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000929 (set-window-point pwin (point)))))
930 (set-buffer curbuf)
931 (if file-finished
932 (progn
933 (py-delete-file-silently (car py-file-queue))
934 (setq py-file-queue (cdr py-file-queue))
935 (if py-file-queue
936 (py-execute-file pyproc (car py-file-queue)))))
937 (and goend
938 (progn (set-buffer pbuf)
939 (goto-char (point-max))))
940 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000941
942(defun py-execute-buffer ()
943 "Send the contents of the buffer to a Python interpreter.
944If there is a *Python* process buffer it is used. If a clipping
945restriction is in effect, only the accessible portion of the buffer is
946sent. A trailing newline will be supplied if needed.
947
948See the `\\[py-execute-region]' docs for an account of some subtleties."
949 (interactive)
950 (py-execute-region (point-min) (point-max)))
951
952
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000953
954;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000955(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000956 "Reduce indentation or delete character.
957If point is at the leftmost column, deletes the preceding newline.
958
959Else if point is at the leftmost non-blank character of a line that is
960neither a continuation line nor a non-indenting comment line, or if
961point is at the end of a blank line, reduces the indentation to match
962that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000963opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000964of where you are. With numeric count, outdents that many blocks (but
965not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966
967Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000968needed so that only a single column position is deleted. Numeric
969argument delets that many characters."
970 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971 (if (or (/= (current-indentation) (current-column))
972 (bolp)
973 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +0000974 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000975 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000976 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977 ;; else indent the same as the colon line that opened the block
978
979 ;; force non-blank so py-goto-block-up doesn't ignore it
980 (insert-char ?* 1)
981 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000982 (let ((base-indent 0) ; indentation of base line
983 (base-text "") ; and text of base line
984 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000985 (save-excursion
986 (while (< 0 count)
987 (condition-case nil ; in case no enclosing block
988 (progn
989 (py-goto-block-up 'no-mark)
990 (setq base-indent (current-indentation)
991 base-text (py-suck-up-leading-text)
992 base-found-p t))
993 (error nil))
994 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995 (delete-char 1) ; toss the dummy character
996 (delete-horizontal-space)
997 (indent-to base-indent)
998 (if base-found-p
999 (message "Closes block: %s" base-text)))))
1000
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001001;; required for pending-del and delsel modes
1002(put 'py-delete-char 'delete-selection 'supersede)
1003(put 'py-delete-char 'pending-delete 'supersede)
1004
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005(defun py-indent-line ()
1006 "Fix the indentation of the current line according to Python rules."
1007 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001008 (let* ((ci (current-indentation))
1009 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +00001010 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001011 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001012 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001013 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001014 (if (/= ci need)
1015 (save-excursion
1016 (beginning-of-line)
1017 (delete-horizontal-space)
1018 (indent-to need)))
1019 (if move-to-indentation-p (back-to-indentation))))
1020
1021(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001022 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023This is just `strives to' because correct indentation can't be computed
1024from scratch for Python code. In general, deletes the whitespace before
1025point, inserts a newline, and takes an educated guess as to how you want
1026the new line indented."
1027 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029 (if (< ci (current-column)) ; if point beyond indentation
1030 (newline-and-indent)
1031 ;; else try to act like newline-and-indent "normally" acts
1032 (beginning-of-line)
1033 (insert-char ?\n 1)
1034 (move-to-column ci))))
1035
1036(defun py-compute-indentation ()
1037 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001038 (let ((pps (parse-partial-sexp (save-excursion
1039 (beginning-of-python-def-or-class)
1040 (point))
1041 (point))))
1042 (beginning-of-line)
1043 (cond
1044 ;; are we inside a string or comment?
1045 ((or (nth 3 pps) (nth 4 pps))
1046 (save-excursion
1047 (if (not py-align-multiline-strings-p) 0
1048 ;; skip back over blank & non-indenting comment lines
1049 ;; note: will skip a blank or non-indenting comment line
1050 ;; that happens to be a continuation line too
1051 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1052 (back-to-indentation)
1053 (current-column))))
1054 ;; are we on a continuation line?
1055 ((py-continuation-line-p)
1056 (let ((startpos (point))
1057 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001058 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001059 (if open-bracket-pos
1060 (progn
1061 ;; align with first item in list; else a normal
1062 ;; indent beyond the line with the open bracket
1063 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1064 ;; is the first list item on the same line?
1065 (skip-chars-forward " \t")
1066 (if (null (memq (following-char) '(?\n ?# ?\\)))
1067 ; yes, so line up with it
1068 (current-column)
1069 ;; first list item on another line, or doesn't exist yet
1070 (forward-line 1)
1071 (while (and (< (point) startpos)
1072 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1073 (forward-line 1))
1074 (if (< (point) startpos)
1075 ;; again mimic the first list item
1076 (current-indentation)
1077 ;; else they're about to enter the first item
1078 (goto-char open-bracket-pos)
1079 (+ (current-indentation) py-indent-offset))))
1080
1081 ;; else on backslash continuation line
1082 (forward-line -1)
1083 (if (py-continuation-line-p) ; on at least 3rd line in block
1084 (current-indentation) ; so just continue the pattern
1085 ;; else started on 2nd line in block, so indent more.
1086 ;; if base line is an assignment with a start on a RHS,
1087 ;; indent to 2 beyond the leftmost "="; else skip first
1088 ;; chunk of non-whitespace characters on base line, + 1 more
1089 ;; column
1090 (end-of-line)
1091 (setq endpos (point) searching t)
1092 (back-to-indentation)
1093 (setq startpos (point))
1094 ;; look at all "=" from left to right, stopping at first
1095 ;; one not nested in a list or string
1096 (while searching
1097 (skip-chars-forward "^=" endpos)
1098 (if (= (point) endpos)
1099 (setq searching nil)
1100 (forward-char 1)
1101 (setq state (parse-partial-sexp startpos (point)))
1102 (if (and (zerop (car state)) ; not in a bracket
1103 (null (nth 3 state))) ; & not in a string
1104 (progn
1105 (setq searching nil) ; done searching in any case
1106 (setq found
1107 (not (or
1108 (eq (following-char) ?=)
1109 (memq (char-after (- (point) 2))
1110 '(?< ?> ?!)))))))))
1111 (if (or (not found) ; not an assignment
1112 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1113 (progn
1114 (goto-char startpos)
1115 (skip-chars-forward "^ \t\n")))
1116 (1+ (current-column))))))
1117
1118 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001119 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001120
Barry Warsawa7891711996-08-01 15:53:09 +00001121 ;; Dfn: "Indenting comment line". A line containing only a
1122 ;; comment, but which is treated like a statement for
1123 ;; indentation calculation purposes. Such lines are only
1124 ;; treated specially by the mode; they are not treated
1125 ;; specially by the Python interpreter.
1126
1127 ;; The rules for indenting comment lines are a line where:
1128 ;; - the first non-whitespace character is `#', and
1129 ;; - the character following the `#' is whitespace, and
1130 ;; - the line is outdented with respect to (i.e. to the left
1131 ;; of) the indentation of the preceding non-blank line.
1132
1133 ;; The first non-blank line following an indenting comment
1134 ;; line is given the same amount of indentation as the
1135 ;; indenting comment line.
1136
1137 ;; All other comment-only lines are ignored for indentation
1138 ;; purposes.
1139
1140 ;; Are we looking at a comment-only line which is *not* an
1141 ;; indenting comment line? If so, we assume that its been
1142 ;; placed at the desired indentation, so leave it alone.
1143 ;; Indenting comment lines are aligned as statements down
1144 ;; below.
1145 ((and (looking-at "[ \t]*#[^ \t\n]")
1146 ;; NOTE: this test will not be performed in older Emacsen
1147 (fboundp 'forward-comment)
1148 (<= (current-indentation)
1149 (save-excursion
1150 (forward-comment (- (point-max)))
1151 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001152 (current-indentation))
1153
1154 ;; else indentation based on that of the statement that
1155 ;; precedes us; use the first line of that statement to
1156 ;; establish the base, in case the user forced a non-std
1157 ;; indentation for the continuation lines (if any)
1158 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001159 ;; skip back over blank & non-indenting comment lines note:
1160 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001161 ;; happens to be a continuation line too. use fast Emacs 19
1162 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001163 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001164 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001165 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001166 (let (done)
1167 (while (not done)
1168 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1169 nil 'move)
1170 (setq done (or (eq py-honor-comment-indentation t)
1171 (bobp)
1172 (/= (following-char) ?#)
1173 (not (zerop (current-column)))))
1174 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001175 ;; if we landed inside a string, go to the beginning of that
1176 ;; string. this handles triple quoted, multi-line spanning
1177 ;; strings.
1178 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001179 (+ (current-indentation)
1180 (if (py-statement-opens-block-p)
1181 py-indent-offset
1182 (if (py-statement-closes-block-p)
1183 (- py-indent-offset)
1184 0)))
1185 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001186
1187(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001188 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001189By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001190`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001191Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001192`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001193their own buffer-local copy), both those currently existing and those
1194created later in the Emacs session.
1195
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001196Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001197There's no excuse for such foolishness, but sometimes you have to deal
1198with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199`py-indent-offset' to what it thinks it was when they created the
1200mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
1202Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001203looking for a line that opens a block of code. `py-indent-offset' is
1204set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001205statement following it. If the search doesn't succeed going forward,
1206it's tried again going backward."
1207 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001208 (let (new-value
1209 (start (point))
1210 restart
1211 (found nil)
1212 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001213 (py-goto-initial-line)
1214 (while (not (or found (eobp)))
1215 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1216 (progn
1217 (setq restart (point))
1218 (py-goto-initial-line)
1219 (if (py-statement-opens-block-p)
1220 (setq found t)
1221 (goto-char restart)))))
1222 (if found
1223 ()
1224 (goto-char start)
1225 (py-goto-initial-line)
1226 (while (not (or found (bobp)))
1227 (setq found
1228 (and
1229 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1230 (or (py-goto-initial-line) t) ; always true -- side effect
1231 (py-statement-opens-block-p)))))
1232 (setq colon-indent (current-indentation)
1233 found (and found (zerop (py-next-statement 1)))
1234 new-value (- (current-indentation) colon-indent))
1235 (goto-char start)
1236 (if found
1237 (progn
1238 (funcall (if global 'kill-local-variable 'make-local-variable)
1239 'py-indent-offset)
1240 (setq py-indent-offset new-value)
1241 (message "%s value of py-indent-offset set to %d"
1242 (if global "Global" "Local")
1243 py-indent-offset))
1244 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1245
1246(defun py-shift-region (start end count)
1247 (save-excursion
1248 (goto-char end) (beginning-of-line) (setq end (point))
1249 (goto-char start) (beginning-of-line) (setq start (point))
1250 (indent-rigidly start end count)))
1251
1252(defun py-shift-region-left (start end &optional count)
1253 "Shift region of Python code to the left.
1254The lines from the line containing the start of the current region up
1255to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001256shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257
1258If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001259many columns. With no active region, outdent only the current line.
1260You cannot outdent the region if any line is already at column zero."
1261 (interactive
1262 (let ((p (point))
1263 (m (mark))
1264 (arg current-prefix-arg))
1265 (if m
1266 (list (min p m) (max p m) arg)
1267 (list p (save-excursion (forward-line 1) (point)) arg))))
1268 ;; if any line is at column zero, don't shift the region
1269 (save-excursion
1270 (goto-char start)
1271 (while (< (point) end)
1272 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001273 (if (and (zerop (current-column))
1274 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001275 (error "Region is at left edge."))
1276 (forward-line 1)))
1277 (py-shift-region start end (- (prefix-numeric-value
1278 (or count py-indent-offset))))
1279 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280
1281(defun py-shift-region-right (start end &optional count)
1282 "Shift region of Python code to the right.
1283The lines from the line containing the start of the current region up
1284to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001285shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001286
1287If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001288many columns. With no active region, indent only the current line."
1289 (interactive
1290 (let ((p (point))
1291 (m (mark))
1292 (arg current-prefix-arg))
1293 (if m
1294 (list (min p m) (max p m) arg)
1295 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001297 (or count py-indent-offset)))
1298 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001299
1300(defun py-indent-region (start end &optional indent-offset)
1301 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001302
Barry Warsaw7ae77681994-12-12 20:38:05 +00001303The lines from the line containing the start of the current region up
1304to (but not including) the line containing the end of the region are
1305reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001306character in the first column, the first line is left alone and the
1307rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001308region is reindented with respect to the (closest code or indenting
1309comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001310
1311This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001312control structures are introduced or removed, or to reformat code
1313using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001314
1315If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001316the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001317used.
1318
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001319Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001320is called! This function does not compute proper indentation from
1321scratch (that's impossible in Python), it merely adjusts the existing
1322indentation to be correct in context.
1323
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001324Warning: This function really has no idea what to do with
1325non-indenting comment lines, and shifts them as if they were indenting
1326comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001327
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001328Special cases: whitespace is deleted from blank lines; continuation
1329lines are shifted by the same amount their initial line was shifted,
1330in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001331initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001332 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001333 (save-excursion
1334 (goto-char end) (beginning-of-line) (setq end (point-marker))
1335 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001336 (let ((py-indent-offset (prefix-numeric-value
1337 (or indent-offset py-indent-offset)))
1338 (indents '(-1)) ; stack of active indent levels
1339 (target-column 0) ; column to which to indent
1340 (base-shifted-by 0) ; amount last base line was shifted
1341 (indent-base (if (looking-at "[ \t\n]")
1342 (py-compute-indentation)
1343 0))
1344 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001345 (while (< (point) end)
1346 (setq ci (current-indentation))
1347 ;; figure out appropriate target column
1348 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001349 ((or (eq (following-char) ?#) ; comment in column 1
1350 (looking-at "[ \t]*$")) ; entirely blank
1351 (setq target-column 0))
1352 ((py-continuation-line-p) ; shift relative to base line
1353 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354 (t ; new base line
1355 (if (> ci (car indents)) ; going deeper; push it
1356 (setq indents (cons ci indents))
1357 ;; else we should have seen this indent before
1358 (setq indents (memq ci indents)) ; pop deeper indents
1359 (if (null indents)
1360 (error "Bad indentation in region, at line %d"
1361 (save-restriction
1362 (widen)
1363 (1+ (count-lines 1 (point)))))))
1364 (setq target-column (+ indent-base
1365 (* py-indent-offset
1366 (- (length indents) 2))))
1367 (setq base-shifted-by (- target-column ci))))
1368 ;; shift as needed
1369 (if (/= ci target-column)
1370 (progn
1371 (delete-horizontal-space)
1372 (indent-to target-column)))
1373 (forward-line 1))))
1374 (set-marker end nil))
1375
Barry Warsawa7891711996-08-01 15:53:09 +00001376(defun py-comment-region (beg end &optional arg)
1377 "Like `comment-region' but uses double hash (`#') comment starter."
1378 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001379 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001380 (comment-region beg end arg)))
1381
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001382
1383;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384(defun py-previous-statement (count)
1385 "Go to the start of previous Python statement.
1386If the statement at point is the i'th Python statement, goes to the
1387start of statement i-COUNT. If there is no such statement, goes to the
1388first statement. Returns count of statements left to move.
1389`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001390 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001391 (if (< count 0) (py-next-statement (- count))
1392 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001393 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001394 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001395 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396 (> count 0)
1397 (zerop (forward-line -1))
1398 (py-goto-statement-at-or-above))
1399 (setq count (1- count)))
1400 (if (> count 0) (goto-char start)))
1401 count))
1402
1403(defun py-next-statement (count)
1404 "Go to the start of next Python statement.
1405If the statement at point is the i'th Python statement, goes to the
1406start of statement i+COUNT. If there is no such statement, goes to the
1407last statement. Returns count of statements left to move. `Statements'
1408do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001410 (if (< count 0) (py-previous-statement (- count))
1411 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001412 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001413 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001414 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001415 (> count 0)
1416 (py-goto-statement-below))
1417 (setq count (1- count)))
1418 (if (> count 0) (goto-char start)))
1419 count))
1420
1421(defun py-goto-block-up (&optional nomark)
1422 "Move up to start of current block.
1423Go to the statement that starts the smallest enclosing block; roughly
1424speaking, this will be the closest preceding statement that ends with a
1425colon and is indented less than the statement you started on. If
1426successful, also sets the mark to the starting point.
1427
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001428`\\[py-mark-block]' can be used afterward to mark the whole code
1429block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001430
1431If called from a program, the mark will not be set if optional argument
1432NOMARK is not nil."
1433 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001434 (let ((start (point))
1435 (found nil)
1436 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001437 (py-goto-initial-line)
1438 ;; if on blank or non-indenting comment line, use the preceding stmt
1439 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1440 (progn
1441 (py-goto-statement-at-or-above)
1442 (setq found (py-statement-opens-block-p))))
1443 ;; search back for colon line indented less
1444 (setq initial-indent (current-indentation))
1445 (if (zerop initial-indent)
1446 ;; force fast exit
1447 (goto-char (point-min)))
1448 (while (not (or found (bobp)))
1449 (setq found
1450 (and
1451 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1452 (or (py-goto-initial-line) t) ; always true -- side effect
1453 (< (current-indentation) initial-indent)
1454 (py-statement-opens-block-p))))
1455 (if found
1456 (progn
1457 (or nomark (push-mark start))
1458 (back-to-indentation))
1459 (goto-char start)
1460 (error "Enclosing block not found"))))
1461
1462(defun beginning-of-python-def-or-class (&optional class)
1463 "Move point to start of def (or class, with prefix arg).
1464
1465Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001466arg, looks for a `class' instead. The docs assume the `def' case;
1467just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001468
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001469If point is in a def statement already, and after the `d', simply
1470moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001471
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001472Else (point is not in a def statement, or at or before the `d' of a
1473def statement), searches for the closest preceding def statement, and
1474leaves point at its start. If no such statement can be found, leaves
1475point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001476
1477Returns t iff a def statement is found by these rules.
1478
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479Note that doing this command repeatedly will take you closer to the
1480start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001481
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001482If you want to mark the current def/class, see
1483`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001484 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001485 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1486 (start-of-line (progn (beginning-of-line) (point)))
1487 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001488 (if (or (/= start-of-stmt start-of-line)
1489 (not at-or-before-p))
1490 (end-of-line)) ; OK to match on this line
1491 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001493
1494(defun end-of-python-def-or-class (&optional class)
1495 "Move point beyond end of def (or class, with prefix arg) body.
1496
1497By default, looks for an appropriate `def'. If you supply a prefix arg,
1498looks for a `class' instead. The docs assume the `def' case; just
1499substitute `class' for `def' for the other case.
1500
1501If point is in a def statement already, this is the def we use.
1502
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503Else if the def found by `\\[beginning-of-python-def-or-class]'
1504contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001505
1506Else we search forward for the closest following def, and use that.
1507
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001508If a def can be found by these rules, point is moved to the start of
1509the line immediately following the def block, and the position of the
1510start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001511
1512Else point is moved to the end of the buffer, and nil is returned.
1513
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001514Note that doing this command repeatedly will take you closer to the
1515end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001516
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517If you want to mark the current def/class, see
1518`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001519 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001520 (let ((start (progn (py-goto-initial-line) (point)))
1521 (which (if class "class" "def"))
1522 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001523 ;; move point to start of appropriate def/class
1524 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1525 (setq state 'at-beginning)
1526 ;; else see if beginning-of-python-def-or-class hits container
1527 (if (and (beginning-of-python-def-or-class class)
1528 (progn (py-goto-beyond-block)
1529 (> (point) start)))
1530 (setq state 'at-end)
1531 ;; else search forward
1532 (goto-char start)
1533 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1534 (progn (setq state 'at-beginning)
1535 (beginning-of-line)))))
1536 (cond
1537 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1538 ((eq state 'at-end) t)
1539 ((eq state 'not-found) nil)
1540 (t (error "internal error in end-of-python-def-or-class")))))
1541
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542
1543;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544(defun py-mark-block (&optional extend just-move)
1545 "Mark following block of lines. With prefix arg, mark structure.
1546Easier to use than explain. It sets the region to an `interesting'
1547block of succeeding lines. If point is on a blank line, it goes down to
1548the next non-blank line. That will be the start of the region. The end
1549of the region depends on the kind of line at the start:
1550
1551 - If a comment, the region will include all succeeding comment lines up
1552 to (but not including) the next non-comment line (if any).
1553
1554 - Else if a prefix arg is given, and the line begins one of these
1555 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556
1557 if elif else try except finally for while def class
1558
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559 the region will be set to the body of the structure, including
1560 following blocks that `belong' to it, but excluding trailing blank
1561 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001562 and all (if any) of the following `except' and `finally' blocks
1563 that belong to the `try' structure will be in the region. Ditto
1564 for if/elif/else, for/else and while/else structures, and (a bit
1565 degenerate, since they're always one-block structures) def and
1566 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567
1568 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001569 block (see list above), and the block is not a `one-liner' (i.e.,
1570 the statement ends with a colon, not with code), the region will
1571 include all succeeding lines up to (but not including) the next
1572 code statement (if any) that's indented no more than the starting
1573 line, except that trailing blank and comment lines are excluded.
1574 E.g., if the starting line begins a multi-statement `def'
1575 structure, the region will be set to the full function definition,
1576 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577
1578 - Else the region will include all succeeding lines up to (but not
1579 including) the next blank line, or code or indenting-comment line
1580 indented strictly less than the starting line. Trailing indenting
1581 comment lines are included in this case, but not trailing blank
1582 lines.
1583
1584A msg identifying the location of the mark is displayed in the echo
1585area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1586
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001587If called from a program, optional argument EXTEND plays the role of
1588the prefix arg, and if optional argument JUST-MOVE is not nil, just
1589moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001590 (interactive "P") ; raw prefix arg
1591 (py-goto-initial-line)
1592 ;; skip over blank lines
1593 (while (and
1594 (looking-at "[ \t]*$") ; while blank line
1595 (not (eobp))) ; & somewhere to go
1596 (forward-line 1))
1597 (if (eobp)
1598 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001599 (let ((initial-pos (point))
1600 (initial-indent (current-indentation))
1601 last-pos ; position of last stmt in region
1602 (followers
1603 '((if elif else) (elif elif else) (else)
1604 (try except finally) (except except) (finally)
1605 (for else) (while else)
1606 (def) (class) ) )
1607 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001608
1609 (cond
1610 ;; if comment line, suck up the following comment lines
1611 ((looking-at "[ \t]*#")
1612 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1613 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1614 (setq last-pos (point)))
1615
1616 ;; else if line is a block line and EXTEND given, suck up
1617 ;; the whole structure
1618 ((and extend
1619 (setq first-symbol (py-suck-up-first-keyword) )
1620 (assq first-symbol followers))
1621 (while (and
1622 (or (py-goto-beyond-block) t) ; side effect
1623 (forward-line -1) ; side effect
1624 (setq last-pos (point)) ; side effect
1625 (py-goto-statement-below)
1626 (= (current-indentation) initial-indent)
1627 (setq next-symbol (py-suck-up-first-keyword))
1628 (memq next-symbol (cdr (assq first-symbol followers))))
1629 (setq first-symbol next-symbol)))
1630
1631 ;; else if line *opens* a block, search for next stmt indented <=
1632 ((py-statement-opens-block-p)
1633 (while (and
1634 (setq last-pos (point)) ; always true -- side effect
1635 (py-goto-statement-below)
1636 (> (current-indentation) initial-indent))
1637 nil))
1638
1639 ;; else plain code line; stop at next blank line, or stmt or
1640 ;; indenting comment line indented <
1641 (t
1642 (while (and
1643 (setq last-pos (point)) ; always true -- side effect
1644 (or (py-goto-beyond-final-line) t)
1645 (not (looking-at "[ \t]*$")) ; stop at blank line
1646 (or
1647 (>= (current-indentation) initial-indent)
1648 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1649 nil)))
1650
1651 ;; skip to end of last stmt
1652 (goto-char last-pos)
1653 (py-goto-beyond-final-line)
1654
1655 ;; set mark & display
1656 (if just-move
1657 () ; just return
1658 (push-mark (point) 'no-msg)
1659 (forward-line -1)
1660 (message "Mark set after: %s" (py-suck-up-leading-text))
1661 (goto-char initial-pos))))
1662
1663(defun mark-python-def-or-class (&optional class)
1664 "Set region to body of def (or class, with prefix arg) enclosing point.
1665Pushes the current mark, then point, on the mark ring (all language
1666modes do this, but although it's handy it's never documented ...).
1667
1668In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1670`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001671
1672And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673Turned out that was more confusing than useful: the `goto start' and
1674`goto end' commands are usually used to search through a file, and
1675people expect them to act a lot like `search backward' and `search
1676forward' string-search commands. But because Python `def' and `class'
1677can nest to arbitrary levels, finding the smallest def containing
1678point cannot be done via a simple backward search: the def containing
1679point may not be the closest preceding def, or even the closest
1680preceding def that's indented less. The fancy algorithm required is
1681appropriate for the usual uses of this `mark' command, but not for the
1682`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001684So the def marked by this command may not be the one either of the
1685`goto' commands find: If point is on a blank or non-indenting comment
1686line, moves back to start of the closest preceding code statement or
1687indenting comment line. If this is a `def' statement, that's the def
1688we use. Else searches for the smallest enclosing `def' block and uses
1689that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001690
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001691When an enclosing def is found: The mark is left immediately beyond
1692the last line of the def block. Point is left at the start of the
1693def, except that: if the def is preceded by a number of comment lines
1694followed by (at most) one optional blank line, point is left at the
1695start of the comments; else if the def is preceded by a blank line,
1696point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697
1698The intent is to mark the containing def/class and its associated
1699documentation, to make moving and duplicating functions and classes
1700pleasant."
1701 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001702 (let ((start (point))
1703 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001704 (push-mark start)
1705 (if (not (py-go-up-tree-to-keyword which))
1706 (progn (goto-char start)
1707 (error "Enclosing %s not found" which))
1708 ;; else enclosing def/class found
1709 (setq start (point))
1710 (py-goto-beyond-block)
1711 (push-mark (point))
1712 (goto-char start)
1713 (if (zerop (forward-line -1)) ; if there is a preceding line
1714 (progn
1715 (if (looking-at "[ \t]*$") ; it's blank
1716 (setq start (point)) ; so reset start point
1717 (goto-char start)) ; else try again
1718 (if (zerop (forward-line -1))
1719 (if (looking-at "[ \t]*#") ; a comment
1720 ;; look back for non-comment line
1721 ;; tricky: note that the regexp matches a blank
1722 ;; line, cuz \n is in the 2nd character class
1723 (and
1724 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1725 (forward-line 1))
1726 ;; no comment, so go back
1727 (goto-char start))))))))
1728
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001729;; ripped from cc-mode
1730(defun py-forward-into-nomenclature (&optional arg)
1731 "Move forward to end of a nomenclature section or word.
1732With arg, to it arg times.
1733
1734A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1735 (interactive "p")
1736 (let ((case-fold-search nil))
1737 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001738 (re-search-forward
1739 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1740 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001741 (while (and (< arg 0)
1742 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001743 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001744 (point-min) 0))
1745 (forward-char 1)
1746 (setq arg (1+ arg)))))
1747 (py-keep-region-active))
1748
1749(defun py-backward-into-nomenclature (&optional arg)
1750 "Move backward to beginning of a nomenclature section or word.
1751With optional ARG, move that many times. If ARG is negative, move
1752forward.
1753
1754A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1755 (interactive "p")
1756 (py-forward-into-nomenclature (- arg))
1757 (py-keep-region-active))
1758
1759
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001760
1761;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762
1763;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1765;; out of the right places, along with the keys they're on & current
1766;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001767(defun py-dump-help-string (str)
1768 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001769 (let ((locals (buffer-local-variables))
1770 funckind funcname func funcdoc
1771 (start 0) mstart end
1772 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001773 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1774 (setq mstart (match-beginning 0) end (match-end 0)
1775 funckind (substring str (match-beginning 1) (match-end 1))
1776 funcname (substring str (match-beginning 2) (match-end 2))
1777 func (intern funcname))
1778 (princ (substitute-command-keys (substring str start mstart)))
1779 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780 ((equal funckind "c") ; command
1781 (setq funcdoc (documentation func)
1782 keys (concat
1783 "Key(s): "
1784 (mapconcat 'key-description
1785 (where-is-internal func py-mode-map)
1786 ", "))))
1787 ((equal funckind "v") ; variable
1788 (setq funcdoc (substitute-command-keys
1789 (get func 'variable-documentation))
1790 keys (if (assq func locals)
1791 (concat
1792 "Local/Global values: "
1793 (prin1-to-string (symbol-value func))
1794 " / "
1795 (prin1-to-string (default-value func)))
1796 (concat
1797 "Value: "
1798 (prin1-to-string (symbol-value func))))))
1799 (t ; unexpected
1800 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001801 (princ (format "\n-> %s:\t%s\t%s\n\n"
1802 (if (equal funckind "c") "Command" "Variable")
1803 funcname keys))
1804 (princ funcdoc)
1805 (terpri)
1806 (setq start end))
1807 (princ (substitute-command-keys (substring str start))))
1808 (print-help-return-message)))
1809
1810(defun py-describe-mode ()
1811 "Dump long form of Python-mode docs."
1812 (interactive)
1813 (py-dump-help-string "Major mode for editing Python files.
1814Knows about Python indentation, tokens, comments and continuation lines.
1815Paragraphs are separated by blank lines only.
1816
1817Major sections below begin with the string `@'; specific function and
1818variable docs begin with `->'.
1819
1820@EXECUTING PYTHON CODE
1821
1822\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1823\\[py-execute-region]\tsends the current region
1824\\[py-shell]\tstarts a Python interpreter window; this will be used by
1825\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1826%c:py-execute-buffer
1827%c:py-execute-region
1828%c:py-shell
1829
1830@VARIABLES
1831
1832py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001833py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
1835py-python-command\tshell command to invoke Python interpreter
1836py-scroll-process-buffer\talways scroll Python process buffer
1837py-temp-directory\tdirectory used for temp files (if needed)
1838
1839py-beep-if-tab-change\tring the bell if tab-width is changed
1840%v:py-indent-offset
1841%v:py-block-comment-prefix
1842%v:py-python-command
1843%v:py-scroll-process-buffer
1844%v:py-temp-directory
1845%v:py-beep-if-tab-change
1846
1847@KINDS OF LINES
1848
1849Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001850preceding line ends with a backslash that's not part of a comment, or
1851the paren/bracket/brace nesting level at the start of the line is
1852non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853
1854An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001855possibly blanks or tabs), a `comment line' (leftmost non-blank
1856character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001857
1858Comment Lines
1859
1860Although all comment lines are treated alike by Python, Python mode
1861recognizes two kinds that act differently with respect to indentation.
1862
1863An `indenting comment line' is a comment line with a blank, tab or
1864nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866indenting comment line will be indented like the comment line. All
1867other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001868following the initial `#') are `non-indenting comment lines', and
1869their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001870
1871Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872whenever possible. Non-indenting comment lines are useful in cases
1873like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874
1875\ta = b # a very wordy single-line comment that ends up being
1876\t #... continued onto another line
1877
1878\tif a == b:
1879##\t\tprint 'panic!' # old code we've `commented out'
1880\t\treturn a
1881
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001882Since the `#...' and `##' comment lines have a non-whitespace
1883character following the initial `#', Python mode ignores them when
1884computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885
1886Continuation Lines and Statements
1887
1888The Python-mode commands generally work on statements instead of on
1889individual lines, where a `statement' is a comment or blank line, or a
1890code line and all of its following continuation lines (if any)
1891considered as a single logical unit. The commands in this mode
1892generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001893statement containing point, even if point happens to be in the middle
1894of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895
1896
1897@INDENTATION
1898
1899Primarily for entering new code:
1900\t\\[indent-for-tab-command]\t indent line appropriately
1901\t\\[py-newline-and-indent]\t insert newline, then indent
1902\t\\[py-delete-char]\t reduce indentation, or delete single character
1903
1904Primarily for reindenting existing code:
1905\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1906\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1907
1908\t\\[py-indent-region]\t reindent region to match its context
1909\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1910\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1911
1912Unlike most programming languages, Python uses indentation, and only
1913indentation, to specify block structure. Hence the indentation supplied
1914automatically by Python-mode is just an educated guess: only you know
1915the block structure you intend, so only you can supply correct
1916indentation.
1917
1918The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1919the indentation of preceding statements. E.g., assuming
1920py-indent-offset is 4, after you enter
1921\tif a > 0: \\[py-newline-and-indent]
1922the cursor will be moved to the position of the `_' (_ is not a
1923character in the file, it's just used here to indicate the location of
1924the cursor):
1925\tif a > 0:
1926\t _
1927If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1928to
1929\tif a > 0:
1930\t c = d
1931\t _
1932Python-mode cannot know whether that's what you intended, or whether
1933\tif a > 0:
1934\t c = d
1935\t_
1936was your intent. In general, Python-mode either reproduces the
1937indentation of the (closest code or indenting-comment) preceding
1938statement, or adds an extra py-indent-offset blanks if the preceding
1939statement has `:' as its last significant (non-whitespace and non-
1940comment) character. If the suggested indentation is too much, use
1941\\[py-delete-char] to reduce it.
1942
1943Continuation lines are given extra indentation. If you don't like the
1944suggested indentation, change it to something you do like, and Python-
1945mode will strive to indent later lines of the statement in the same way.
1946
1947If a line is a continuation line by virtue of being in an unclosed
1948paren/bracket/brace structure (`list', for short), the suggested
1949indentation depends on whether the current line contains the first item
1950in the list. If it does, it's indented py-indent-offset columns beyond
1951the indentation of the line containing the open bracket. If you don't
1952like that, change it by hand. The remaining items in the list will mimic
1953whatever indentation you give to the first item.
1954
1955If a line is a continuation line because the line preceding it ends with
1956a backslash, the third and following lines of the statement inherit their
1957indentation from the line preceding them. The indentation of the second
1958line in the statement depends on the form of the first (base) line: if
1959the base line is an assignment statement with anything more interesting
1960than the backslash following the leftmost assigning `=', the second line
1961is indented two columns beyond that `='. Else it's indented to two
1962columns beyond the leftmost solid chunk of non-whitespace characters on
1963the base line.
1964
1965Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1966repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1967structure you intend.
1968%c:indent-for-tab-command
1969%c:py-newline-and-indent
1970%c:py-delete-char
1971
1972
1973The next function may be handy when editing code you didn't write:
1974%c:py-guess-indent-offset
1975
1976
1977The remaining `indent' functions apply to a region of Python code. They
1978assume the block structure (equals indentation, in Python) of the region
1979is correct, and alter the indentation in various ways while preserving
1980the block structure:
1981%c:py-indent-region
1982%c:py-shift-region-left
1983%c:py-shift-region-right
1984
1985@MARKING & MANIPULATING REGIONS OF CODE
1986
1987\\[py-mark-block]\t mark block of lines
1988\\[mark-python-def-or-class]\t mark smallest enclosing def
1989\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001990\\[comment-region]\t comment out region of code
1991\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00001992%c:py-mark-block
1993%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001994%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001995
1996@MOVING POINT
1997
1998\\[py-previous-statement]\t move to statement preceding point
1999\\[py-next-statement]\t move to statement following point
2000\\[py-goto-block-up]\t move up to start of current block
2001\\[beginning-of-python-def-or-class]\t move to start of def
2002\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2003\\[end-of-python-def-or-class]\t move to end of def
2004\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2005
2006The first two move to one statement beyond the statement that contains
2007point. A numeric prefix argument tells them to move that many
2008statements instead. Blank lines, comment lines, and continuation lines
2009do not count as `statements' for these commands. So, e.g., you can go
2010to the first code statement in a file by entering
2011\t\\[beginning-of-buffer]\t to move to the top of the file
2012\t\\[py-next-statement]\t to skip over initial comments and blank lines
2013Or do `\\[py-previous-statement]' with a huge prefix argument.
2014%c:py-previous-statement
2015%c:py-next-statement
2016%c:py-goto-block-up
2017%c:beginning-of-python-def-or-class
2018%c:end-of-python-def-or-class
2019
2020@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2021
2022`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2023
2024`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2025overall class and def structure of a module.
2026
2027`\\[back-to-indentation]' moves point to a line's first non-blank character.
2028
2029`\\[indent-relative]' is handy for creating odd indentation.
2030
2031@OTHER EMACS HINTS
2032
2033If you don't like the default value of a variable, change its value to
2034whatever you do like by putting a `setq' line in your .emacs file.
2035E.g., to set the indentation increment to 4, put this line in your
2036.emacs:
2037\t(setq py-indent-offset 4)
2038To see the value of a variable, do `\\[describe-variable]' and enter the variable
2039name at the prompt.
2040
2041When entering a key sequence like `C-c C-n', it is not necessary to
2042release the CONTROL key after doing the `C-c' part -- it suffices to
2043press the CONTROL key, press and release `c' (while still holding down
2044CONTROL), press and release `n' (while still holding down CONTROL), &
2045then release CONTROL.
2046
2047Entering Python mode calls with no arguments the value of the variable
2048`python-mode-hook', if that value exists and is not nil; for backward
2049compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2050the Elisp manual for details.
2051
2052Obscure: When python-mode is first loaded, it looks for all bindings
2053to newline-and-indent in the global keymap, and shadows them with
2054local bindings to py-newline-and-indent."))
2055
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002056
2057;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002058(defvar py-parse-state-re
2059 (concat
2060 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2061 "\\|"
2062 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002063
Barry Warsaw7ae77681994-12-12 20:38:05 +00002064;; returns the parse state at point (see parse-partial-sexp docs)
2065(defun py-parse-state ()
2066 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002067 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002068 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002069 (while (not done)
2070 ;; back up to the first preceding line (if any; else start of
2071 ;; buffer) that begins with a popular Python keyword, or a
2072 ;; non- whitespace and non-comment character. These are good
2073 ;; places to start parsing to see whether where we started is
2074 ;; at a non-zero nesting level. It may be slow for people who
2075 ;; write huge code blocks or huge lists ... tough beans.
2076 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002077 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002078 (beginning-of-line)
2079 (save-excursion
2080 (setq pps (parse-partial-sexp (point) here)))
2081 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002082 (setq done (or (zerop ci)
2083 (not (nth 3 pps))
2084 (bobp)))
2085 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002086 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002087
2088;; if point is at a non-zero nesting level, returns the number of the
2089;; character that opens the smallest enclosing unclosed list; else
2090;; returns nil.
2091(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002092 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002093 (if (zerop (car status))
2094 nil ; not in a nest
2095 (car (cdr status))))) ; char# of open bracket
2096
2097;; t iff preceding line ends with backslash that's not in a comment
2098(defun py-backslash-continuation-line-p ()
2099 (save-excursion
2100 (beginning-of-line)
2101 (and
2102 ;; use a cheap test first to avoid the regexp if possible
2103 ;; use 'eq' because char-after may return nil
2104 (eq (char-after (- (point) 2)) ?\\ )
2105 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002106 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107 (looking-at py-continued-re))))
2108
2109;; t iff current line is a continuation line
2110(defun py-continuation-line-p ()
2111 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002112 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002113 (or (py-backslash-continuation-line-p)
2114 (py-nesting-level))))
2115
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002116;; go to initial line of current statement; usually this is the line
2117;; we're on, but if we're on the 2nd or following lines of a
2118;; continuation block, we need to go up to the first line of the
2119;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002120;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002121;; Tricky: We want to avoid quadratic-time behavior for long continued
2122;; blocks, whether of the backslash or open-bracket varieties, or a
2123;; mix of the two. The following manages to do that in the usual
2124;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002125(defun py-goto-initial-line ()
2126 (let ( open-bracket-pos )
2127 (while (py-continuation-line-p)
2128 (beginning-of-line)
2129 (if (py-backslash-continuation-line-p)
2130 (while (py-backslash-continuation-line-p)
2131 (forward-line -1))
2132 ;; else zip out of nested brackets/braces/parens
2133 (while (setq open-bracket-pos (py-nesting-level))
2134 (goto-char open-bracket-pos)))))
2135 (beginning-of-line))
2136
2137;; go to point right beyond final line of current statement; usually
2138;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002139;; statement we need to skip over the continuation lines. Tricky:
2140;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141(defun py-goto-beyond-final-line ()
2142 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002143 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144 (while (and (py-continuation-line-p)
2145 (not (eobp)))
2146 ;; skip over the backslash flavor
2147 (while (and (py-backslash-continuation-line-p)
2148 (not (eobp)))
2149 (forward-line 1))
2150 ;; if in nest, zip to the end of the nest
2151 (setq state (py-parse-state))
2152 (if (and (not (zerop (car state)))
2153 (not (eobp)))
2154 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002155 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156 ;; the 3rd argument should be plain 0
2157 (parse-partial-sexp (point) (point-max) (- 0 (car state))
2158 nil state)
2159 (forward-line 1))))))
2160
2161;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002162;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002163(defun py-statement-opens-block-p ()
2164 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002165 (let ((start (point))
2166 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2167 (searching t)
2168 (answer nil)
2169 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170 (goto-char start)
2171 (while searching
2172 ;; look for a colon with nothing after it except whitespace, and
2173 ;; maybe a comment
2174 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2175 finish t)
2176 (if (eq (point) finish) ; note: no `else' clause; just
2177 ; keep searching if we're not at
2178 ; the end yet
2179 ;; sure looks like it opens a block -- but it might
2180 ;; be in a comment
2181 (progn
2182 (setq searching nil) ; search is done either way
2183 (setq state (parse-partial-sexp start
2184 (match-beginning 0)))
2185 (setq answer (not (nth 4 state)))))
2186 ;; search failed: couldn't find another interesting colon
2187 (setq searching nil)))
2188 answer)))
2189
Barry Warsawf831d811996-07-31 20:42:59 +00002190(defun py-statement-closes-block-p ()
2191 ;; true iff the current statement `closes' a block == the line
2192 ;; starts with `return', `raise', `break' or `continue'. doesn't
2193 ;; catch embedded statements
2194 (let ((here (point)))
2195 (back-to-indentation)
2196 (prog1
2197 (looking-at "\\(return\\|raise\\|break\\|continue\\)\\>")
2198 (goto-char here))))
2199
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200;; go to point right beyond final line of block begun by the current
2201;; line. This is the same as where py-goto-beyond-final-line goes
2202;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002203;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002204(defun py-goto-beyond-block ()
2205 (if (py-statement-opens-block-p)
2206 (py-mark-block nil 'just-move)
2207 (py-goto-beyond-final-line)))
2208
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002209;; go to start of first statement (not blank or comment or
2210;; continuation line) at or preceding point. returns t if there is
2211;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002212(defun py-goto-statement-at-or-above ()
2213 (py-goto-initial-line)
2214 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002215 ;; skip back over blank & comment lines
2216 ;; note: will skip a blank or comment line that happens to be
2217 ;; a continuation line too
2218 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2219 (progn (py-goto-initial-line) t)
2220 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002221 t))
2222
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002223;; go to start of first statement (not blank or comment or
2224;; continuation line) following the statement containing point returns
2225;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226(defun py-goto-statement-below ()
2227 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002228 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002229 (py-goto-beyond-final-line)
2230 (while (and
2231 (looking-at py-blank-or-comment-re)
2232 (not (eobp)))
2233 (forward-line 1))
2234 (if (eobp)
2235 (progn (goto-char start) nil)
2236 t)))
2237
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002238;; go to start of statement, at or preceding point, starting with
2239;; keyword KEY. Skips blank lines and non-indenting comments upward
2240;; first. If that statement starts with KEY, done, else go back to
2241;; first enclosing block starting with KEY. If successful, leaves
2242;; point at the start of the KEY line & returns t. Else leaves point
2243;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002244(defun py-go-up-tree-to-keyword (key)
2245 ;; skip blanks and non-indenting #
2246 (py-goto-initial-line)
2247 (while (and
2248 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2249 (zerop (forward-line -1))) ; go back
2250 nil)
2251 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002252 (let* ((re (concat "[ \t]*" key "\\b"))
2253 (case-fold-search nil) ; let* so looking-at sees this
2254 (found (looking-at re))
2255 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002256 (while (not (or found dead))
2257 (condition-case nil ; in case no enclosing block
2258 (py-goto-block-up 'no-mark)
2259 (error (setq dead t)))
2260 (or dead (setq found (looking-at re))))
2261 (beginning-of-line)
2262 found))
2263
2264;; return string in buffer from start of indentation to end of line;
2265;; prefix "..." if leading whitespace was skipped
2266(defun py-suck-up-leading-text ()
2267 (save-excursion
2268 (back-to-indentation)
2269 (concat
2270 (if (bolp) "" "...")
2271 (buffer-substring (point) (progn (end-of-line) (point))))))
2272
2273;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2274;; as a Lisp symbol; return nil if none
2275(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002276 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002277 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2278 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2279 nil)))
2280
2281(defun py-make-temp-name ()
2282 (make-temp-name
2283 (concat (file-name-as-directory py-temp-directory) "python")))
2284
2285(defun py-delete-file-silently (fname)
2286 (condition-case nil
2287 (delete-file fname)
2288 (error nil)))
2289
2290(defun py-kill-emacs-hook ()
2291 ;; delete our temp files
2292 (while py-file-queue
2293 (py-delete-file-silently (car py-file-queue))
2294 (setq py-file-queue (cdr py-file-queue)))
2295 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2296 ;; run the hook we inherited, if any
2297 (and py-inherited-kill-emacs-hook
2298 (funcall py-inherited-kill-emacs-hook))))
2299
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002300;; make PROCESS's buffer visible, append STRING to it, and force
2301;; display; also make shell-mode believe the user typed this string,
2302;; so that kill-output-from-shell and show-output-from-shell work
2303;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002305 (let ((cbuf (current-buffer))
2306 (pbuf (process-buffer process))
2307 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002308 (set-buffer pbuf)
2309 (goto-char (point-max))
2310 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002311 (if (not (or py-this-is-emacs-19-p
2312 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002313 (move-marker last-input-start (point))) ; muck w/ shell-mode
2314 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002315 (if (not (or py-this-is-emacs-19-p
2316 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002317 (move-marker last-input-end (point))) ; muck w/ shell-mode
2318 (set-buffer cbuf))
2319 (sit-for 0))
2320
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002321
2322
Barry Warsaw850437a1995-03-08 21:50:28 +00002323(defconst py-version "$Revision$"
2324 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002325(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002326 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002327
Barry Warsaw850437a1995-03-08 21:50:28 +00002328(defun py-version ()
2329 "Echo the current version of `python-mode' in the minibuffer."
2330 (interactive)
2331 (message "Using `python-mode' version %s" py-version)
2332 (py-keep-region-active))
2333
2334;; only works under Emacs 19
2335;(eval-when-compile
2336; (require 'reporter))
2337
2338(defun py-submit-bug-report (enhancement-p)
2339 "Submit via mail a bug report on `python-mode'.
2340With \\[universal-argument] just submit an enhancement request."
2341 (interactive
2342 (list (not (y-or-n-p
2343 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002344 (let ((reporter-prompt-for-summary-p (if enhancement-p
2345 "(Very) brief summary: "
2346 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002347 (require 'reporter)
2348 (reporter-submit-bug-report
2349 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002350 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002351 ;; varlist
2352 (if enhancement-p nil
2353 '(py-python-command
2354 py-indent-offset
2355 py-block-comment-prefix
2356 py-scroll-process-buffer
2357 py-temp-directory
2358 py-beep-if-tab-change))
2359 nil ;pre-hooks
2360 nil ;post-hooks
2361 "Dear Barry,") ;salutation
2362 (if enhancement-p nil
2363 (set-mark (point))
2364 (insert
2365"Please replace this text with a sufficiently large code sample\n\
2366and an exact recipe so that I can reproduce your problem. Failure\n\
2367to do so may mean a greater delay in fixing your bug.\n\n")
2368 (exchange-point-and-mark)
2369 (py-keep-region-active))))
2370
2371
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002372;; arrange to kill temp files when Emacs exists
2373(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2374 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2375 ;; have to trust that other people are as respectful of our hook
2376 ;; fiddling as we are of theirs
2377 (if (boundp 'py-inherited-kill-emacs-hook)
2378 ;; we were loaded before -- trust others not to have screwed us
2379 ;; in the meantime (no choice, really)
2380 nil
2381 ;; else arrange for our hook to run theirs
2382 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2383 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2384
2385
2386
2387(provide 'python-mode)
2388;;; python-mode.el ends here