blob: 13634482647fb4ba330d2dd71439919e6a67781a [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 Warsaw755c6711996-08-01 20:02:55 +000020
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000022;; by Tim Peters after an original idea by Michael A. Guravage. Tim
23;; subsequently left the net; in 1995, Barry Warsaw inherited the
24;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
Barry Warsaw755c6711996-08-01 20:02:55 +000027;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
28;; 18 support. But all in all, the mode works exceedingly well, and
29;; I've simply been tweaking it as I go along. Ain't it wonderful
30;; that Python has a much more sane syntax than C? (or <shudder> C++?!
31;; :-). I can say that; I maintain cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
33;; The following statements, placed in your .emacs file or
34;; site-init.el, will cause this file to be autoloaded, and
35;; python-mode invoked, when visiting .py files (assuming this file is
36;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000037;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000041;;
42;; If you want font-lock support for Python source code (a.k.a. syntax
43;; coloring, highlighting), add this to your .emacs file:
44;;
45;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000046;;
47;; But you better be sure you're version of Emacs supports
48;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
49;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000050
Barry Warsaw3fcaf611996-08-01 20:11:51 +000051;; Here's a brief list of recent additions/improvements/changes:
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000052;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000053;; - Wrapping and indentation within triple quote strings now works.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000054;; - `Standard' bug reporting mechanism (use C-c C-b)
55;; - py-mark-block was moved to C-c C-m
56;; - C-c C-v shows you the python-mode version
Barry Warsaw3fcaf611996-08-01 20:11:51 +000057;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000058;; - proper interaction with pending-del and del-sel modes.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000059;; - Better support for outdenting: py-electric-colon (:) and
60;; py-indent-line (TAB) improvements; one level of outdentation
61;; added after a return, raise, break, or continue statement
62;; - New py-electric-colon (:) command for improved outdenting Also
63;; py-indent-line (TAB) should handle outdented lines better
Barry Warsaw03970731996-07-03 23:12:52 +000064;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000065;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
66;; M-f and M-b respectively.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000067;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
68;; - py-indent-offset now defaults to 4
69;; - new variable py-honor-comment-indentation
70;; - comment-region bound to C-c #
71;; - py-delete-char obeys numeric arguments
72;; - Small modification to rule for "indenting comment lines", such
73;; lines must now also be indented less than or equal to the
74;; indentation of the previous statement.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000075
Barry Warsaw7b0f5681995-03-08 21:33:04 +000076;; Here's a brief to do list:
77;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000078;; - Better integration with gud-mode for debugging.
79;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000080;; - possibly force indent-tabs-mode == nil, and add a
81;; write-file-hooks that runs untabify on the whole buffer (to work
82;; around potential tab/space mismatch problems). In practice this
83;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000084;; - have py-execute-region on indented code act as if the region is
85;; left justified. Avoids syntax errors.
Barry Warsaw7ae77681994-12-12 20:38:05 +000086
Barry Warsaw7b0f5681995-03-08 21:33:04 +000087;; If you can think of more things you'd like to see, drop me a line.
88;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
89;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000090;; Note that I only test things on XEmacs 19 and to some degree on
91;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
92;; send me your patches. Byte compiler complaints can probably be
93;; safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000094
Barry Warsaw7b0f5681995-03-08 21:33:04 +000095;;; Code:
96
97
98;; user definable variables
99;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000100
101(defvar py-python-command "python"
102 "*Shell command used to start Python interpreter.")
103
Barry Warsaw17914f41995-11-03 18:25:15 +0000104(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106Note that `\\[py-guess-indent-offset]' can usually guess a good value
107when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000108
Barry Warsaw095e9c61995-09-19 20:01:42 +0000109(defvar py-align-multiline-strings-p t
110 "*Flag describing how multiline triple quoted strings are aligned.
111When this flag is non-nil, continuation lines are lined up under the
112preceding line's indentation. When this flag is nil, continuation
113lines are aligned to column zero.")
114
Barry Warsaw3fcaf611996-08-01 20:11:51 +0000115(defvar py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000116 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000117This should follow the convention for non-indenting comment lines so
118that the indentation commands won't get confused (i.e., the string
119should be of the form `#x...' where `x' is not a blank or a tab, and
120`...' is arbitrary).")
121
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000122(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000123 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000124
Barry Warsaw6d627751996-03-06 18:41:38 +0000125When nil, all comment lines are skipped for indentation purposes, and
126in Emacs 19, a faster algorithm is used.
127
128When t, lines that begin with a single `#' are a hint to subsequent
129line indentation. If the previous line is such a comment line (as
130opposed to one that starts with `py-block-comment-prefix'), then it's
131indentation is used as a hint for this line's indentation. Lines that
132begin with `py-block-comment-prefix' are ignored for indentation
133purposes.
134
135When not nil or t, comment lines that begin with a `#' are used as
136indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000137
Barry Warsaw7ae77681994-12-12 20:38:05 +0000138(defvar py-scroll-process-buffer t
139 "*Scroll Python process buffer as output arrives.
140If nil, the Python process buffer acts, with respect to scrolling, like
141Shell-mode buffers normally act. This is surprisingly complicated and
142so won't be explained here; in fact, you can't get the whole story
143without studying the Emacs C code.
144
145If non-nil, the behavior is different in two respects (which are
146slightly inaccurate in the interest of brevity):
147
148 - If the buffer is in a window, and you left point at its end, the
149 window will scroll as new output arrives, and point will move to the
150 buffer's end, even if the window is not the selected window (that
151 being the one the cursor is in). The usual behavior for shell-mode
152 windows is not to scroll, and to leave point where it was, if the
153 buffer is in a window other than the selected window.
154
155 - If the buffer is not visible in any window, and you left point at
156 its end, the buffer will be popped into a window as soon as more
157 output arrives. This is handy if you have a long-running
158 computation and don't want to tie up screen area waiting for the
159 output. The usual behavior for a shell-mode buffer is to stay
160 invisible until you explicitly visit it.
161
162Note the `and if you left point at its end' clauses in both of the
163above: you can `turn off' the special behaviors while output is in
164progress, by visiting the Python buffer and moving point to anywhere
165besides the end. Then the buffer won't scroll, point will remain where
166you leave it, and if you hide the buffer it will stay hidden until you
167visit it again. You can enable and disable the special behaviors as
168often as you like, while output is in progress, by (respectively) moving
169point to, or away from, the end of the buffer.
170
171Warning: If you expect a large amount of output, you'll probably be
172happier setting this option to nil.
173
174Obscure: `End of buffer' above should really say `at or beyond the
175process mark', but if you know what that means you didn't need to be
176told <grin>.")
177
178(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000179 (let ((ok '(lambda (x)
180 (and x
181 (setq x (expand-file-name x)) ; always true
182 (file-directory-p x)
183 (file-writable-p x)
184 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000185 (or (funcall ok (getenv "TMPDIR"))
186 (funcall ok "/usr/tmp")
187 (funcall ok "/tmp")
188 (funcall ok ".")
189 (error
190 "Couldn't find a usable temp directory -- set py-temp-directory")))
191 "*Directory used for temp files created by a *Python* process.
192By default, the first directory from this list that exists and that you
193can write into: the value (if any) of the environment variable TMPDIR,
194/usr/tmp, /tmp, or the current directory.")
195
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000196(defvar py-beep-if-tab-change t
197 "*Ring the bell if tab-width is changed.
198If a comment of the form
199
200 \t# vi:set tabsize=<number>:
201
202is found before the first code line when the file is entered, and the
203current value of (the general Emacs variable) `tab-width' does not
204equal <number>, `tab-width' is set to <number>, a message saying so is
205displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
206the Emacs bell is also rung as a warning.")
207
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000208(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000209 (let* ((keywords '("access" "and" "break" "class"
210 "continue" "def" "del" "elif"
211 "else:" "except" "except:" "exec"
212 "finally:" "for" "from" "global"
213 "if" "import" "in" "is"
214 "lambda" "not" "or" "pass"
215 "print" "raise" "return" "try:"
216 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000217 ))
218 (kwregex (mapconcat 'identity keywords "\\|")))
219 (list
220 ;; keywords not at beginning of line
221 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
222 ;; keywords at beginning of line. i don't think regexps are
223 ;; powerful enough to handle these two cases in one regexp.
224 ;; prove me wrong!
225 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
226 ;; classes
227 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
228 1 font-lock-type-face)
229 ;; functions
230 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
231 1 font-lock-function-name-face)
232 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000233 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000234
Barry Warsaw81437461996-08-01 19:48:02 +0000235(defvar imenu-example--python-show-method-args-p nil
236 "*Controls echoing of arguments of functions & methods in the imenu buffer.
237When non-nil, arguments are printed.")
238
239
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000240
241;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
242;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
243
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000244(make-variable-buffer-local 'py-indent-offset)
245
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000246;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
247;; seems to be the standard way of checking this.
248;; BAW - This is *not* the right solution. When at all possible,
249;; instead of testing for the version of Emacs, use feature tests.
250
251(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
252(setq py-this-is-emacs-19-p
253 (and
254 (not py-this-is-lucid-emacs-p)
255 (string-match "^19\\." emacs-version)))
256
Barry Warsaw7ae77681994-12-12 20:38:05 +0000257;; have to bind py-file-queue before installing the kill-emacs hook
258(defvar py-file-queue nil
259 "Queue of Python temp files awaiting execution.
260Currently-active file is at the head of the list.")
261
262;; define a mode-specific abbrev table for those who use such things
263(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000264 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000265(define-abbrev-table 'python-mode-abbrev-table nil)
266
Barry Warsaw7ae77681994-12-12 20:38:05 +0000267(defvar python-mode-hook nil
268 "*Hook called by `python-mode'.")
269
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000270;; in previous version of python-mode.el, the hook was incorrectly
271;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000272(and (fboundp 'make-obsolete-variable)
273 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
274
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000275(defvar py-mode-map ()
276 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000277
Barry Warsaw7ae77681994-12-12 20:38:05 +0000278(if py-mode-map
279 ()
280 (setq py-mode-map (make-sparse-keymap))
281
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000282 ;; shadow global bindings for newline-and-indent w/ the py- version.
283 ;; BAW - this is extremely bad form, but I'm not going to change it
284 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285 (mapcar (function (lambda (key)
286 (define-key
287 py-mode-map key 'py-newline-and-indent)))
288 (where-is-internal 'newline-and-indent))
289
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000290 ;; BAW - you could do it this way, but its not considered proper
291 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000292 (mapcar (function
293 (lambda (x)
294 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000295 '((":" . py-electric-colon)
296 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000297 ("\C-c|" . py-execute-region)
298 ("\C-c!" . py-shell)
299 ("\177" . py-delete-char)
300 ("\n" . py-newline-and-indent)
301 ("\C-c:" . py-guess-indent-offset)
302 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000303 ("\C-c\C-l" . py-shift-region-left)
304 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000305 ("\C-c<" . py-shift-region-left)
306 ("\C-c>" . py-shift-region-right)
307 ("\C-c\C-n" . py-next-statement)
308 ("\C-c\C-p" . py-previous-statement)
309 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000310 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000311 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000312 ("\C-c?" . py-describe-mode)
313 ("\C-c\C-hm" . py-describe-mode)
314 ("\e\C-a" . beginning-of-python-def-or-class)
315 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000316 ( "\e\C-h" . mark-python-def-or-class)))
317 ;; should do all keybindings this way
318 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
319 (define-key py-mode-map "\C-c\C-v" 'py-version)
320 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000321
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000322(defvar py-mode-syntax-table nil
323 "Syntax table used in `python-mode' buffers.")
324
Barry Warsaw7ae77681994-12-12 20:38:05 +0000325(if py-mode-syntax-table
326 ()
327 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000328 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000329 (mapcar (function
330 (lambda (x) (modify-syntax-entry
331 (car x) (cdr x) py-mode-syntax-table)))
332 '(( ?\( . "()" ) ( ?\) . ")(" )
333 ( ?\[ . "(]" ) ( ?\] . ")[" )
334 ( ?\{ . "(}" ) ( ?\} . "){" )
335 ;; fix operator symbols misassigned in the std table
336 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
337 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
338 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
339 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000340 ;; for historical reasons, underscore is word class
341 ;; instead of symbol class. it should be symbol class,
342 ;; but if you're tempted to change it, try binding M-f and
343 ;; M-b to py-forward-into-nomenclature and
344 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000345 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000346 ( ?\' . "\"") ; single quote is string quote
347 ( ?\" . "\"" ) ; double quote is string quote too
348 ( ?\` . "$") ; backquote is open and close paren
349 ( ?\# . "<") ; hash starts comment
350 ( ?\n . ">")))) ; newline ends comment
351
352(defconst py-stringlit-re
353 (concat
354 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
355 "\\|" ; or
356 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000357 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000358
359;; this is tricky because a trailing backslash does not mean
360;; continuation if it's in a comment
361(defconst py-continued-re
362 (concat
363 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
364 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000365 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000366
367(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000368 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000369
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000370(defconst py-outdent-re
371 (concat "\\(" (mapconcat 'identity
372 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000373 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000374 "finally:"
375 "elif\\s +.*:")
376 "\\|")
377 "\\)")
378 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000379
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000380(defconst py-no-outdent-re
381 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000382 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000383 "except\\(\\s +.*\\)?:"
384 "while\\s +.*:"
385 "for\\s +.*:"
386 "if\\s +.*:"
Barry Warsawf67a57e1996-08-12 19:52:27 +0000387 "elif\\s +.*:"
388 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
389 )
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000390 "\\|")
391 "\\)")
392 "Regexp matching lines to not outdent after.")
393
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000394
Barry Warsaw42f707f1996-07-29 21:05:05 +0000395;; Menu definitions, only relevent if you have the easymenu.el package
396;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000397(defvar py-menu nil
398 "Menu for Python Mode.
399
400This menu will get created automatically if you have the easymenu
401package. Note that the latest XEmacs 19 and Emacs 19 versions contain
402this package.")
403
Barry Warsaw42f707f1996-07-29 21:05:05 +0000404(if (condition-case nil
405 (require 'easymenu)
406 (error nil))
407 (easy-menu-define
408 py-menu py-mode-map "Python Mode menu"
409 '("Python"
410 ["Comment Out Region" comment-region (mark)]
411 ["Uncomment Region" (comment-region (point) (mark) '(4)) (mark)]
412 "-"
413 ["Mark current block" py-mark-block t]
414 ["Mark current def" mark-python-def-or-class t]
415 ["Mark current class" (mark-python-def-or-class t) t]
416 "-"
417 ["Shift region left" py-shift-region-left (mark)]
418 ["Shift region right" py-shift-region-right (mark)]
419 "-"
420 ["Execute buffer" py-execute-buffer t]
421 ["Execute region" py-execute-region (mark)]
422 ["Start interpreter..." py-shell t]
423 "-"
424 ["Go to start of block" py-goto-block-up t]
425 ["Go to start of class" (beginning-of-python-def-or-class t) t]
426 ["Move to end of class" (end-of-python-def-or-class t) t]
427 ["Move to start of def" beginning-of-python-def-or-class t]
428 ["Move to end of def" end-of-python-def-or-class t]
429 "-"
430 ["Describe mode" py-describe-mode t]
431 )))
432
Barry Warsaw81437461996-08-01 19:48:02 +0000433
434
435;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
436(defvar imenu-example--python-class-regexp
437 (concat ; <<classes>>
438 "\\(" ;
439 "^[ \t]*" ; newline and maybe whitespace
440 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
441 ; possibly multiple superclasses
442 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
443 "[ \t]*:" ; and the final :
444 "\\)" ; >>classes<<
445 )
446 "Regexp for Python classes for use with the imenu package."
447 )
448
449(defvar imenu-example--python-method-regexp
450 (concat ; <<methods and functions>>
451 "\\(" ;
452 "^[ \t]*" ; new line and maybe whitespace
453 "\\(def[ \t]+" ; function definitions start with def
454 "\\([a-zA-Z0-9_]+\\)" ; name is here
455 ; function arguments...
456 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
457 "\\)" ; end of def
458 "[ \t]*:" ; and then the :
459 "\\)" ; >>methods and functions<<
460 )
461 "Regexp for Python methods/functions for use with the imenu package."
462 )
463
464(defvar imenu-example--python-method-no-arg-parens '(2 8)
465 "Indicies into groups of the Python regexp for use with imenu.
466
467Using these values will result in smaller imenu lists, as arguments to
468functions are not listed.
469
470See the variable `imenu-example--python-show-method-args-p' for more
471information.")
472
473(defvar imenu-example--python-method-arg-parens '(2 7)
474 "Indicies into groups of the Python regexp for use with imenu.
475Using these values will result in large imenu lists, as arguments to
476functions are listed.
477
478See the variable `imenu-example--python-show-method-args-p' for more
479information.")
480
481;; Note that in this format, this variable can still be used with the
482;; imenu--generic-function. Otherwise, there is no real reason to have
483;; it.
484(defvar imenu-example--generic-python-expression
485 (cons
486 (concat
487 imenu-example--python-class-regexp
488 "\\|" ; or...
489 imenu-example--python-method-regexp
490 )
491 imenu-example--python-method-no-arg-parens)
492 "Generic Python expression which may be used directly with imenu.
493Used by setting the variable `imenu-generic-expression' to this value.
494Also, see the function \\[imenu-example--create-python-index] for a
495better alternative for finding the index.")
496
497;; These next two variables are used when searching for the python
498;; class/definitions. Just saving some time in accessing the
499;; generic-python-expression, really.
500(defvar imenu-example--python-generic-regexp)
501(defvar imenu-example--python-generic-parens)
502
503
504;;;###autoload
505(eval-when-compile
506 ;; Imenu isn't used in XEmacs, so just ignore load errors
507 (condition-case ()
508 (progn
509 (require 'cl)
510 (require 'imenu))
511 (error nil)))
512
513(defun imenu-example--create-python-index ()
514 "Python interface function for imenu package.
515Finds all python classes and functions/methods. Calls function
516\\[imenu-example--create-python-index-engine]. See that function for
517the details of how this works."
518 (setq imenu-example--python-generic-regexp
519 (car imenu-example--generic-python-expression))
520 (setq imenu-example--python-generic-parens
521 (if imenu-example--python-show-method-args-p
522 imenu-example--python-method-arg-parens
523 imenu-example--python-method-no-arg-parens))
524 (goto-char (point-min))
525 (imenu-example--create-python-index-engine nil))
526
527(defun imenu-example--create-python-index-engine (&optional start-indent)
528 "Function for finding imenu definitions in Python.
529
530Finds all definitions (classes, methods, or functions) in a Python
531file for the imenu package.
532
533Returns a possibly nested alist of the form
534
535 (INDEX-NAME . INDEX-POSITION)
536
537The second element of the alist may be an alist, producing a nested
538list as in
539
540 (INDEX-NAME . INDEX-ALIST)
541
542This function should not be called directly, as it calls itself
543recursively and requires some setup. Rather this is the engine for
544the function \\[imenu-example--create-python-index].
545
546It works recursively by looking for all definitions at the current
547indention level. When it finds one, it adds it to the alist. If it
548finds a definition at a greater indentation level, it removes the
549previous definition from the alist. In it's place it adds all
550definitions found at the next indentation level. When it finds a
551definition that is less indented then the current level, it retuns the
552alist it has created thus far.
553
554The optional argument START-INDENT indicates the starting indentation
555at which to continue looking for Python classes, methods, or
556functions. If this is not supplied, the function uses the indentation
557of the first definition found."
558 (let ((index-alist '())
559 (sub-method-alist '())
560 looking-p
561 def-name prev-name
562 cur-indent def-pos
563 (class-paren (first imenu-example--python-generic-parens))
564 (def-paren (second imenu-example--python-generic-parens)))
565 (setq looking-p
566 (re-search-forward imenu-example--python-generic-regexp
567 (point-max) t))
568 (while looking-p
569 (save-excursion
570 ;; used to set def-name to this value but generic-extract-name is
571 ;; new to imenu-1.14. this way it still works with imenu-1.11
572 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
573 (let ((cur-paren (if (match-beginning class-paren)
574 class-paren def-paren)))
575 (setq def-name
576 (buffer-substring (match-beginning cur-paren)
577 (match-end cur-paren))))
578 (beginning-of-line)
579 (setq cur-indent (current-indentation)))
580
581 ;; HACK: want to go to the next correct definition location. we
582 ;; explicitly list them here. would be better to have them in a
583 ;; list.
584 (setq def-pos
585 (or (match-beginning class-paren)
586 (match-beginning def-paren)))
587
588 ;; if we don't have a starting indent level, take this one
589 (or start-indent
590 (setq start-indent cur-indent))
591
592 ;; if we don't have class name yet, take this one
593 (or prev-name
594 (setq prev-name def-name))
595
596 ;; what level is the next definition on? must be same, deeper
597 ;; or shallower indentation
598 (cond
599 ;; at the same indent level, add it to the list...
600 ((= start-indent cur-indent)
601
602 ;; if we don't have push, use the following...
603 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
604 (push (cons def-name def-pos) index-alist))
605
606 ;; deeper indented expression, recur...
607 ((< start-indent cur-indent)
608
609 ;; the point is currently on the expression we're supposed to
610 ;; start on, so go back to the last expression. The recursive
611 ;; call will find this place again and add it to the correct
612 ;; list
613 (re-search-backward imenu-example--python-generic-regexp
614 (point-min) 'move)
615 (setq sub-method-alist (imenu-example--create-python-index-engine
616 cur-indent))
617
618 (if sub-method-alist
619 ;; we put the last element on the index-alist on the start
620 ;; of the submethod alist so the user can still get to it.
621 (let ((save-elmt (pop index-alist)))
622 (push (cons (imenu-create-submenu-name prev-name)
623 (cons save-elmt sub-method-alist))
624 index-alist))))
625
626 ;; found less indented expression, we're done.
627 (t
628 (setq looking-p nil)
629 (re-search-backward imenu-example--python-generic-regexp
630 (point-min) t)))
631 (setq prev-name def-name)
632 (and looking-p
633 (setq looking-p
634 (re-search-forward imenu-example--python-generic-regexp
635 (point-max) 'move))))
636 (nreverse index-alist)))
637
Barry Warsaw42f707f1996-07-29 21:05:05 +0000638
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000639;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000640(defun python-mode ()
641 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000642To submit a problem report, enter `\\[py-submit-bug-report]' from a
643`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
644documentation. To see what version of `python-mode' you are running,
645enter `\\[py-version]'.
646
647This mode knows about Python indentation, tokens, comments and
648continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000649
650COMMANDS
651\\{py-mode-map}
652VARIABLES
653
Barry Warsaw42f707f1996-07-29 21:05:05 +0000654py-indent-offset\t\tindentation increment
655py-block-comment-prefix\t\tcomment string used by comment-region
656py-python-command\t\tshell command to invoke Python interpreter
657py-scroll-process-buffer\t\talways scroll Python process buffer
658py-temp-directory\t\tdirectory used for temp files (if needed)
659py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000660 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000661 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000662 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000663 (make-local-variable 'font-lock-defaults)
664 (make-local-variable 'paragraph-separate)
665 (make-local-variable 'paragraph-start)
666 (make-local-variable 'require-final-newline)
667 (make-local-variable 'comment-start)
668 (make-local-variable 'comment-start-skip)
669 (make-local-variable 'comment-column)
670 (make-local-variable 'indent-region-function)
671 (make-local-variable 'indent-line-function)
672 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000673 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000674 (setq major-mode 'python-mode
675 mode-name "Python"
676 local-abbrev-table python-mode-abbrev-table
677 font-lock-defaults '(python-font-lock-keywords)
678 paragraph-separate "^[ \t]*$"
679 paragraph-start "^[ \t]*$"
680 require-final-newline t
681 comment-start "# "
682 comment-start-skip "# *"
683 comment-column 40
684 indent-region-function py-indent-region
685 indent-line-function py-indent-line
Barry Warsawb1f89511996-09-03 16:38:30 +0000686 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000687 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000688 ;; add the menu
689 (if py-menu
690 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000691 ;; Emacs 19 requires this
692 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
693 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000694 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000695 ;;
696 ;; not sure where the magic comment has to be; to save time
697 ;; searching for a rarity, we give up if it's not found prior to the
698 ;; first executable statement.
699 ;;
700 ;; BAW - on first glance, this seems like complete hackery. Why was
701 ;; this necessary, and is it still necessary?
702 (let ((case-fold-search nil)
703 (start (point))
704 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000705 (if (re-search-forward
706 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
707 (prog2 (py-next-statement 1) (point) (goto-char 1))
708 t)
709 (progn
710 (setq new-tab-width
711 (string-to-int
712 (buffer-substring (match-beginning 1) (match-end 1))))
713 (if (= tab-width new-tab-width)
714 nil
715 (setq tab-width new-tab-width)
716 (message "Caution: tab-width changed to %d" new-tab-width)
717 (if py-beep-if-tab-change (beep)))))
718 (goto-char start))
719
Barry Warsaw755c6711996-08-01 20:02:55 +0000720 ;; install imenu
721 (setq imenu-create-index-function
722 (function imenu-example--create-python-index))
723 (if (fboundp 'imenu-add-to-menubar)
724 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
725
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000726 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000727 (if python-mode-hook
728 (run-hooks 'python-mode-hook)
729 (run-hooks 'py-mode-hook)))
730
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000731
Barry Warsaw826255b1996-03-22 16:09:34 +0000732(defun py-keep-region-active ()
Barry Warsawce60bc71996-08-01 18:17:14 +0000733 ;; do whatever is necessary to keep the region active in XEmacs.
734 ;; Ignore byte-compiler warnings you might see. Also note that
735 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
736 ;; require us to take explicit action.
Barry Warsaw826255b1996-03-22 16:09:34 +0000737 (and (boundp 'zmacs-region-stays)
738 (setq zmacs-region-stays t)))
739
Barry Warsawce60bc71996-08-01 18:17:14 +0000740
Barry Warsawb91b7431995-03-14 15:55:20 +0000741;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000742(defun py-outdent-p ()
743 ;; returns non-nil if the current line should outdent one level
744 (save-excursion
745 (and (progn (back-to-indentation)
746 (looking-at py-outdent-re))
747 (progn (backward-to-indentation 1)
748 (while (or (looking-at py-blank-or-comment-re)
749 (bobp))
750 (backward-to-indentation 1))
751 (not (looking-at py-no-outdent-re)))
752 )))
753
754
Barry Warsawb91b7431995-03-14 15:55:20 +0000755(defun py-electric-colon (arg)
756 "Insert a colon.
757In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000758argument is provided, that many colons are inserted non-electrically.
759Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000760 (interactive "P")
761 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000762 ;; are we in a string or comment?
763 (if (save-excursion
764 (let ((pps (parse-partial-sexp (save-excursion
765 (beginning-of-python-def-or-class)
766 (point))
767 (point))))
768 (not (or (nth 3 pps) (nth 4 pps)))))
769 (save-excursion
770 (let ((here (point))
771 (outdent 0)
772 (indent (py-compute-indentation)))
773 (if (and (not arg)
774 (py-outdent-p)
775 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000776 (py-next-statement -1)
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000777 (py-compute-indentation)))
778 )
779 (setq outdent py-indent-offset))
780 ;; Don't indent, only outdent. This assumes that any lines that
781 ;; are already outdented relative to py-compute-indentation were
782 ;; put there on purpose. Its highly annoying to have `:' indent
783 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
784 ;; there a better way to determine this???
785 (if (< (current-indentation) indent) nil
786 (goto-char here)
787 (beginning-of-line)
788 (delete-horizontal-space)
789 (indent-to (- indent outdent))
790 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000791
792
Barry Warsaw7ae77681994-12-12 20:38:05 +0000793;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000794;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000795(defun py-shell ()
796 "Start an interactive Python interpreter in another window.
797This is like Shell mode, except that Python is running in the window
798instead of a shell. See the `Interactive Shell' and `Shell Mode'
799sections of the Emacs manual for details, especially for the key
800bindings active in the `*Python*' buffer.
801
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000802See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000803behavior in the process window.
804
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000805Warning: Don't use an interactive Python if you change sys.ps1 or
806sys.ps2 from their default values, or if you're running code that
807prints `>>> ' or `... ' at the start of a line. `python-mode' can't
808distinguish your output from Python's output, and assumes that `>>> '
809at the start of a line is a prompt from Python. Similarly, the Emacs
810Shell mode code assumes that both `>>> ' and `... ' at the start of a
811line are Python prompts. Bad things can happen if you fool either
812mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000813
814Warning: If you do any editing *in* the process buffer *while* the
815buffer is accepting output from Python, do NOT attempt to `undo' the
816changes. Some of the output (nowhere near the parts you changed!) may
817be lost if you do. This appears to be an Emacs bug, an unfortunate
818interaction between undo and process filters; the same problem exists in
819non-Python process buffers using the default (Emacs-supplied) process
820filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000821 ;; BAW - should undo be disabled in the python process buffer, if
822 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000823 (interactive)
824 (if py-this-is-emacs-19-p
825 (progn
826 (require 'comint)
827 (switch-to-buffer-other-window
828 (make-comint "Python" py-python-command)))
829 (progn
830 (require 'shell)
831 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000832 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000833 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000834 (make-local-variable 'shell-prompt-pattern)
835 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
836 (set-process-filter (get-buffer-process (current-buffer))
837 'py-process-filter)
838 (set-syntax-table py-mode-syntax-table))
839
840(defun py-execute-region (start end)
841 "Send the region between START and END to a Python interpreter.
842If there is a *Python* process it is used.
843
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000844Hint: If you want to execute part of a Python file several times
845\(e.g., perhaps you're developing a function and want to flesh it out
846a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
847the region of interest, and send the code to a *Python* process via
848`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000849
850Following are subtleties to note when using a *Python* process:
851
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000852If a *Python* process is used, the region is copied into a temporary
853file (in directory `py-temp-directory'), and an `execfile' command is
854sent to Python naming that file. If you send regions faster than
855Python can execute them, `python-mode' will save them into distinct
856temp files, and execute the next one in the queue the next time it
857sees a `>>> ' prompt from Python. Each time this happens, the process
858buffer is popped into a window (if it's not already in some window) so
859you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000860
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000861 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000862
863is inserted at the end.
864
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000865Caution: No more than 26 regions can be pending at any given time.
866This limit is (indirectly) inherited from libc's mktemp(3).
867`python-mode' does not try to protect you from exceeding the limit.
868It's extremely unlikely that you'll get anywhere close to the limit in
869practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000870
871See the `\\[py-shell]' docs for additional warnings."
872 (interactive "r")
873 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000874 (let ((pyproc (get-process "Python"))
875 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876 (if (null pyproc)
877 (shell-command-on-region start end py-python-command)
878 ;; else feed it thru a temp file
879 (setq fname (py-make-temp-name))
880 (write-region start end fname nil 'no-msg)
881 (setq py-file-queue (append py-file-queue (list fname)))
882 (if (cdr py-file-queue)
883 (message "File %s queued for execution" fname)
884 ;; else
885 (py-execute-file pyproc fname)))))
886
887(defun py-execute-file (pyproc fname)
888 (py-append-to-process-buffer
889 pyproc
890 (format "## working on region in file %s ...\n" fname))
891 (process-send-string pyproc (format "execfile('%s')\n" fname)))
892
893(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000894 (let ((curbuf (current-buffer))
895 (pbuf (process-buffer pyproc))
896 (pmark (process-mark pyproc))
897 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898
899 ;; make sure we switch to a different buffer at least once. if we
900 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000901 ;; window, and point is before the end, and lots of output is
902 ;; coming at a fast pace, then (a) simple cursor-movement commands
903 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
904 ;; to have a visible effect (the window just doesn't get updated,
905 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
906 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908 ;; #b makes no sense to me at all. #a almost makes sense: unless
909 ;; we actually change buffers, set_buffer_internal in buffer.c
910 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
911 ;; seems to make the Emacs command loop reluctant to update the
912 ;; display. Perhaps the default process filter in process.c's
913 ;; read_process_output has update_mode_lines++ for a similar
914 ;; reason? beats me ...
915
916 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000917 (if (eq curbuf pbuf) ; mysterious ugly hack
918 (set-buffer (get-buffer-create "*scratch*")))
919
920 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000921 (let* ((start (point))
922 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000923 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000924 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925 (goto-char pmark)
926 (insert string)
927 (move-marker pmark (point))
928 (setq file-finished
929 (and py-file-queue
930 (equal ">>> "
931 (buffer-substring
932 (prog2 (beginning-of-line) (point)
933 (goto-char pmark))
934 (point)))))
935 (if goback (goto-char start)
936 ;; else
937 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000938 (let* ((pop-up-windows t)
939 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000940 (set-window-point pwin (point)))))
941 (set-buffer curbuf)
942 (if file-finished
943 (progn
944 (py-delete-file-silently (car py-file-queue))
945 (setq py-file-queue (cdr py-file-queue))
946 (if py-file-queue
947 (py-execute-file pyproc (car py-file-queue)))))
948 (and goend
949 (progn (set-buffer pbuf)
950 (goto-char (point-max))))
951 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000952
953(defun py-execute-buffer ()
954 "Send the contents of the buffer to a Python interpreter.
955If there is a *Python* process buffer it is used. If a clipping
956restriction is in effect, only the accessible portion of the buffer is
957sent. A trailing newline will be supplied if needed.
958
959See the `\\[py-execute-region]' docs for an account of some subtleties."
960 (interactive)
961 (py-execute-region (point-min) (point-max)))
962
963
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000964
965;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000966(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000967 "Reduce indentation or delete character.
968If point is at the leftmost column, deletes the preceding newline.
969
970Else if point is at the leftmost non-blank character of a line that is
971neither a continuation line nor a non-indenting comment line, or if
972point is at the end of a blank line, reduces the indentation to match
973that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000974opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000975of where you are. With numeric count, outdents that many blocks (but
976not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977
978Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000979needed so that only a single column position is deleted. Numeric
980argument delets that many characters."
981 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000982 (if (or (/= (current-indentation) (current-column))
983 (bolp)
984 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +0000985 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000986 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000987 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988 ;; else indent the same as the colon line that opened the block
989
990 ;; force non-blank so py-goto-block-up doesn't ignore it
991 (insert-char ?* 1)
992 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000993 (let ((base-indent 0) ; indentation of base line
994 (base-text "") ; and text of base line
995 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000996 (save-excursion
997 (while (< 0 count)
998 (condition-case nil ; in case no enclosing block
999 (progn
1000 (py-goto-block-up 'no-mark)
1001 (setq base-indent (current-indentation)
1002 base-text (py-suck-up-leading-text)
1003 base-found-p t))
1004 (error nil))
1005 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006 (delete-char 1) ; toss the dummy character
1007 (delete-horizontal-space)
1008 (indent-to base-indent)
1009 (if base-found-p
1010 (message "Closes block: %s" base-text)))))
1011
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001012;; required for pending-del and delsel modes
1013(put 'py-delete-char 'delete-selection 'supersede)
1014(put 'py-delete-char 'pending-delete 'supersede)
1015
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016(defun py-indent-line ()
1017 "Fix the indentation of the current line according to Python rules."
1018 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001019 (let* ((ci (current-indentation))
1020 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +00001021 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001022 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001023 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001024 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001025 (if (/= ci need)
1026 (save-excursion
1027 (beginning-of-line)
1028 (delete-horizontal-space)
1029 (indent-to need)))
1030 (if move-to-indentation-p (back-to-indentation))))
1031
1032(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001033 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001034This is just `strives to' because correct indentation can't be computed
1035from scratch for Python code. In general, deletes the whitespace before
1036point, inserts a newline, and takes an educated guess as to how you want
1037the new line indented."
1038 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001039 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001040 (if (< ci (current-column)) ; if point beyond indentation
1041 (newline-and-indent)
1042 ;; else try to act like newline-and-indent "normally" acts
1043 (beginning-of-line)
1044 (insert-char ?\n 1)
1045 (move-to-column ci))))
1046
1047(defun py-compute-indentation ()
1048 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001049 (let ((pps (parse-partial-sexp (save-excursion
1050 (beginning-of-python-def-or-class)
1051 (point))
1052 (point))))
1053 (beginning-of-line)
1054 (cond
1055 ;; are we inside a string or comment?
1056 ((or (nth 3 pps) (nth 4 pps))
1057 (save-excursion
1058 (if (not py-align-multiline-strings-p) 0
1059 ;; skip back over blank & non-indenting comment lines
1060 ;; note: will skip a blank or non-indenting comment line
1061 ;; that happens to be a continuation line too
1062 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1063 (back-to-indentation)
1064 (current-column))))
1065 ;; are we on a continuation line?
1066 ((py-continuation-line-p)
1067 (let ((startpos (point))
1068 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001069 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001070 (if open-bracket-pos
1071 (progn
1072 ;; align with first item in list; else a normal
1073 ;; indent beyond the line with the open bracket
1074 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1075 ;; is the first list item on the same line?
1076 (skip-chars-forward " \t")
1077 (if (null (memq (following-char) '(?\n ?# ?\\)))
1078 ; yes, so line up with it
1079 (current-column)
1080 ;; first list item on another line, or doesn't exist yet
1081 (forward-line 1)
1082 (while (and (< (point) startpos)
1083 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1084 (forward-line 1))
1085 (if (< (point) startpos)
1086 ;; again mimic the first list item
1087 (current-indentation)
1088 ;; else they're about to enter the first item
1089 (goto-char open-bracket-pos)
1090 (+ (current-indentation) py-indent-offset))))
1091
1092 ;; else on backslash continuation line
1093 (forward-line -1)
1094 (if (py-continuation-line-p) ; on at least 3rd line in block
1095 (current-indentation) ; so just continue the pattern
1096 ;; else started on 2nd line in block, so indent more.
1097 ;; if base line is an assignment with a start on a RHS,
1098 ;; indent to 2 beyond the leftmost "="; else skip first
1099 ;; chunk of non-whitespace characters on base line, + 1 more
1100 ;; column
1101 (end-of-line)
1102 (setq endpos (point) searching t)
1103 (back-to-indentation)
1104 (setq startpos (point))
1105 ;; look at all "=" from left to right, stopping at first
1106 ;; one not nested in a list or string
1107 (while searching
1108 (skip-chars-forward "^=" endpos)
1109 (if (= (point) endpos)
1110 (setq searching nil)
1111 (forward-char 1)
1112 (setq state (parse-partial-sexp startpos (point)))
1113 (if (and (zerop (car state)) ; not in a bracket
1114 (null (nth 3 state))) ; & not in a string
1115 (progn
1116 (setq searching nil) ; done searching in any case
1117 (setq found
1118 (not (or
1119 (eq (following-char) ?=)
1120 (memq (char-after (- (point) 2))
1121 '(?< ?> ?!)))))))))
1122 (if (or (not found) ; not an assignment
1123 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1124 (progn
1125 (goto-char startpos)
1126 (skip-chars-forward "^ \t\n")))
1127 (1+ (current-column))))))
1128
1129 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001130 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001131
Barry Warsawa7891711996-08-01 15:53:09 +00001132 ;; Dfn: "Indenting comment line". A line containing only a
1133 ;; comment, but which is treated like a statement for
1134 ;; indentation calculation purposes. Such lines are only
1135 ;; treated specially by the mode; they are not treated
1136 ;; specially by the Python interpreter.
1137
1138 ;; The rules for indenting comment lines are a line where:
1139 ;; - the first non-whitespace character is `#', and
1140 ;; - the character following the `#' is whitespace, and
1141 ;; - the line is outdented with respect to (i.e. to the left
1142 ;; of) the indentation of the preceding non-blank line.
1143
1144 ;; The first non-blank line following an indenting comment
1145 ;; line is given the same amount of indentation as the
1146 ;; indenting comment line.
1147
1148 ;; All other comment-only lines are ignored for indentation
1149 ;; purposes.
1150
1151 ;; Are we looking at a comment-only line which is *not* an
1152 ;; indenting comment line? If so, we assume that its been
1153 ;; placed at the desired indentation, so leave it alone.
1154 ;; Indenting comment lines are aligned as statements down
1155 ;; below.
1156 ((and (looking-at "[ \t]*#[^ \t\n]")
1157 ;; NOTE: this test will not be performed in older Emacsen
1158 (fboundp 'forward-comment)
1159 (<= (current-indentation)
1160 (save-excursion
1161 (forward-comment (- (point-max)))
1162 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001163 (current-indentation))
1164
1165 ;; else indentation based on that of the statement that
1166 ;; precedes us; use the first line of that statement to
1167 ;; establish the base, in case the user forced a non-std
1168 ;; indentation for the continuation lines (if any)
1169 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001170 ;; skip back over blank & non-indenting comment lines note:
1171 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001172 ;; happens to be a continuation line too. use fast Emacs 19
1173 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001174 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001175 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001176 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001177 (let (done)
1178 (while (not done)
1179 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1180 nil 'move)
1181 (setq done (or (eq py-honor-comment-indentation t)
1182 (bobp)
1183 (/= (following-char) ?#)
1184 (not (zerop (current-column)))))
1185 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001186 ;; if we landed inside a string, go to the beginning of that
1187 ;; string. this handles triple quoted, multi-line spanning
1188 ;; strings.
1189 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001190 (+ (current-indentation)
1191 (if (py-statement-opens-block-p)
1192 py-indent-offset
1193 (if (py-statement-closes-block-p)
1194 (- py-indent-offset)
1195 0)))
1196 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001197
1198(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001200By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001201`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001202Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001203`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001204their own buffer-local copy), both those currently existing and those
1205created later in the Emacs session.
1206
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001208There's no excuse for such foolishness, but sometimes you have to deal
1209with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001210`py-indent-offset' to what it thinks it was when they created the
1211mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001212
1213Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001214looking for a line that opens a block of code. `py-indent-offset' is
1215set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001216statement following it. If the search doesn't succeed going forward,
1217it's tried again going backward."
1218 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001219 (let (new-value
1220 (start (point))
1221 restart
1222 (found nil)
1223 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001224 (py-goto-initial-line)
1225 (while (not (or found (eobp)))
1226 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1227 (progn
1228 (setq restart (point))
1229 (py-goto-initial-line)
1230 (if (py-statement-opens-block-p)
1231 (setq found t)
1232 (goto-char restart)))))
1233 (if found
1234 ()
1235 (goto-char start)
1236 (py-goto-initial-line)
1237 (while (not (or found (bobp)))
1238 (setq found
1239 (and
1240 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1241 (or (py-goto-initial-line) t) ; always true -- side effect
1242 (py-statement-opens-block-p)))))
1243 (setq colon-indent (current-indentation)
1244 found (and found (zerop (py-next-statement 1)))
1245 new-value (- (current-indentation) colon-indent))
1246 (goto-char start)
1247 (if found
1248 (progn
1249 (funcall (if global 'kill-local-variable 'make-local-variable)
1250 'py-indent-offset)
1251 (setq py-indent-offset new-value)
1252 (message "%s value of py-indent-offset set to %d"
1253 (if global "Global" "Local")
1254 py-indent-offset))
1255 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1256
1257(defun py-shift-region (start end count)
1258 (save-excursion
1259 (goto-char end) (beginning-of-line) (setq end (point))
1260 (goto-char start) (beginning-of-line) (setq start (point))
1261 (indent-rigidly start end count)))
1262
1263(defun py-shift-region-left (start end &optional count)
1264 "Shift region of Python code to the left.
1265The lines from the line containing the start of the current region up
1266to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001267shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001268
1269If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001270many columns. With no active region, outdent only the current line.
1271You cannot outdent the region if any line is already at column zero."
1272 (interactive
1273 (let ((p (point))
1274 (m (mark))
1275 (arg current-prefix-arg))
1276 (if m
1277 (list (min p m) (max p m) arg)
1278 (list p (save-excursion (forward-line 1) (point)) arg))))
1279 ;; if any line is at column zero, don't shift the region
1280 (save-excursion
1281 (goto-char start)
1282 (while (< (point) end)
1283 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001284 (if (and (zerop (current-column))
1285 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001286 (error "Region is at left edge."))
1287 (forward-line 1)))
1288 (py-shift-region start end (- (prefix-numeric-value
1289 (or count py-indent-offset))))
1290 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001291
1292(defun py-shift-region-right (start end &optional count)
1293 "Shift region of Python code to the right.
1294The lines from the line containing the start of the current region up
1295to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001296shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001297
1298If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001299many columns. With no active region, indent only the current line."
1300 (interactive
1301 (let ((p (point))
1302 (m (mark))
1303 (arg current-prefix-arg))
1304 (if m
1305 (list (min p m) (max p m) arg)
1306 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001307 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001308 (or count py-indent-offset)))
1309 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001310
1311(defun py-indent-region (start end &optional indent-offset)
1312 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001313
Barry Warsaw7ae77681994-12-12 20:38:05 +00001314The lines from the line containing the start of the current region up
1315to (but not including) the line containing the end of the region are
1316reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001317character in the first column, the first line is left alone and the
1318rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001319region is reindented with respect to the (closest code or indenting
1320comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001321
1322This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001323control structures are introduced or removed, or to reformat code
1324using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001325
1326If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001327the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001328used.
1329
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001330Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001331is called! This function does not compute proper indentation from
1332scratch (that's impossible in Python), it merely adjusts the existing
1333indentation to be correct in context.
1334
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001335Warning: This function really has no idea what to do with
1336non-indenting comment lines, and shifts them as if they were indenting
1337comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001338
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001339Special cases: whitespace is deleted from blank lines; continuation
1340lines are shifted by the same amount their initial line was shifted,
1341in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001342initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001343 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001344 (save-excursion
1345 (goto-char end) (beginning-of-line) (setq end (point-marker))
1346 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001347 (let ((py-indent-offset (prefix-numeric-value
1348 (or indent-offset py-indent-offset)))
1349 (indents '(-1)) ; stack of active indent levels
1350 (target-column 0) ; column to which to indent
1351 (base-shifted-by 0) ; amount last base line was shifted
1352 (indent-base (if (looking-at "[ \t\n]")
1353 (py-compute-indentation)
1354 0))
1355 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356 (while (< (point) end)
1357 (setq ci (current-indentation))
1358 ;; figure out appropriate target column
1359 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360 ((or (eq (following-char) ?#) ; comment in column 1
1361 (looking-at "[ \t]*$")) ; entirely blank
1362 (setq target-column 0))
1363 ((py-continuation-line-p) ; shift relative to base line
1364 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365 (t ; new base line
1366 (if (> ci (car indents)) ; going deeper; push it
1367 (setq indents (cons ci indents))
1368 ;; else we should have seen this indent before
1369 (setq indents (memq ci indents)) ; pop deeper indents
1370 (if (null indents)
1371 (error "Bad indentation in region, at line %d"
1372 (save-restriction
1373 (widen)
1374 (1+ (count-lines 1 (point)))))))
1375 (setq target-column (+ indent-base
1376 (* py-indent-offset
1377 (- (length indents) 2))))
1378 (setq base-shifted-by (- target-column ci))))
1379 ;; shift as needed
1380 (if (/= ci target-column)
1381 (progn
1382 (delete-horizontal-space)
1383 (indent-to target-column)))
1384 (forward-line 1))))
1385 (set-marker end nil))
1386
Barry Warsawa7891711996-08-01 15:53:09 +00001387(defun py-comment-region (beg end &optional arg)
1388 "Like `comment-region' but uses double hash (`#') comment starter."
1389 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001390 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001391 (comment-region beg end arg)))
1392
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001393
1394;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001395(defun py-previous-statement (count)
1396 "Go to the start of previous Python statement.
1397If the statement at point is the i'th Python statement, goes to the
1398start of statement i-COUNT. If there is no such statement, goes to the
1399first statement. Returns count of statements left to move.
1400`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001401 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001402 (if (< count 0) (py-next-statement (- count))
1403 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001404 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001405 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001406 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001407 (> count 0)
1408 (zerop (forward-line -1))
1409 (py-goto-statement-at-or-above))
1410 (setq count (1- count)))
1411 (if (> count 0) (goto-char start)))
1412 count))
1413
1414(defun py-next-statement (count)
1415 "Go to the start of next Python statement.
1416If the statement at point is the i'th Python statement, goes to the
1417start of statement i+COUNT. If there is no such statement, goes to the
1418last statement. Returns count of statements left to move. `Statements'
1419do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001420 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001421 (if (< count 0) (py-previous-statement (- count))
1422 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001423 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001424 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001425 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001426 (> count 0)
1427 (py-goto-statement-below))
1428 (setq count (1- count)))
1429 (if (> count 0) (goto-char start)))
1430 count))
1431
1432(defun py-goto-block-up (&optional nomark)
1433 "Move up to start of current block.
1434Go to the statement that starts the smallest enclosing block; roughly
1435speaking, this will be the closest preceding statement that ends with a
1436colon and is indented less than the statement you started on. If
1437successful, also sets the mark to the starting point.
1438
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001439`\\[py-mark-block]' can be used afterward to mark the whole code
1440block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001441
1442If called from a program, the mark will not be set if optional argument
1443NOMARK is not nil."
1444 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001445 (let ((start (point))
1446 (found nil)
1447 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001448 (py-goto-initial-line)
1449 ;; if on blank or non-indenting comment line, use the preceding stmt
1450 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1451 (progn
1452 (py-goto-statement-at-or-above)
1453 (setq found (py-statement-opens-block-p))))
1454 ;; search back for colon line indented less
1455 (setq initial-indent (current-indentation))
1456 (if (zerop initial-indent)
1457 ;; force fast exit
1458 (goto-char (point-min)))
1459 (while (not (or found (bobp)))
1460 (setq found
1461 (and
1462 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1463 (or (py-goto-initial-line) t) ; always true -- side effect
1464 (< (current-indentation) initial-indent)
1465 (py-statement-opens-block-p))))
1466 (if found
1467 (progn
1468 (or nomark (push-mark start))
1469 (back-to-indentation))
1470 (goto-char start)
1471 (error "Enclosing block not found"))))
1472
1473(defun beginning-of-python-def-or-class (&optional class)
1474 "Move point to start of def (or class, with prefix arg).
1475
1476Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001477arg, looks for a `class' instead. The docs assume the `def' case;
1478just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001479
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001480If point is in a def statement already, and after the `d', simply
1481moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001482
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001483Else (point is not in a def statement, or at or before the `d' of a
1484def statement), searches for the closest preceding def statement, and
1485leaves point at its start. If no such statement can be found, leaves
1486point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001487
1488Returns t iff a def statement is found by these rules.
1489
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001490Note that doing this command repeatedly will take you closer to the
1491start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001492
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001493If you want to mark the current def/class, see
1494`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001495 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001496 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1497 (start-of-line (progn (beginning-of-line) (point)))
1498 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001499 (if (or (/= start-of-stmt start-of-line)
1500 (not at-or-before-p))
1501 (end-of-line)) ; OK to match on this line
1502 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001504
1505(defun end-of-python-def-or-class (&optional class)
1506 "Move point beyond end of def (or class, with prefix arg) body.
1507
1508By default, looks for an appropriate `def'. If you supply a prefix arg,
1509looks for a `class' instead. The docs assume the `def' case; just
1510substitute `class' for `def' for the other case.
1511
1512If point is in a def statement already, this is the def we use.
1513
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001514Else if the def found by `\\[beginning-of-python-def-or-class]'
1515contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001516
1517Else we search forward for the closest following def, and use that.
1518
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001519If a def can be found by these rules, point is moved to the start of
1520the line immediately following the def block, and the position of the
1521start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001522
1523Else point is moved to the end of the buffer, and nil is returned.
1524
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001525Note that doing this command repeatedly will take you closer to the
1526end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001527
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001528If you want to mark the current def/class, see
1529`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001530 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531 (let ((start (progn (py-goto-initial-line) (point)))
1532 (which (if class "class" "def"))
1533 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001534 ;; move point to start of appropriate def/class
1535 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1536 (setq state 'at-beginning)
1537 ;; else see if beginning-of-python-def-or-class hits container
1538 (if (and (beginning-of-python-def-or-class class)
1539 (progn (py-goto-beyond-block)
1540 (> (point) start)))
1541 (setq state 'at-end)
1542 ;; else search forward
1543 (goto-char start)
1544 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1545 (progn (setq state 'at-beginning)
1546 (beginning-of-line)))))
1547 (cond
1548 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1549 ((eq state 'at-end) t)
1550 ((eq state 'not-found) nil)
1551 (t (error "internal error in end-of-python-def-or-class")))))
1552
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553
1554;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001555(defun py-mark-block (&optional extend just-move)
1556 "Mark following block of lines. With prefix arg, mark structure.
1557Easier to use than explain. It sets the region to an `interesting'
1558block of succeeding lines. If point is on a blank line, it goes down to
1559the next non-blank line. That will be the start of the region. The end
1560of the region depends on the kind of line at the start:
1561
1562 - If a comment, the region will include all succeeding comment lines up
1563 to (but not including) the next non-comment line (if any).
1564
1565 - Else if a prefix arg is given, and the line begins one of these
1566 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001567
1568 if elif else try except finally for while def class
1569
Barry Warsaw7ae77681994-12-12 20:38:05 +00001570 the region will be set to the body of the structure, including
1571 following blocks that `belong' to it, but excluding trailing blank
1572 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573 and all (if any) of the following `except' and `finally' blocks
1574 that belong to the `try' structure will be in the region. Ditto
1575 for if/elif/else, for/else and while/else structures, and (a bit
1576 degenerate, since they're always one-block structures) def and
1577 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578
1579 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580 block (see list above), and the block is not a `one-liner' (i.e.,
1581 the statement ends with a colon, not with code), the region will
1582 include all succeeding lines up to (but not including) the next
1583 code statement (if any) that's indented no more than the starting
1584 line, except that trailing blank and comment lines are excluded.
1585 E.g., if the starting line begins a multi-statement `def'
1586 structure, the region will be set to the full function definition,
1587 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588
1589 - Else the region will include all succeeding lines up to (but not
1590 including) the next blank line, or code or indenting-comment line
1591 indented strictly less than the starting line. Trailing indenting
1592 comment lines are included in this case, but not trailing blank
1593 lines.
1594
1595A msg identifying the location of the mark is displayed in the echo
1596area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1597
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001598If called from a program, optional argument EXTEND plays the role of
1599the prefix arg, and if optional argument JUST-MOVE is not nil, just
1600moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001601 (interactive "P") ; raw prefix arg
1602 (py-goto-initial-line)
1603 ;; skip over blank lines
1604 (while (and
1605 (looking-at "[ \t]*$") ; while blank line
1606 (not (eobp))) ; & somewhere to go
1607 (forward-line 1))
1608 (if (eobp)
1609 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001610 (let ((initial-pos (point))
1611 (initial-indent (current-indentation))
1612 last-pos ; position of last stmt in region
1613 (followers
1614 '((if elif else) (elif elif else) (else)
1615 (try except finally) (except except) (finally)
1616 (for else) (while else)
1617 (def) (class) ) )
1618 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001619
1620 (cond
1621 ;; if comment line, suck up the following comment lines
1622 ((looking-at "[ \t]*#")
1623 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1624 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1625 (setq last-pos (point)))
1626
1627 ;; else if line is a block line and EXTEND given, suck up
1628 ;; the whole structure
1629 ((and extend
1630 (setq first-symbol (py-suck-up-first-keyword) )
1631 (assq first-symbol followers))
1632 (while (and
1633 (or (py-goto-beyond-block) t) ; side effect
1634 (forward-line -1) ; side effect
1635 (setq last-pos (point)) ; side effect
1636 (py-goto-statement-below)
1637 (= (current-indentation) initial-indent)
1638 (setq next-symbol (py-suck-up-first-keyword))
1639 (memq next-symbol (cdr (assq first-symbol followers))))
1640 (setq first-symbol next-symbol)))
1641
1642 ;; else if line *opens* a block, search for next stmt indented <=
1643 ((py-statement-opens-block-p)
1644 (while (and
1645 (setq last-pos (point)) ; always true -- side effect
1646 (py-goto-statement-below)
1647 (> (current-indentation) initial-indent))
1648 nil))
1649
1650 ;; else plain code line; stop at next blank line, or stmt or
1651 ;; indenting comment line indented <
1652 (t
1653 (while (and
1654 (setq last-pos (point)) ; always true -- side effect
1655 (or (py-goto-beyond-final-line) t)
1656 (not (looking-at "[ \t]*$")) ; stop at blank line
1657 (or
1658 (>= (current-indentation) initial-indent)
1659 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1660 nil)))
1661
1662 ;; skip to end of last stmt
1663 (goto-char last-pos)
1664 (py-goto-beyond-final-line)
1665
1666 ;; set mark & display
1667 (if just-move
1668 () ; just return
1669 (push-mark (point) 'no-msg)
1670 (forward-line -1)
1671 (message "Mark set after: %s" (py-suck-up-leading-text))
1672 (goto-char initial-pos))))
1673
1674(defun mark-python-def-or-class (&optional class)
1675 "Set region to body of def (or class, with prefix arg) enclosing point.
1676Pushes the current mark, then point, on the mark ring (all language
1677modes do this, but although it's handy it's never documented ...).
1678
1679In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001680hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1681`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001682
1683And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001684Turned out that was more confusing than useful: the `goto start' and
1685`goto end' commands are usually used to search through a file, and
1686people expect them to act a lot like `search backward' and `search
1687forward' string-search commands. But because Python `def' and `class'
1688can nest to arbitrary levels, finding the smallest def containing
1689point cannot be done via a simple backward search: the def containing
1690point may not be the closest preceding def, or even the closest
1691preceding def that's indented less. The fancy algorithm required is
1692appropriate for the usual uses of this `mark' command, but not for the
1693`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001694
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001695So the def marked by this command may not be the one either of the
1696`goto' commands find: If point is on a blank or non-indenting comment
1697line, moves back to start of the closest preceding code statement or
1698indenting comment line. If this is a `def' statement, that's the def
1699we use. Else searches for the smallest enclosing `def' block and uses
1700that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001701
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001702When an enclosing def is found: The mark is left immediately beyond
1703the last line of the def block. Point is left at the start of the
1704def, except that: if the def is preceded by a number of comment lines
1705followed by (at most) one optional blank line, point is left at the
1706start of the comments; else if the def is preceded by a blank line,
1707point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001708
1709The intent is to mark the containing def/class and its associated
1710documentation, to make moving and duplicating functions and classes
1711pleasant."
1712 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001713 (let ((start (point))
1714 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715 (push-mark start)
1716 (if (not (py-go-up-tree-to-keyword which))
1717 (progn (goto-char start)
1718 (error "Enclosing %s not found" which))
1719 ;; else enclosing def/class found
1720 (setq start (point))
1721 (py-goto-beyond-block)
1722 (push-mark (point))
1723 (goto-char start)
1724 (if (zerop (forward-line -1)) ; if there is a preceding line
1725 (progn
1726 (if (looking-at "[ \t]*$") ; it's blank
1727 (setq start (point)) ; so reset start point
1728 (goto-char start)) ; else try again
1729 (if (zerop (forward-line -1))
1730 (if (looking-at "[ \t]*#") ; a comment
1731 ;; look back for non-comment line
1732 ;; tricky: note that the regexp matches a blank
1733 ;; line, cuz \n is in the 2nd character class
1734 (and
1735 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1736 (forward-line 1))
1737 ;; no comment, so go back
1738 (goto-char start))))))))
1739
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001740;; ripped from cc-mode
1741(defun py-forward-into-nomenclature (&optional arg)
1742 "Move forward to end of a nomenclature section or word.
1743With arg, to it arg times.
1744
1745A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1746 (interactive "p")
1747 (let ((case-fold-search nil))
1748 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001749 (re-search-forward
1750 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1751 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001752 (while (and (< arg 0)
1753 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001754 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001755 (point-min) 0))
1756 (forward-char 1)
1757 (setq arg (1+ arg)))))
1758 (py-keep-region-active))
1759
1760(defun py-backward-into-nomenclature (&optional arg)
1761 "Move backward to beginning of a nomenclature section or word.
1762With optional ARG, move that many times. If ARG is negative, move
1763forward.
1764
1765A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1766 (interactive "p")
1767 (py-forward-into-nomenclature (- arg))
1768 (py-keep-region-active))
1769
1770
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001771
1772;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001773
1774;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001775;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1776;; out of the right places, along with the keys they're on & current
1777;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778(defun py-dump-help-string (str)
1779 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780 (let ((locals (buffer-local-variables))
1781 funckind funcname func funcdoc
1782 (start 0) mstart end
1783 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001784 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1785 (setq mstart (match-beginning 0) end (match-end 0)
1786 funckind (substring str (match-beginning 1) (match-end 1))
1787 funcname (substring str (match-beginning 2) (match-end 2))
1788 func (intern funcname))
1789 (princ (substitute-command-keys (substring str start mstart)))
1790 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001791 ((equal funckind "c") ; command
1792 (setq funcdoc (documentation func)
1793 keys (concat
1794 "Key(s): "
1795 (mapconcat 'key-description
1796 (where-is-internal func py-mode-map)
1797 ", "))))
1798 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001799 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800 keys (if (assq func locals)
1801 (concat
1802 "Local/Global values: "
1803 (prin1-to-string (symbol-value func))
1804 " / "
1805 (prin1-to-string (default-value func)))
1806 (concat
1807 "Value: "
1808 (prin1-to-string (symbol-value func))))))
1809 (t ; unexpected
1810 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811 (princ (format "\n-> %s:\t%s\t%s\n\n"
1812 (if (equal funckind "c") "Command" "Variable")
1813 funcname keys))
1814 (princ funcdoc)
1815 (terpri)
1816 (setq start end))
1817 (princ (substitute-command-keys (substring str start))))
1818 (print-help-return-message)))
1819
1820(defun py-describe-mode ()
1821 "Dump long form of Python-mode docs."
1822 (interactive)
1823 (py-dump-help-string "Major mode for editing Python files.
1824Knows about Python indentation, tokens, comments and continuation lines.
1825Paragraphs are separated by blank lines only.
1826
1827Major sections below begin with the string `@'; specific function and
1828variable docs begin with `->'.
1829
1830@EXECUTING PYTHON CODE
1831
1832\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1833\\[py-execute-region]\tsends the current region
1834\\[py-shell]\tstarts a Python interpreter window; this will be used by
1835\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1836%c:py-execute-buffer
1837%c:py-execute-region
1838%c:py-shell
1839
1840@VARIABLES
1841
1842py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001843py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844
1845py-python-command\tshell command to invoke Python interpreter
1846py-scroll-process-buffer\talways scroll Python process buffer
1847py-temp-directory\tdirectory used for temp files (if needed)
1848
1849py-beep-if-tab-change\tring the bell if tab-width is changed
1850%v:py-indent-offset
1851%v:py-block-comment-prefix
1852%v:py-python-command
1853%v:py-scroll-process-buffer
1854%v:py-temp-directory
1855%v:py-beep-if-tab-change
1856
1857@KINDS OF LINES
1858
1859Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001860preceding line ends with a backslash that's not part of a comment, or
1861the paren/bracket/brace nesting level at the start of the line is
1862non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863
1864An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865possibly blanks or tabs), a `comment line' (leftmost non-blank
1866character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001867
1868Comment Lines
1869
1870Although all comment lines are treated alike by Python, Python mode
1871recognizes two kinds that act differently with respect to indentation.
1872
1873An `indenting comment line' is a comment line with a blank, tab or
1874nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876indenting comment line will be indented like the comment line. All
1877other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878following the initial `#') are `non-indenting comment lines', and
1879their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880
1881Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001882whenever possible. Non-indenting comment lines are useful in cases
1883like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884
1885\ta = b # a very wordy single-line comment that ends up being
1886\t #... continued onto another line
1887
1888\tif a == b:
1889##\t\tprint 'panic!' # old code we've `commented out'
1890\t\treturn a
1891
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892Since the `#...' and `##' comment lines have a non-whitespace
1893character following the initial `#', Python mode ignores them when
1894computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895
1896Continuation Lines and Statements
1897
1898The Python-mode commands generally work on statements instead of on
1899individual lines, where a `statement' is a comment or blank line, or a
1900code line and all of its following continuation lines (if any)
1901considered as a single logical unit. The commands in this mode
1902generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001903statement containing point, even if point happens to be in the middle
1904of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905
1906
1907@INDENTATION
1908
1909Primarily for entering new code:
1910\t\\[indent-for-tab-command]\t indent line appropriately
1911\t\\[py-newline-and-indent]\t insert newline, then indent
1912\t\\[py-delete-char]\t reduce indentation, or delete single character
1913
1914Primarily for reindenting existing code:
1915\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1916\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1917
1918\t\\[py-indent-region]\t reindent region to match its context
1919\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1920\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1921
1922Unlike most programming languages, Python uses indentation, and only
1923indentation, to specify block structure. Hence the indentation supplied
1924automatically by Python-mode is just an educated guess: only you know
1925the block structure you intend, so only you can supply correct
1926indentation.
1927
1928The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1929the indentation of preceding statements. E.g., assuming
1930py-indent-offset is 4, after you enter
1931\tif a > 0: \\[py-newline-and-indent]
1932the cursor will be moved to the position of the `_' (_ is not a
1933character in the file, it's just used here to indicate the location of
1934the cursor):
1935\tif a > 0:
1936\t _
1937If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1938to
1939\tif a > 0:
1940\t c = d
1941\t _
1942Python-mode cannot know whether that's what you intended, or whether
1943\tif a > 0:
1944\t c = d
1945\t_
1946was your intent. In general, Python-mode either reproduces the
1947indentation of the (closest code or indenting-comment) preceding
1948statement, or adds an extra py-indent-offset blanks if the preceding
1949statement has `:' as its last significant (non-whitespace and non-
1950comment) character. If the suggested indentation is too much, use
1951\\[py-delete-char] to reduce it.
1952
1953Continuation lines are given extra indentation. If you don't like the
1954suggested indentation, change it to something you do like, and Python-
1955mode will strive to indent later lines of the statement in the same way.
1956
1957If a line is a continuation line by virtue of being in an unclosed
1958paren/bracket/brace structure (`list', for short), the suggested
1959indentation depends on whether the current line contains the first item
1960in the list. If it does, it's indented py-indent-offset columns beyond
1961the indentation of the line containing the open bracket. If you don't
1962like that, change it by hand. The remaining items in the list will mimic
1963whatever indentation you give to the first item.
1964
1965If a line is a continuation line because the line preceding it ends with
1966a backslash, the third and following lines of the statement inherit their
1967indentation from the line preceding them. The indentation of the second
1968line in the statement depends on the form of the first (base) line: if
1969the base line is an assignment statement with anything more interesting
1970than the backslash following the leftmost assigning `=', the second line
1971is indented two columns beyond that `='. Else it's indented to two
1972columns beyond the leftmost solid chunk of non-whitespace characters on
1973the base line.
1974
1975Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1976repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1977structure you intend.
1978%c:indent-for-tab-command
1979%c:py-newline-and-indent
1980%c:py-delete-char
1981
1982
1983The next function may be handy when editing code you didn't write:
1984%c:py-guess-indent-offset
1985
1986
1987The remaining `indent' functions apply to a region of Python code. They
1988assume the block structure (equals indentation, in Python) of the region
1989is correct, and alter the indentation in various ways while preserving
1990the block structure:
1991%c:py-indent-region
1992%c:py-shift-region-left
1993%c:py-shift-region-right
1994
1995@MARKING & MANIPULATING REGIONS OF CODE
1996
1997\\[py-mark-block]\t mark block of lines
1998\\[mark-python-def-or-class]\t mark smallest enclosing def
1999\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002000\\[comment-region]\t comment out region of code
2001\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002002%c:py-mark-block
2003%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002004%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002005
2006@MOVING POINT
2007
2008\\[py-previous-statement]\t move to statement preceding point
2009\\[py-next-statement]\t move to statement following point
2010\\[py-goto-block-up]\t move up to start of current block
2011\\[beginning-of-python-def-or-class]\t move to start of def
2012\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2013\\[end-of-python-def-or-class]\t move to end of def
2014\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2015
2016The first two move to one statement beyond the statement that contains
2017point. A numeric prefix argument tells them to move that many
2018statements instead. Blank lines, comment lines, and continuation lines
2019do not count as `statements' for these commands. So, e.g., you can go
2020to the first code statement in a file by entering
2021\t\\[beginning-of-buffer]\t to move to the top of the file
2022\t\\[py-next-statement]\t to skip over initial comments and blank lines
2023Or do `\\[py-previous-statement]' with a huge prefix argument.
2024%c:py-previous-statement
2025%c:py-next-statement
2026%c:py-goto-block-up
2027%c:beginning-of-python-def-or-class
2028%c:end-of-python-def-or-class
2029
2030@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2031
2032`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2033
2034`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2035overall class and def structure of a module.
2036
2037`\\[back-to-indentation]' moves point to a line's first non-blank character.
2038
2039`\\[indent-relative]' is handy for creating odd indentation.
2040
2041@OTHER EMACS HINTS
2042
2043If you don't like the default value of a variable, change its value to
2044whatever you do like by putting a `setq' line in your .emacs file.
2045E.g., to set the indentation increment to 4, put this line in your
2046.emacs:
2047\t(setq py-indent-offset 4)
2048To see the value of a variable, do `\\[describe-variable]' and enter the variable
2049name at the prompt.
2050
2051When entering a key sequence like `C-c C-n', it is not necessary to
2052release the CONTROL key after doing the `C-c' part -- it suffices to
2053press the CONTROL key, press and release `c' (while still holding down
2054CONTROL), press and release `n' (while still holding down CONTROL), &
2055then release CONTROL.
2056
2057Entering Python mode calls with no arguments the value of the variable
2058`python-mode-hook', if that value exists and is not nil; for backward
2059compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2060the Elisp manual for details.
2061
2062Obscure: When python-mode is first loaded, it looks for all bindings
2063to newline-and-indent in the global keymap, and shadows them with
2064local bindings to py-newline-and-indent."))
2065
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002066
2067;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002068(defvar py-parse-state-re
2069 (concat
2070 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2071 "\\|"
2072 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002073
Barry Warsaw7ae77681994-12-12 20:38:05 +00002074;; returns the parse state at point (see parse-partial-sexp docs)
2075(defun py-parse-state ()
2076 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002077 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002078 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002079 (while (not done)
2080 ;; back up to the first preceding line (if any; else start of
2081 ;; buffer) that begins with a popular Python keyword, or a
2082 ;; non- whitespace and non-comment character. These are good
2083 ;; places to start parsing to see whether where we started is
2084 ;; at a non-zero nesting level. It may be slow for people who
2085 ;; write huge code blocks or huge lists ... tough beans.
2086 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002087 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002088 (beginning-of-line)
2089 (save-excursion
2090 (setq pps (parse-partial-sexp (point) here)))
2091 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002092 (setq done (or (zerop ci)
2093 (not (nth 3 pps))
2094 (bobp)))
2095 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002096 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002097
2098;; if point is at a non-zero nesting level, returns the number of the
2099;; character that opens the smallest enclosing unclosed list; else
2100;; returns nil.
2101(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002102 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002103 (if (zerop (car status))
2104 nil ; not in a nest
2105 (car (cdr status))))) ; char# of open bracket
2106
2107;; t iff preceding line ends with backslash that's not in a comment
2108(defun py-backslash-continuation-line-p ()
2109 (save-excursion
2110 (beginning-of-line)
2111 (and
2112 ;; use a cheap test first to avoid the regexp if possible
2113 ;; use 'eq' because char-after may return nil
2114 (eq (char-after (- (point) 2)) ?\\ )
2115 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002116 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002117 (looking-at py-continued-re))))
2118
2119;; t iff current line is a continuation line
2120(defun py-continuation-line-p ()
2121 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002122 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002123 (or (py-backslash-continuation-line-p)
2124 (py-nesting-level))))
2125
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002126;; go to initial line of current statement; usually this is the line
2127;; we're on, but if we're on the 2nd or following lines of a
2128;; continuation block, we need to go up to the first line of the
2129;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002130;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002131;; Tricky: We want to avoid quadratic-time behavior for long continued
2132;; blocks, whether of the backslash or open-bracket varieties, or a
2133;; mix of the two. The following manages to do that in the usual
2134;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002135(defun py-goto-initial-line ()
2136 (let ( open-bracket-pos )
2137 (while (py-continuation-line-p)
2138 (beginning-of-line)
2139 (if (py-backslash-continuation-line-p)
2140 (while (py-backslash-continuation-line-p)
2141 (forward-line -1))
2142 ;; else zip out of nested brackets/braces/parens
2143 (while (setq open-bracket-pos (py-nesting-level))
2144 (goto-char open-bracket-pos)))))
2145 (beginning-of-line))
2146
2147;; go to point right beyond final line of current statement; usually
2148;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002149;; statement we need to skip over the continuation lines. Tricky:
2150;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151(defun py-goto-beyond-final-line ()
2152 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002153 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154 (while (and (py-continuation-line-p)
2155 (not (eobp)))
2156 ;; skip over the backslash flavor
2157 (while (and (py-backslash-continuation-line-p)
2158 (not (eobp)))
2159 (forward-line 1))
2160 ;; if in nest, zip to the end of the nest
2161 (setq state (py-parse-state))
2162 (if (and (not (zerop (car state)))
2163 (not (eobp)))
2164 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002165 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00002166 ;; the 3rd argument should be plain 0
2167 (parse-partial-sexp (point) (point-max) (- 0 (car state))
2168 nil state)
2169 (forward-line 1))))))
2170
2171;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002172;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002173(defun py-statement-opens-block-p ()
2174 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002175 (let ((start (point))
2176 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2177 (searching t)
2178 (answer nil)
2179 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002180 (goto-char start)
2181 (while searching
2182 ;; look for a colon with nothing after it except whitespace, and
2183 ;; maybe a comment
2184 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2185 finish t)
2186 (if (eq (point) finish) ; note: no `else' clause; just
2187 ; keep searching if we're not at
2188 ; the end yet
2189 ;; sure looks like it opens a block -- but it might
2190 ;; be in a comment
2191 (progn
2192 (setq searching nil) ; search is done either way
2193 (setq state (parse-partial-sexp start
2194 (match-beginning 0)))
2195 (setq answer (not (nth 4 state)))))
2196 ;; search failed: couldn't find another interesting colon
2197 (setq searching nil)))
2198 answer)))
2199
Barry Warsawf831d811996-07-31 20:42:59 +00002200(defun py-statement-closes-block-p ()
2201 ;; true iff the current statement `closes' a block == the line
2202 ;; starts with `return', `raise', `break' or `continue'. doesn't
2203 ;; catch embedded statements
2204 (let ((here (point)))
2205 (back-to-indentation)
2206 (prog1
2207 (looking-at "\\(return\\|raise\\|break\\|continue\\)\\>")
2208 (goto-char here))))
2209
Barry Warsaw7ae77681994-12-12 20:38:05 +00002210;; go to point right beyond final line of block begun by the current
2211;; line. This is the same as where py-goto-beyond-final-line goes
2212;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002213;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002214(defun py-goto-beyond-block ()
2215 (if (py-statement-opens-block-p)
2216 (py-mark-block nil 'just-move)
2217 (py-goto-beyond-final-line)))
2218
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002219;; go to start of first statement (not blank or comment or
2220;; continuation line) at or preceding point. returns t if there is
2221;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002222(defun py-goto-statement-at-or-above ()
2223 (py-goto-initial-line)
2224 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002225 ;; skip back over blank & comment lines
2226 ;; note: will skip a blank or comment line that happens to be
2227 ;; a continuation line too
2228 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2229 (progn (py-goto-initial-line) t)
2230 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002231 t))
2232
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002233;; go to start of first statement (not blank or comment or
2234;; continuation line) following the statement containing point returns
2235;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002236(defun py-goto-statement-below ()
2237 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002238 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002239 (py-goto-beyond-final-line)
2240 (while (and
2241 (looking-at py-blank-or-comment-re)
2242 (not (eobp)))
2243 (forward-line 1))
2244 (if (eobp)
2245 (progn (goto-char start) nil)
2246 t)))
2247
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002248;; go to start of statement, at or preceding point, starting with
2249;; keyword KEY. Skips blank lines and non-indenting comments upward
2250;; first. If that statement starts with KEY, done, else go back to
2251;; first enclosing block starting with KEY. If successful, leaves
2252;; point at the start of the KEY line & returns t. Else leaves point
2253;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002254(defun py-go-up-tree-to-keyword (key)
2255 ;; skip blanks and non-indenting #
2256 (py-goto-initial-line)
2257 (while (and
2258 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2259 (zerop (forward-line -1))) ; go back
2260 nil)
2261 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002262 (let* ((re (concat "[ \t]*" key "\\b"))
2263 (case-fold-search nil) ; let* so looking-at sees this
2264 (found (looking-at re))
2265 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266 (while (not (or found dead))
2267 (condition-case nil ; in case no enclosing block
2268 (py-goto-block-up 'no-mark)
2269 (error (setq dead t)))
2270 (or dead (setq found (looking-at re))))
2271 (beginning-of-line)
2272 found))
2273
2274;; return string in buffer from start of indentation to end of line;
2275;; prefix "..." if leading whitespace was skipped
2276(defun py-suck-up-leading-text ()
2277 (save-excursion
2278 (back-to-indentation)
2279 (concat
2280 (if (bolp) "" "...")
2281 (buffer-substring (point) (progn (end-of-line) (point))))))
2282
2283;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2284;; as a Lisp symbol; return nil if none
2285(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002286 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002287 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2288 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2289 nil)))
2290
2291(defun py-make-temp-name ()
2292 (make-temp-name
2293 (concat (file-name-as-directory py-temp-directory) "python")))
2294
2295(defun py-delete-file-silently (fname)
2296 (condition-case nil
2297 (delete-file fname)
2298 (error nil)))
2299
2300(defun py-kill-emacs-hook ()
2301 ;; delete our temp files
2302 (while py-file-queue
2303 (py-delete-file-silently (car py-file-queue))
2304 (setq py-file-queue (cdr py-file-queue)))
2305 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2306 ;; run the hook we inherited, if any
2307 (and py-inherited-kill-emacs-hook
2308 (funcall py-inherited-kill-emacs-hook))))
2309
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002310;; make PROCESS's buffer visible, append STRING to it, and force
2311;; display; also make shell-mode believe the user typed this string,
2312;; so that kill-output-from-shell and show-output-from-shell work
2313;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002314(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002315 (let ((cbuf (current-buffer))
2316 (pbuf (process-buffer process))
2317 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002318 (set-buffer pbuf)
2319 (goto-char (point-max))
2320 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002321 (if (not (or py-this-is-emacs-19-p
2322 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002323 (move-marker last-input-start (point))) ; muck w/ shell-mode
2324 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002325 (if (not (or py-this-is-emacs-19-p
2326 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002327 (move-marker last-input-end (point))) ; muck w/ shell-mode
2328 (set-buffer cbuf))
2329 (sit-for 0))
2330
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002331
2332
Barry Warsaw850437a1995-03-08 21:50:28 +00002333(defconst py-version "$Revision$"
2334 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002335(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002336 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002337
Barry Warsaw850437a1995-03-08 21:50:28 +00002338(defun py-version ()
2339 "Echo the current version of `python-mode' in the minibuffer."
2340 (interactive)
2341 (message "Using `python-mode' version %s" py-version)
2342 (py-keep-region-active))
2343
2344;; only works under Emacs 19
2345;(eval-when-compile
2346; (require 'reporter))
2347
2348(defun py-submit-bug-report (enhancement-p)
2349 "Submit via mail a bug report on `python-mode'.
2350With \\[universal-argument] just submit an enhancement request."
2351 (interactive
2352 (list (not (y-or-n-p
2353 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002354 (let ((reporter-prompt-for-summary-p (if enhancement-p
2355 "(Very) brief summary: "
2356 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002357 (require 'reporter)
2358 (reporter-submit-bug-report
2359 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002360 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002361 ;; varlist
2362 (if enhancement-p nil
2363 '(py-python-command
2364 py-indent-offset
2365 py-block-comment-prefix
2366 py-scroll-process-buffer
2367 py-temp-directory
2368 py-beep-if-tab-change))
2369 nil ;pre-hooks
2370 nil ;post-hooks
2371 "Dear Barry,") ;salutation
2372 (if enhancement-p nil
2373 (set-mark (point))
2374 (insert
2375"Please replace this text with a sufficiently large code sample\n\
2376and an exact recipe so that I can reproduce your problem. Failure\n\
2377to do so may mean a greater delay in fixing your bug.\n\n")
2378 (exchange-point-and-mark)
2379 (py-keep-region-active))))
2380
2381
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002382;; arrange to kill temp files when Emacs exists
2383(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2384 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2385 ;; have to trust that other people are as respectful of our hook
2386 ;; fiddling as we are of theirs
2387 (if (boundp 'py-inherited-kill-emacs-hook)
2388 ;; we were loaded before -- trust others not to have screwed us
2389 ;; in the meantime (no choice, really)
2390 nil
2391 ;; else arrange for our hook to run theirs
2392 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2393 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2394
2395
2396
2397(provide 'python-mode)
2398;;; python-mode.el ends here