blob: bfe6b2b9464a163733da1b6be47f7042a0b73a86 [file] [log] [blame]
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Guido van Rossum6ba11201996-08-20 19:57:53 +00005;; Author: 1995-1996 Barry A. Warsaw
Guido van Rossumd4901c81995-08-28 03:12:57 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +00008;; Created: Feb 1992
Guido van Rossuma83f3b81996-10-23 20:55:00 +00009;; Version: 2.83
10;; Last Modified: 1996/10/23 20:44:59
Guido van Rossum6ba11201996-08-20 19:57:53 +000011;; Keywords: python languages oop
Guido van Rossumdeaa1051995-03-10 16:17:03 +000012
Guido van Rossuma8a8d4a1995-03-10 16:19:31 +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.
Guido van Rossumdeaa1051995-03-10 16:17:03 +000018
19;;; Commentary:
Guido van Rossum6ba11201996-08-20 19:57:53 +000020
Guido van Rossumdeaa1051995-03-10 16:17:03 +000021;; This is a major mode for editing Python programs. It was developed
Guido van Rossum880d1ee1996-08-20 20:07: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.
Guido van Rossumdeaa1051995-03-10 16:17:03 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
Guido van Rossum6ba11201996-08-20 19:57:53 +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!
Guido van Rossumdeaa1051995-03-10 16:17:03 +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):
Guido van Rossuma7925f11994-01-26 10:20:16 +000037;;
Guido van Rossumdeaa1051995-03-10 16:17:03 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Guido van Rossuma7925f11994-01-26 10:20:16 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Guido van Rossum1d5645d1995-03-14 21:31:47 +000041;;
Guido van Rossum6ba11201996-08-20 19:57:53 +000042;; 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)
46;;
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.
50
51;; Here's a brief list of recent additions/improvements/changes:
52;;
53;; - Wrapping and indentation within triple quote strings now works.
Guido van Rossum1d5645d1995-03-14 21:31:47 +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
Guido van Rossum6ba11201996-08-20 19:57:53 +000057;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Guido van Rossum1d5645d1995-03-14 21:31:47 +000058;; - proper interaction with pending-del and del-sel modes.
Guido van Rossum6ba11201996-08-20 19:57:53 +000059;; - Better support for outdenting: py-electric-colon (:) and
60;; py-indent-line (TAB) improvements; one level of outdentation
Guido van Rossuma83f3b81996-10-23 20:55:00 +000061;; added after a return, raise, break, pass, or continue statement.
62;; Defeated by prefixing command with C-u.
Guido van Rossum6ba11201996-08-20 19:57:53 +000063;; - New py-electric-colon (:) command for improved outdenting Also
64;; py-indent-line (TAB) should handle outdented lines better
65;; - improved (I think) C-c > and C-c <
66;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
67;; M-f and M-b respectively.
68;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
69;; - py-indent-offset now defaults to 4
70;; - new variable py-honor-comment-indentation
71;; - comment-region bound to C-c #
72;; - py-delete-char obeys numeric arguments
73;; - Small modification to rule for "indenting comment lines", such
74;; lines must now also be indented less than or equal to the
75;; indentation of the previous statement.
Guido van Rossum1d5645d1995-03-14 21:31:47 +000076
Guido van Rossumdeaa1051995-03-10 16:17:03 +000077;; Here's a brief to do list:
78;;
Guido van Rossum1d5645d1995-03-14 21:31:47 +000079;; - Better integration with gud-mode for debugging.
80;; - Rewrite according to GNU Emacs Lisp standards.
Guido van Rossum6ba11201996-08-20 19:57:53 +000081;; - possibly force indent-tabs-mode == nil, and add a
82;; write-file-hooks that runs untabify on the whole buffer (to work
83;; around potential tab/space mismatch problems). In practice this
84;; hasn't been a problem... yet.
85;; - have py-execute-region on indented code act as if the region is
86;; left justified. Avoids syntax errors.
Guido van Rossuma83f3b81996-10-23 20:55:00 +000087;; - Add a py-goto-error or some such that would scan an exception in
88;; the py-shell buffer, and pop you to that line in the file.
Guido van Rossuma7925f11994-01-26 10:20:16 +000089
Guido van Rossumdeaa1051995-03-10 16:17:03 +000090;; If you can think of more things you'd like to see, drop me a line.
91;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
92;;
Guido van Rossum6ba11201996-08-20 19:57:53 +000093;; Note that I only test things on XEmacs 19 and to some degree on
94;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
95;; send me your patches. Byte compiler complaints can probably be
96;; safely ignored.
Guido van Rossuma7925f11994-01-26 10:20:16 +000097
Guido van Rossumdeaa1051995-03-10 16:17:03 +000098;;; Code:
99
100
101;; user definable variables
102;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Guido van Rossuma7925f11994-01-26 10:20:16 +0000103
104(defvar py-python-command "python"
105 "*Shell command used to start Python interpreter.")
106
Guido van Rossum6ba11201996-08-20 19:57:53 +0000107(defvar py-indent-offset 4
Guido van Rossuma7925f11994-01-26 10:20:16 +0000108 "*Indentation increment.
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000109Note that `\\[py-guess-indent-offset]' can usually guess a good value
110when you're editing someone else's Python code.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000111
Guido van Rossum503b2e81995-10-08 00:44:23 +0000112(defvar py-align-multiline-strings-p t
113 "*Flag describing how multiline triple quoted strings are aligned.
114When this flag is non-nil, continuation lines are lined up under the
115preceding line's indentation. When this flag is nil, continuation
116lines are aligned to column zero.")
117
Guido van Rossum6ba11201996-08-20 19:57:53 +0000118(defvar py-block-comment-prefix "## "
119 "*String used by \\[comment-region] to comment out a block of code.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000120This should follow the convention for non-indenting comment lines so
121that the indentation commands won't get confused (i.e., the string
122should be of the form `#x...' where `x' is not a blank or a tab, and
123`...' is arbitrary).")
124
Guido van Rossum6ba11201996-08-20 19:57:53 +0000125(defvar py-honor-comment-indentation t
126 "*Controls how comment lines influence subsequent indentation.
127
128When nil, all comment lines are skipped for indentation purposes, and
129in Emacs 19, a faster algorithm is used.
130
131When t, lines that begin with a single `#' are a hint to subsequent
132line indentation. If the previous line is such a comment line (as
133opposed to one that starts with `py-block-comment-prefix'), then it's
134indentation is used as a hint for this line's indentation. Lines that
135begin with `py-block-comment-prefix' are ignored for indentation
136purposes.
137
138When not nil or t, comment lines that begin with a `#' are used as
139indentation hints, unless the comment character is in column zero.")
140
Guido van Rossuma7925f11994-01-26 10:20:16 +0000141(defvar py-scroll-process-buffer t
142 "*Scroll Python process buffer as output arrives.
143If nil, the Python process buffer acts, with respect to scrolling, like
144Shell-mode buffers normally act. This is surprisingly complicated and
145so won't be explained here; in fact, you can't get the whole story
146without studying the Emacs C code.
147
148If non-nil, the behavior is different in two respects (which are
149slightly inaccurate in the interest of brevity):
150
151 - If the buffer is in a window, and you left point at its end, the
152 window will scroll as new output arrives, and point will move to the
153 buffer's end, even if the window is not the selected window (that
154 being the one the cursor is in). The usual behavior for shell-mode
155 windows is not to scroll, and to leave point where it was, if the
156 buffer is in a window other than the selected window.
157
158 - If the buffer is not visible in any window, and you left point at
159 its end, the buffer will be popped into a window as soon as more
160 output arrives. This is handy if you have a long-running
161 computation and don't want to tie up screen area waiting for the
162 output. The usual behavior for a shell-mode buffer is to stay
163 invisible until you explicitly visit it.
164
165Note the `and if you left point at its end' clauses in both of the
166above: you can `turn off' the special behaviors while output is in
167progress, by visiting the Python buffer and moving point to anywhere
168besides the end. Then the buffer won't scroll, point will remain where
169you leave it, and if you hide the buffer it will stay hidden until you
170visit it again. You can enable and disable the special behaviors as
171often as you like, while output is in progress, by (respectively) moving
172point to, or away from, the end of the buffer.
173
174Warning: If you expect a large amount of output, you'll probably be
175happier setting this option to nil.
176
177Obscure: `End of buffer' above should really say `at or beyond the
178process mark', but if you know what that means you didn't need to be
179told <grin>.")
180
181(defvar py-temp-directory
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000182 (let ((ok '(lambda (x)
183 (and x
184 (setq x (expand-file-name x)) ; always true
185 (file-directory-p x)
186 (file-writable-p x)
187 x))))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000188 (or (funcall ok (getenv "TMPDIR"))
189 (funcall ok "/usr/tmp")
190 (funcall ok "/tmp")
191 (funcall ok ".")
192 (error
193 "Couldn't find a usable temp directory -- set py-temp-directory")))
194 "*Directory used for temp files created by a *Python* process.
195By default, the first directory from this list that exists and that you
196can write into: the value (if any) of the environment variable TMPDIR,
197/usr/tmp, /tmp, or the current directory.")
198
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000199(defvar py-beep-if-tab-change t
200 "*Ring the bell if tab-width is changed.
201If a comment of the form
202
203 \t# vi:set tabsize=<number>:
204
205is found before the first code line when the file is entered, and the
206current value of (the general Emacs variable) `tab-width' does not
207equal <number>, `tab-width' is set to <number>, a message saying so is
208displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
209the Emacs bell is also rung as a warning.")
210
Guido van Rossum6ba11201996-08-20 19:57:53 +0000211(defconst python-font-lock-keywords
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000212 (let* ((keywords '("and" "break" "class"
Guido van Rossum6ba11201996-08-20 19:57:53 +0000213 "continue" "def" "del" "elif"
214 "else:" "except" "except:" "exec"
215 "finally:" "for" "from" "global"
216 "if" "import" "in" "is"
217 "lambda" "not" "or" "pass"
218 "print" "raise" "return" "try:"
219 "while"
220 ))
221 (kwregex (mapconcat 'identity keywords "\\|")))
222 (list
223 ;; keywords not at beginning of line
224 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
225 ;; keywords at beginning of line. i don't think regexps are
226 ;; powerful enough to handle these two cases in one regexp.
227 ;; prove me wrong!
228 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
229 ;; classes
230 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
231 1 font-lock-type-face)
232 ;; functions
233 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
234 1 font-lock-function-name-face)
235 ))
236 "Additional expressions to highlight in Python mode.")
Guido van Rossumd4901c81995-08-28 03:12:57 +0000237
Guido van Rossum6ba11201996-08-20 19:57:53 +0000238(defvar imenu-example--python-show-method-args-p nil
239 "*Controls echoing of arguments of functions & methods in the imenu buffer.
240When non-nil, arguments are printed.")
Guido van Rossumd4901c81995-08-28 03:12:57 +0000241
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000242
243
244;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
245;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
246
Guido van Rossum6ba11201996-08-20 19:57:53 +0000247(make-variable-buffer-local 'py-indent-offset)
248
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000249;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
250;; seems to be the standard way of checking this.
251;; BAW - This is *not* the right solution. When at all possible,
252;; instead of testing for the version of Emacs, use feature tests.
253
254(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
255(setq py-this-is-emacs-19-p
256 (and
257 (not py-this-is-lucid-emacs-p)
258 (string-match "^19\\." emacs-version)))
259
Guido van Rossuma7925f11994-01-26 10:20:16 +0000260;; have to bind py-file-queue before installing the kill-emacs hook
261(defvar py-file-queue nil
262 "Queue of Python temp files awaiting execution.
263Currently-active file is at the head of the list.")
264
265;; define a mode-specific abbrev table for those who use such things
266(defvar python-mode-abbrev-table nil
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000267 "Abbrev table in use in `python-mode' buffers.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000268(define-abbrev-table 'python-mode-abbrev-table nil)
269
Guido van Rossuma67bb7e1994-11-10 23:01:59 +0000270(defvar python-mode-hook nil
271 "*Hook called by `python-mode'.")
272
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000273;; in previous version of python-mode.el, the hook was incorrectly
274;; called py-mode-hook, and was not defvar'd. deprecate its use.
Guido van Rossuma67bb7e1994-11-10 23:01:59 +0000275(and (fboundp 'make-obsolete-variable)
276 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
277
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000278(defvar py-mode-map ()
279 "Keymap used in `python-mode' buffers.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000280
Guido van Rossuma7925f11994-01-26 10:20:16 +0000281(if py-mode-map
282 ()
283 (setq py-mode-map (make-sparse-keymap))
284
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000285 ;; shadow global bindings for newline-and-indent w/ the py- version.
286 ;; BAW - this is extremely bad form, but I'm not going to change it
287 ;; for now.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000288 (mapcar (function (lambda (key)
289 (define-key
290 py-mode-map key 'py-newline-and-indent)))
291 (where-is-internal 'newline-and-indent))
292
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000293 ;; BAW - you could do it this way, but its not considered proper
294 ;; major-mode form.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000295 (mapcar (function
296 (lambda (x)
297 (define-key py-mode-map (car x) (cdr x))))
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000298 '((":" . py-electric-colon)
299 ("\C-c\C-c" . py-execute-buffer)
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000300 ("\C-c|" . py-execute-region)
301 ("\C-c!" . py-shell)
302 ("\177" . py-delete-char)
303 ("\n" . py-newline-and-indent)
304 ("\C-c:" . py-guess-indent-offset)
305 ("\C-c\t" . py-indent-region)
Guido van Rossum6ba11201996-08-20 19:57:53 +0000306 ("\C-c\C-l" . py-shift-region-left)
307 ("\C-c\C-r" . py-shift-region-right)
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000308 ("\C-c<" . py-shift-region-left)
309 ("\C-c>" . py-shift-region-right)
310 ("\C-c\C-n" . py-next-statement)
311 ("\C-c\C-p" . py-previous-statement)
312 ("\C-c\C-u" . py-goto-block-up)
313 ("\C-c\C-m" . py-mark-block)
314 ("\C-c#" . py-comment-region)
315 ("\C-c?" . py-describe-mode)
316 ("\C-c\C-hm" . py-describe-mode)
317 ("\e\C-a" . beginning-of-python-def-or-class)
318 ("\e\C-e" . end-of-python-def-or-class)
319 ( "\e\C-h" . mark-python-def-or-class)))
320 ;; should do all keybindings this way
321 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
322 (define-key py-mode-map "\C-c\C-v" 'py-version)
323 )
Guido van Rossuma7925f11994-01-26 10:20:16 +0000324
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000325(defvar py-mode-syntax-table nil
326 "Syntax table used in `python-mode' buffers.")
327
Guido van Rossuma7925f11994-01-26 10:20:16 +0000328(if py-mode-syntax-table
329 ()
330 (setq py-mode-syntax-table (make-syntax-table))
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000331 ;; BAW - again, blech.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000332 (mapcar (function
333 (lambda (x) (modify-syntax-entry
334 (car x) (cdr x) py-mode-syntax-table)))
335 '(( ?\( . "()" ) ( ?\) . ")(" )
336 ( ?\[ . "(]" ) ( ?\] . ")[" )
337 ( ?\{ . "(}" ) ( ?\} . "){" )
338 ;; fix operator symbols misassigned in the std table
339 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
340 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
341 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
342 ( ?\> . "." ) ( ?\| . "." )
Guido van Rossum6ba11201996-08-20 19:57:53 +0000343 ;; for historical reasons, underscore is word class
344 ;; instead of symbol class. it should be symbol class,
345 ;; but if you're tempted to change it, try binding M-f and
346 ;; M-b to py-forward-into-nomenclature and
347 ;; py-backward-into-nomenclature instead. -baw
348 ( ?\_ . "w" ) ; underscore is legit in words
Guido van Rossuma7925f11994-01-26 10:20:16 +0000349 ( ?\' . "\"") ; single quote is string quote
350 ( ?\" . "\"" ) ; double quote is string quote too
351 ( ?\` . "$") ; backquote is open and close paren
352 ( ?\# . "<") ; hash starts comment
353 ( ?\n . ">")))) ; newline ends comment
354
Guido van Rossume531e4b1994-04-16 08:29:27 +0000355(defconst py-stringlit-re
356 (concat
357 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
358 "\\|" ; or
359 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000360 "Regexp matching a Python string literal.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000361
362;; this is tricky because a trailing backslash does not mean
363;; continuation if it's in a comment
364(defconst py-continued-re
365 (concat
Guido van Rossume531e4b1994-04-16 08:29:27 +0000366 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
Guido van Rossuma7925f11994-01-26 10:20:16 +0000367 "\\\\$")
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000368 "Regexp matching Python lines that are continued via backslash.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000369
370(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000371 "Regexp matching blank or comment lines.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000372
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000373(defconst py-outdent-re
374 (concat "\\(" (mapconcat 'identity
375 '("else:"
Guido van Rossum1c1fbf81995-03-14 21:33:10 +0000376 "except\\(\\s +.*\\)?:"
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000377 "finally:"
378 "elif\\s +.*:")
379 "\\|")
380 "\\)")
381 "Regexp matching clauses to be outdented one level.")
Guido van Rossuma7925f11994-01-26 10:20:16 +0000382
Guido van Rossum1c1fbf81995-03-14 21:33:10 +0000383(defconst py-no-outdent-re
384 (concat "\\(" (mapconcat 'identity
Guido van Rossum2ed53541995-03-15 19:57:14 +0000385 '("try:"
Guido van Rossum1c1fbf81995-03-14 21:33:10 +0000386 "except\\(\\s +.*\\)?:"
387 "while\\s +.*:"
388 "for\\s +.*:"
389 "if\\s +.*:"
Guido van Rossum6ba11201996-08-20 19:57:53 +0000390 "elif\\s +.*:"
391 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
392 )
Guido van Rossum1c1fbf81995-03-14 21:33:10 +0000393 "\\|")
394 "\\)")
395 "Regexp matching lines to not outdent after.")
396
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000397(defvar py-defun-start-re
398 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
399 "Regexp matching a function, method or variable assignment.
400
401If you change this, you probably have to change `py-current-defun' as well.
402This is only used by `py-current-defun' to find the name for add-log.el.")
403
404(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
405 "Regexp for finding a class name.
406
407If you change this, you probably have to change `py-current-defun' as well.
408This is only used by `py-current-defun' to find the name for add-log.el.")
409
410
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000411
Guido van Rossum6ba11201996-08-20 19:57:53 +0000412;; Menu definitions, only relevent if you have the easymenu.el package
413;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
414(defvar py-menu nil
415 "Menu for Python Mode.
416
417This menu will get created automatically if you have the easymenu
418package. Note that the latest XEmacs 19 and Emacs 19 versions contain
419this package.")
420
421(if (condition-case nil
422 (require 'easymenu)
423 (error nil))
424 (easy-menu-define
425 py-menu py-mode-map "Python Mode menu"
426 '("Python"
427 ["Comment Out Region" comment-region (mark)]
428 ["Uncomment Region" (comment-region (point) (mark) '(4)) (mark)]
429 "-"
430 ["Mark current block" py-mark-block t]
431 ["Mark current def" mark-python-def-or-class t]
432 ["Mark current class" (mark-python-def-or-class t) t]
433 "-"
434 ["Shift region left" py-shift-region-left (mark)]
435 ["Shift region right" py-shift-region-right (mark)]
436 "-"
437 ["Execute buffer" py-execute-buffer t]
438 ["Execute region" py-execute-region (mark)]
439 ["Start interpreter..." py-shell t]
440 "-"
441 ["Go to start of block" py-goto-block-up t]
442 ["Go to start of class" (beginning-of-python-def-or-class t) t]
443 ["Move to end of class" (end-of-python-def-or-class t) t]
444 ["Move to start of def" beginning-of-python-def-or-class t]
445 ["Move to end of def" end-of-python-def-or-class t]
446 "-"
447 ["Describe mode" py-describe-mode t]
448 )))
449
450
451
452;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
453(defvar imenu-example--python-class-regexp
454 (concat ; <<classes>>
455 "\\(" ;
456 "^[ \t]*" ; newline and maybe whitespace
457 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
458 ; possibly multiple superclasses
459 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
460 "[ \t]*:" ; and the final :
461 "\\)" ; >>classes<<
462 )
463 "Regexp for Python classes for use with the imenu package."
464 )
465
466(defvar imenu-example--python-method-regexp
467 (concat ; <<methods and functions>>
468 "\\(" ;
469 "^[ \t]*" ; new line and maybe whitespace
470 "\\(def[ \t]+" ; function definitions start with def
471 "\\([a-zA-Z0-9_]+\\)" ; name is here
472 ; function arguments...
473 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
474 "\\)" ; end of def
475 "[ \t]*:" ; and then the :
476 "\\)" ; >>methods and functions<<
477 )
478 "Regexp for Python methods/functions for use with the imenu package."
479 )
480
481(defvar imenu-example--python-method-no-arg-parens '(2 8)
482 "Indicies into groups of the Python regexp for use with imenu.
483
484Using these values will result in smaller imenu lists, as arguments to
485functions are not listed.
486
487See the variable `imenu-example--python-show-method-args-p' for more
488information.")
489
490(defvar imenu-example--python-method-arg-parens '(2 7)
491 "Indicies into groups of the Python regexp for use with imenu.
492Using these values will result in large imenu lists, as arguments to
493functions are listed.
494
495See the variable `imenu-example--python-show-method-args-p' for more
496information.")
497
498;; Note that in this format, this variable can still be used with the
499;; imenu--generic-function. Otherwise, there is no real reason to have
500;; it.
501(defvar imenu-example--generic-python-expression
502 (cons
503 (concat
504 imenu-example--python-class-regexp
505 "\\|" ; or...
506 imenu-example--python-method-regexp
507 )
508 imenu-example--python-method-no-arg-parens)
509 "Generic Python expression which may be used directly with imenu.
510Used by setting the variable `imenu-generic-expression' to this value.
511Also, see the function \\[imenu-example--create-python-index] for a
512better alternative for finding the index.")
513
514;; These next two variables are used when searching for the python
515;; class/definitions. Just saving some time in accessing the
516;; generic-python-expression, really.
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000517(defvar imenu-example--python-generic-regexp nil)
518(defvar imenu-example--python-generic-parens nil)
Guido van Rossum6ba11201996-08-20 19:57:53 +0000519
520
521;;;###autoload
522(eval-when-compile
523 ;; Imenu isn't used in XEmacs, so just ignore load errors
524 (condition-case ()
525 (progn
526 (require 'cl)
527 (require 'imenu))
528 (error nil)))
529
530(defun imenu-example--create-python-index ()
531 "Python interface function for imenu package.
532Finds all python classes and functions/methods. Calls function
533\\[imenu-example--create-python-index-engine]. See that function for
534the details of how this works."
535 (setq imenu-example--python-generic-regexp
536 (car imenu-example--generic-python-expression))
537 (setq imenu-example--python-generic-parens
538 (if imenu-example--python-show-method-args-p
539 imenu-example--python-method-arg-parens
540 imenu-example--python-method-no-arg-parens))
541 (goto-char (point-min))
542 (imenu-example--create-python-index-engine nil))
543
544(defun imenu-example--create-python-index-engine (&optional start-indent)
545 "Function for finding imenu definitions in Python.
546
547Finds all definitions (classes, methods, or functions) in a Python
548file for the imenu package.
549
550Returns a possibly nested alist of the form
551
552 (INDEX-NAME . INDEX-POSITION)
553
554The second element of the alist may be an alist, producing a nested
555list as in
556
557 (INDEX-NAME . INDEX-ALIST)
558
559This function should not be called directly, as it calls itself
560recursively and requires some setup. Rather this is the engine for
561the function \\[imenu-example--create-python-index].
562
563It works recursively by looking for all definitions at the current
564indention level. When it finds one, it adds it to the alist. If it
565finds a definition at a greater indentation level, it removes the
566previous definition from the alist. In it's place it adds all
567definitions found at the next indentation level. When it finds a
568definition that is less indented then the current level, it retuns the
569alist it has created thus far.
570
571The optional argument START-INDENT indicates the starting indentation
572at which to continue looking for Python classes, methods, or
573functions. If this is not supplied, the function uses the indentation
574of the first definition found."
575 (let ((index-alist '())
576 (sub-method-alist '())
577 looking-p
578 def-name prev-name
579 cur-indent def-pos
580 (class-paren (first imenu-example--python-generic-parens))
581 (def-paren (second imenu-example--python-generic-parens)))
582 (setq looking-p
583 (re-search-forward imenu-example--python-generic-regexp
584 (point-max) t))
585 (while looking-p
586 (save-excursion
587 ;; used to set def-name to this value but generic-extract-name is
588 ;; new to imenu-1.14. this way it still works with imenu-1.11
589 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
590 (let ((cur-paren (if (match-beginning class-paren)
591 class-paren def-paren)))
592 (setq def-name
593 (buffer-substring (match-beginning cur-paren)
594 (match-end cur-paren))))
595 (beginning-of-line)
596 (setq cur-indent (current-indentation)))
597
598 ;; HACK: want to go to the next correct definition location. we
599 ;; explicitly list them here. would be better to have them in a
600 ;; list.
601 (setq def-pos
602 (or (match-beginning class-paren)
603 (match-beginning def-paren)))
604
605 ;; if we don't have a starting indent level, take this one
606 (or start-indent
607 (setq start-indent cur-indent))
608
609 ;; if we don't have class name yet, take this one
610 (or prev-name
611 (setq prev-name def-name))
612
613 ;; what level is the next definition on? must be same, deeper
614 ;; or shallower indentation
615 (cond
616 ;; at the same indent level, add it to the list...
617 ((= start-indent cur-indent)
618
619 ;; if we don't have push, use the following...
620 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
621 (push (cons def-name def-pos) index-alist))
622
623 ;; deeper indented expression, recur...
624 ((< start-indent cur-indent)
625
626 ;; the point is currently on the expression we're supposed to
627 ;; start on, so go back to the last expression. The recursive
628 ;; call will find this place again and add it to the correct
629 ;; list
630 (re-search-backward imenu-example--python-generic-regexp
631 (point-min) 'move)
632 (setq sub-method-alist (imenu-example--create-python-index-engine
633 cur-indent))
634
635 (if sub-method-alist
636 ;; we put the last element on the index-alist on the start
637 ;; of the submethod alist so the user can still get to it.
638 (let ((save-elmt (pop index-alist)))
639 (push (cons (imenu-create-submenu-name prev-name)
640 (cons save-elmt sub-method-alist))
641 index-alist))))
642
643 ;; found less indented expression, we're done.
644 (t
645 (setq looking-p nil)
646 (re-search-backward imenu-example--python-generic-regexp
647 (point-min) t)))
648 (setq prev-name def-name)
649 (and looking-p
650 (setq looking-p
651 (re-search-forward imenu-example--python-generic-regexp
652 (point-max) 'move))))
653 (nreverse index-alist)))
654
655
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000656;;;###autoload
Guido van Rossuma7925f11994-01-26 10:20:16 +0000657(defun python-mode ()
658 "Major mode for editing Python files.
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000659To submit a problem report, enter `\\[py-submit-bug-report]' from a
660`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
661documentation. To see what version of `python-mode' you are running,
662enter `\\[py-version]'.
663
664This mode knows about Python indentation, tokens, comments and
665continuation lines. Paragraphs are separated by blank lines only.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000666
667COMMANDS
668\\{py-mode-map}
669VARIABLES
670
Guido van Rossum6ba11201996-08-20 19:57:53 +0000671py-indent-offset\t\tindentation increment
672py-block-comment-prefix\t\tcomment string used by comment-region
673py-python-command\t\tshell command to invoke Python interpreter
674py-scroll-process-buffer\t\talways scroll Python process buffer
675py-temp-directory\t\tdirectory used for temp files (if needed)
676py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Guido van Rossuma7925f11994-01-26 10:20:16 +0000677 (interactive)
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000678 ;; set up local variables
Guido van Rossuma7925f11994-01-26 10:20:16 +0000679 (kill-all-local-variables)
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000680 (make-local-variable 'font-lock-defaults)
681 (make-local-variable 'paragraph-separate)
682 (make-local-variable 'paragraph-start)
683 (make-local-variable 'require-final-newline)
684 (make-local-variable 'comment-start)
685 (make-local-variable 'comment-start-skip)
686 (make-local-variable 'comment-column)
687 (make-local-variable 'indent-region-function)
688 (make-local-variable 'indent-line-function)
689 (make-local-variable 'add-log-current-defun-function)
690 ;;
Guido van Rossuma7925f11994-01-26 10:20:16 +0000691 (set-syntax-table py-mode-syntax-table)
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000692 (setq major-mode 'python-mode
693 mode-name "Python"
694 local-abbrev-table python-mode-abbrev-table
695 font-lock-defaults '(python-font-lock-keywords)
696 paragraph-separate "^[ \t]*$"
697 paragraph-start "^[ \t]*$"
698 require-final-newline t
699 comment-start "# "
700 comment-start-skip "# *"
701 comment-column 40
702 indent-region-function 'py-indent-region
703 indent-line-function 'py-indent-line
704 ;; tell add-log.el how to find the current function/method/variable
705 add-log-current-defun-function 'py-current-defun
706 )
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000707 (use-local-map py-mode-map)
Guido van Rossum6ba11201996-08-20 19:57:53 +0000708 ;; add the menu
709 (if py-menu
710 (easy-menu-add py-menu))
Guido van Rossum503b2e81995-10-08 00:44:23 +0000711 ;; Emacs 19 requires this
712 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
713 (setq comment-multi-line nil))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000714 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000715 ;;
716 ;; not sure where the magic comment has to be; to save time
717 ;; searching for a rarity, we give up if it's not found prior to the
718 ;; first executable statement.
719 ;;
720 ;; BAW - on first glance, this seems like complete hackery. Why was
721 ;; this necessary, and is it still necessary?
722 (let ((case-fold-search nil)
723 (start (point))
724 new-tab-width)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000725 (if (re-search-forward
726 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
727 (prog2 (py-next-statement 1) (point) (goto-char 1))
728 t)
729 (progn
730 (setq new-tab-width
731 (string-to-int
732 (buffer-substring (match-beginning 1) (match-end 1))))
733 (if (= tab-width new-tab-width)
734 nil
735 (setq tab-width new-tab-width)
736 (message "Caution: tab-width changed to %d" new-tab-width)
737 (if py-beep-if-tab-change (beep)))))
738 (goto-char start))
739
Guido van Rossum6ba11201996-08-20 19:57:53 +0000740 ;; install imenu
741 (setq imenu-create-index-function
742 (function imenu-example--create-python-index))
743 (if (fboundp 'imenu-add-to-menubar)
744 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
745
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000746 ;; run the mode hook. py-mode-hook use is deprecated
Guido van Rossuma67bb7e1994-11-10 23:01:59 +0000747 (if python-mode-hook
748 (run-hooks 'python-mode-hook)
749 (run-hooks 'py-mode-hook)))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000750
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000751
Guido van Rossum6ba11201996-08-20 19:57:53 +0000752(defun py-keep-region-active ()
753 ;; do whatever is necessary to keep the region active in XEmacs.
754 ;; Ignore byte-compiler warnings you might see. Also note that
755 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
756 ;; require us to take explicit action.
757 (and (boundp 'zmacs-region-stays)
758 (setq zmacs-region-stays t)))
759
760
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000761;; electric characters
Guido van Rossumd97cc371995-03-15 19:55:55 +0000762(defun py-outdent-p ()
763 ;; returns non-nil if the current line should outdent one level
764 (save-excursion
765 (and (progn (back-to-indentation)
766 (looking-at py-outdent-re))
767 (progn (backward-to-indentation 1)
768 (while (or (looking-at py-blank-or-comment-re)
769 (bobp))
770 (backward-to-indentation 1))
771 (not (looking-at py-no-outdent-re)))
772 )))
773
774
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000775(defun py-electric-colon (arg)
776 "Insert a colon.
777In certain cases the line is outdented appropriately. If a numeric
Guido van Rossum503b2e81995-10-08 00:44:23 +0000778argument is provided, that many colons are inserted non-electrically.
779Electric behavior is inhibited inside a string or comment."
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000780 (interactive "P")
781 (self-insert-command (prefix-numeric-value arg))
Guido van Rossum503b2e81995-10-08 00:44:23 +0000782 ;; are we in a string or comment?
783 (if (save-excursion
784 (let ((pps (parse-partial-sexp (save-excursion
785 (beginning-of-python-def-or-class)
786 (point))
787 (point))))
788 (not (or (nth 3 pps) (nth 4 pps)))))
789 (save-excursion
790 (let ((here (point))
791 (outdent 0)
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000792 (indent (py-compute-indentation t)))
Guido van Rossum503b2e81995-10-08 00:44:23 +0000793 (if (and (not arg)
794 (py-outdent-p)
795 (= indent (save-excursion
Guido van Rossum6ba11201996-08-20 19:57:53 +0000796 (py-next-statement -1)
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000797 (py-compute-indentation t)))
Guido van Rossum503b2e81995-10-08 00:44:23 +0000798 )
799 (setq outdent py-indent-offset))
800 ;; Don't indent, only outdent. This assumes that any lines that
801 ;; are already outdented relative to py-compute-indentation were
802 ;; put there on purpose. Its highly annoying to have `:' indent
803 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
804 ;; there a better way to determine this???
805 (if (< (current-indentation) indent) nil
806 (goto-char here)
807 (beginning-of-line)
808 (delete-horizontal-space)
809 (indent-to (- indent outdent))
810 )))))
Guido van Rossum2ed53541995-03-15 19:57:14 +0000811
Guido van Rossum1d5645d1995-03-14 21:31:47 +0000812
Guido van Rossuma7925f11994-01-26 10:20:16 +0000813;;; Functions that execute Python commands in a subprocess
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000814;;;###autoload
Guido van Rossuma7925f11994-01-26 10:20:16 +0000815(defun py-shell ()
816 "Start an interactive Python interpreter in another window.
817This is like Shell mode, except that Python is running in the window
818instead of a shell. See the `Interactive Shell' and `Shell Mode'
819sections of the Emacs manual for details, especially for the key
820bindings active in the `*Python*' buffer.
821
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000822See the docs for variable `py-scroll-buffer' for info on scrolling
Guido van Rossuma7925f11994-01-26 10:20:16 +0000823behavior in the process window.
824
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000825Warning: Don't use an interactive Python if you change sys.ps1 or
826sys.ps2 from their default values, or if you're running code that
827prints `>>> ' or `... ' at the start of a line. `python-mode' can't
828distinguish your output from Python's output, and assumes that `>>> '
829at the start of a line is a prompt from Python. Similarly, the Emacs
830Shell mode code assumes that both `>>> ' and `... ' at the start of a
831line are Python prompts. Bad things can happen if you fool either
832mode.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000833
834Warning: If you do any editing *in* the process buffer *while* the
835buffer is accepting output from Python, do NOT attempt to `undo' the
836changes. Some of the output (nowhere near the parts you changed!) may
837be lost if you do. This appears to be an Emacs bug, an unfortunate
838interaction between undo and process filters; the same problem exists in
839non-Python process buffers using the default (Emacs-supplied) process
840filter."
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000841 ;; BAW - should undo be disabled in the python process buffer, if
842 ;; this bug still exists?
Guido van Rossuma7925f11994-01-26 10:20:16 +0000843 (interactive)
844 (if py-this-is-emacs-19-p
845 (progn
846 (require 'comint)
847 (switch-to-buffer-other-window
848 (make-comint "Python" py-python-command)))
849 (progn
850 (require 'shell)
851 (switch-to-buffer-other-window
Guido van Rossum6ba11201996-08-20 19:57:53 +0000852 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Guido van Rossumd4901c81995-08-28 03:12:57 +0000853 "Python" py-python-command nil))))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000854 (make-local-variable 'shell-prompt-pattern)
855 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
856 (set-process-filter (get-buffer-process (current-buffer))
857 'py-process-filter)
858 (set-syntax-table py-mode-syntax-table))
859
860(defun py-execute-region (start end)
861 "Send the region between START and END to a Python interpreter.
862If there is a *Python* process it is used.
863
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000864Hint: If you want to execute part of a Python file several times
865\(e.g., perhaps you're developing a function and want to flesh it out
866a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
867the region of interest, and send the code to a *Python* process via
868`\\[py-execute-buffer]' instead.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000869
870Following are subtleties to note when using a *Python* process:
871
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000872If a *Python* process is used, the region is copied into a temporary
873file (in directory `py-temp-directory'), and an `execfile' command is
874sent to Python naming that file. If you send regions faster than
875Python can execute them, `python-mode' will save them into distinct
876temp files, and execute the next one in the queue the next time it
877sees a `>>> ' prompt from Python. Each time this happens, the process
878buffer is popped into a window (if it's not already in some window) so
879you can see it, and a comment of the form
Guido van Rossuma7925f11994-01-26 10:20:16 +0000880
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000881 \t## working on region in file <name> ...
Guido van Rossuma7925f11994-01-26 10:20:16 +0000882
883is inserted at the end.
884
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000885Caution: No more than 26 regions can be pending at any given time.
886This limit is (indirectly) inherited from libc's mktemp(3).
887`python-mode' does not try to protect you from exceeding the limit.
888It's extremely unlikely that you'll get anywhere close to the limit in
889practice, unless you're trying to be a jerk <grin>.
Guido van Rossuma7925f11994-01-26 10:20:16 +0000890
891See the `\\[py-shell]' docs for additional warnings."
892 (interactive "r")
893 (or (< start end) (error "Region is empty"))
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000894 (let ((pyproc (get-process "Python"))
895 fname)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000896 (if (null pyproc)
897 (shell-command-on-region start end py-python-command)
898 ;; else feed it thru a temp file
899 (setq fname (py-make-temp-name))
900 (write-region start end fname nil 'no-msg)
901 (setq py-file-queue (append py-file-queue (list fname)))
902 (if (cdr py-file-queue)
903 (message "File %s queued for execution" fname)
904 ;; else
905 (py-execute-file pyproc fname)))))
906
907(defun py-execute-file (pyproc fname)
908 (py-append-to-process-buffer
909 pyproc
910 (format "## working on region in file %s ...\n" fname))
911 (process-send-string pyproc (format "execfile('%s')\n" fname)))
912
913(defun py-process-filter (pyproc string)
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000914 (let ((curbuf (current-buffer))
915 (pbuf (process-buffer pyproc))
916 (pmark (process-mark pyproc))
917 file-finished)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000918
919 ;; make sure we switch to a different buffer at least once. if we
920 ;; *don't* do this, then if the process buffer is in the selected
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000921 ;; window, and point is before the end, and lots of output is
922 ;; coming at a fast pace, then (a) simple cursor-movement commands
923 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
924 ;; to have a visible effect (the window just doesn't get updated,
925 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
926 ;; get all the process output (until the next python prompt).
Guido van Rossuma7925f11994-01-26 10:20:16 +0000927 ;;
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000928 ;; #b makes no sense to me at all. #a almost makes sense: unless
929 ;; we actually change buffers, set_buffer_internal in buffer.c
930 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
931 ;; seems to make the Emacs command loop reluctant to update the
932 ;; display. Perhaps the default process filter in process.c's
933 ;; read_process_output has update_mode_lines++ for a similar
934 ;; reason? beats me ...
935
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000936 (unwind-protect
937 ;; make sure current buffer is restored
938 ;; BAW - we want to check to see if this still applies
939 (progn
940 ;; mysterious ugly hack
941 (if (eq curbuf pbuf)
942 (set-buffer (get-buffer-create "*scratch*")))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000943
Guido van Rossuma83f3b81996-10-23 20:55:00 +0000944 (set-buffer pbuf)
945 (let* ((start (point))
946 (goback (< start pmark))
947 (goend (and (not goback) (= start (point-max))))
948 (buffer-read-only nil))
949 (goto-char pmark)
950 (insert string)
951 (move-marker pmark (point))
952 (setq file-finished
953 (and py-file-queue
954 (equal ">>> "
955 (buffer-substring
956 (prog2 (beginning-of-line) (point)
957 (goto-char pmark))
958 (point)))))
959 (if goback (goto-char start)
960 ;; else
961 (if py-scroll-process-buffer
962 (let* ((pop-up-windows t)
963 (pwin (display-buffer pbuf)))
964 (set-window-point pwin (point)))))
965 (set-buffer curbuf)
966 (if file-finished
967 (progn
968 (py-delete-file-silently (car py-file-queue))
969 (setq py-file-queue (cdr py-file-queue))
970 (if py-file-queue
971 (py-execute-file pyproc (car py-file-queue)))))
972 (and goend
973 (progn (set-buffer pbuf)
974 (goto-char (point-max))))
975 ))
976 (set-buffer curbuf))))
Guido van Rossuma7925f11994-01-26 10:20:16 +0000977
978(defun py-execute-buffer ()
979 "Send the contents of the buffer to a Python interpreter.
980If there is a *Python* process buffer it is used. If a clipping
981restriction is in effect, only the accessible portion of the buffer is
982sent. A trailing newline will be supplied if needed.
983
984See the `\\[py-execute-region]' docs for an account of some subtleties."
985 (interactive)
986 (py-execute-region (point-min) (point-max)))
987
988
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000989
990;; Functions for Python style indentation
Guido van Rossum6ba11201996-08-20 19:57:53 +0000991(defun py-delete-char (count)
Guido van Rossuma7925f11994-01-26 10:20:16 +0000992 "Reduce indentation or delete character.
993If point is at the leftmost column, deletes the preceding newline.
994
995Else if point is at the leftmost non-blank character of a line that is
996neither a continuation line nor a non-indenting comment line, or if
997point is at the end of a blank line, reduces the indentation to match
998that of the line that opened the current block of code. The line that
Guido van Rossumdeaa1051995-03-10 16:17:03 +0000999opened the block is displayed in the echo area to help you keep track
Guido van Rossum6ba11201996-08-20 19:57:53 +00001000of where you are. With numeric count, outdents that many blocks (but
1001not past column zero).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001002
1003Else the preceding character is deleted, converting a tab to spaces if
Guido van Rossum6ba11201996-08-20 19:57:53 +00001004needed so that only a single column position is deleted. Numeric
1005argument delets that many characters."
1006 (interactive "*p")
Guido van Rossuma7925f11994-01-26 10:20:16 +00001007 (if (or (/= (current-indentation) (current-column))
1008 (bolp)
1009 (py-continuation-line-p)
Guido van Rossum6ba11201996-08-20 19:57:53 +00001010 (not py-honor-comment-indentation)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001011 (looking-at "#[^ \t\n]")) ; non-indenting #
Guido van Rossum6ba11201996-08-20 19:57:53 +00001012 (backward-delete-char-untabify count)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001013 ;; else indent the same as the colon line that opened the block
1014
1015 ;; force non-blank so py-goto-block-up doesn't ignore it
1016 (insert-char ?* 1)
1017 (backward-char)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001018 (let ((base-indent 0) ; indentation of base line
1019 (base-text "") ; and text of base line
1020 (base-found-p nil))
Guido van Rossum6ba11201996-08-20 19:57:53 +00001021 (save-excursion
1022 (while (< 0 count)
1023 (condition-case nil ; in case no enclosing block
1024 (progn
1025 (py-goto-block-up 'no-mark)
1026 (setq base-indent (current-indentation)
1027 base-text (py-suck-up-leading-text)
1028 base-found-p t))
1029 (error nil))
1030 (setq count (1- count))))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001031 (delete-char 1) ; toss the dummy character
1032 (delete-horizontal-space)
1033 (indent-to base-indent)
1034 (if base-found-p
1035 (message "Closes block: %s" base-text)))))
1036
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001037;; required for pending-del and delsel modes
1038(put 'py-delete-char 'delete-selection 'supersede)
1039(put 'py-delete-char 'pending-delete 'supersede)
1040
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001041(defun py-indent-line (&optional arg)
1042 "Fix the indentation of the current line according to Python rules.
1043With \\[universal-argument], ignore outdenting rules for block
1044closing statements (e.g. return, raise, break, continue, pass)
1045
1046This function is normally bound to `indent-line-function' so
1047\\[indent-for-tab-command] will call it."
1048 (interactive "P")
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001049 (let* ((ci (current-indentation))
1050 (move-to-indentation-p (<= (current-column) ci))
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001051 (need (py-compute-indentation (not arg))))
Guido van Rossum1c1fbf81995-03-14 21:33:10 +00001052 ;; see if we need to outdent
Guido van Rossumd97cc371995-03-15 19:55:55 +00001053 (if (py-outdent-p)
Guido van Rossum1d5645d1995-03-14 21:31:47 +00001054 (setq need (- need py-indent-offset)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001055 (if (/= ci need)
1056 (save-excursion
1057 (beginning-of-line)
1058 (delete-horizontal-space)
1059 (indent-to need)))
1060 (if move-to-indentation-p (back-to-indentation))))
1061
1062(defun py-newline-and-indent ()
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001063 "Strives to act like the Emacs `newline-and-indent'.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001064This is just `strives to' because correct indentation can't be computed
1065from scratch for Python code. In general, deletes the whitespace before
1066point, inserts a newline, and takes an educated guess as to how you want
1067the new line indented."
1068 (interactive)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001069 (let ((ci (current-indentation)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001070 (if (< ci (current-column)) ; if point beyond indentation
1071 (newline-and-indent)
1072 ;; else try to act like newline-and-indent "normally" acts
1073 (beginning-of-line)
1074 (insert-char ?\n 1)
1075 (move-to-column ci))))
1076
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001077(defun py-compute-indentation (honor-block-close-p)
1078 ;; implements all the rules for indentation computation. when
1079 ;; honor-block-close-p is non-nil, statements such as return, raise,
1080 ;; break, continue, and pass force one level of outdenting.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001081 (save-excursion
Guido van Rossum503b2e81995-10-08 00:44:23 +00001082 (let ((pps (parse-partial-sexp (save-excursion
1083 (beginning-of-python-def-or-class)
1084 (point))
1085 (point))))
1086 (beginning-of-line)
1087 (cond
1088 ;; are we inside a string or comment?
1089 ((or (nth 3 pps) (nth 4 pps))
1090 (save-excursion
1091 (if (not py-align-multiline-strings-p) 0
1092 ;; skip back over blank & non-indenting comment lines
1093 ;; note: will skip a blank or non-indenting comment line
1094 ;; that happens to be a continuation line too
1095 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001096 (back-to-indentation)
Guido van Rossum503b2e81995-10-08 00:44:23 +00001097 (current-column))))
1098 ;; are we on a continuation line?
1099 ((py-continuation-line-p)
1100 (let ((startpos (point))
1101 (open-bracket-pos (py-nesting-level))
Guido van Rossum6ba11201996-08-20 19:57:53 +00001102 endpos searching found state)
Guido van Rossum503b2e81995-10-08 00:44:23 +00001103 (if open-bracket-pos
1104 (progn
1105 ;; align with first item in list; else a normal
1106 ;; indent beyond the line with the open bracket
1107 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1108 ;; is the first list item on the same line?
1109 (skip-chars-forward " \t")
1110 (if (null (memq (following-char) '(?\n ?# ?\\)))
1111 ; yes, so line up with it
1112 (current-column)
1113 ;; first list item on another line, or doesn't exist yet
1114 (forward-line 1)
1115 (while (and (< (point) startpos)
1116 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1117 (forward-line 1))
1118 (if (< (point) startpos)
1119 ;; again mimic the first list item
1120 (current-indentation)
1121 ;; else they're about to enter the first item
1122 (goto-char open-bracket-pos)
1123 (+ (current-indentation) py-indent-offset))))
Guido van Rossume531e4b1994-04-16 08:29:27 +00001124
Guido van Rossum503b2e81995-10-08 00:44:23 +00001125 ;; else on backslash continuation line
1126 (forward-line -1)
1127 (if (py-continuation-line-p) ; on at least 3rd line in block
1128 (current-indentation) ; so just continue the pattern
1129 ;; else started on 2nd line in block, so indent more.
1130 ;; if base line is an assignment with a start on a RHS,
1131 ;; indent to 2 beyond the leftmost "="; else skip first
1132 ;; chunk of non-whitespace characters on base line, + 1 more
1133 ;; column
1134 (end-of-line)
1135 (setq endpos (point) searching t)
1136 (back-to-indentation)
1137 (setq startpos (point))
1138 ;; look at all "=" from left to right, stopping at first
1139 ;; one not nested in a list or string
1140 (while searching
1141 (skip-chars-forward "^=" endpos)
1142 (if (= (point) endpos)
1143 (setq searching nil)
1144 (forward-char 1)
1145 (setq state (parse-partial-sexp startpos (point)))
1146 (if (and (zerop (car state)) ; not in a bracket
1147 (null (nth 3 state))) ; & not in a string
1148 (progn
1149 (setq searching nil) ; done searching in any case
1150 (setq found
1151 (not (or
1152 (eq (following-char) ?=)
1153 (memq (char-after (- (point) 2))
1154 '(?< ?> ?!)))))))))
1155 (if (or (not found) ; not an assignment
1156 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1157 (progn
1158 (goto-char startpos)
1159 (skip-chars-forward "^ \t\n")))
1160 (1+ (current-column))))))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001161
Guido van Rossum503b2e81995-10-08 00:44:23 +00001162 ;; not on a continuation line
Guido van Rossum6ba11201996-08-20 19:57:53 +00001163 ((bobp) (current-indentation))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001164
Guido van Rossum6ba11201996-08-20 19:57:53 +00001165 ;; Dfn: "Indenting comment line". A line containing only a
1166 ;; comment, but which is treated like a statement for
1167 ;; indentation calculation purposes. Such lines are only
1168 ;; treated specially by the mode; they are not treated
1169 ;; specially by the Python interpreter.
1170
1171 ;; The rules for indenting comment lines are a line where:
1172 ;; - the first non-whitespace character is `#', and
1173 ;; - the character following the `#' is whitespace, and
1174 ;; - the line is outdented with respect to (i.e. to the left
1175 ;; of) the indentation of the preceding non-blank line.
1176
1177 ;; The first non-blank line following an indenting comment
1178 ;; line is given the same amount of indentation as the
1179 ;; indenting comment line.
1180
1181 ;; All other comment-only lines are ignored for indentation
1182 ;; purposes.
1183
1184 ;; Are we looking at a comment-only line which is *not* an
1185 ;; indenting comment line? If so, we assume that its been
1186 ;; placed at the desired indentation, so leave it alone.
1187 ;; Indenting comment lines are aligned as statements down
1188 ;; below.
1189 ((and (looking-at "[ \t]*#[^ \t\n]")
1190 ;; NOTE: this test will not be performed in older Emacsen
1191 (fboundp 'forward-comment)
1192 (<= (current-indentation)
1193 (save-excursion
1194 (forward-comment (- (point-max)))
1195 (current-indentation))))
Guido van Rossum503b2e81995-10-08 00:44:23 +00001196 (current-indentation))
1197
1198 ;; else indentation based on that of the statement that
1199 ;; precedes us; use the first line of that statement to
1200 ;; establish the base, in case the user forced a non-std
1201 ;; indentation for the continuation lines (if any)
1202 (t
1203 ;; skip back over blank & non-indenting comment lines note:
1204 ;; will skip a blank or non-indenting comment line that
Guido van Rossum6ba11201996-08-20 19:57:53 +00001205 ;; happens to be a continuation line too. use fast Emacs 19
1206 ;; function if it's there.
1207 (if (and (eq py-honor-comment-indentation nil)
1208 (fboundp 'forward-comment))
1209 (forward-comment (- (point-max)))
1210 (let (done)
1211 (while (not done)
1212 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1213 nil 'move)
1214 (setq done (or (eq py-honor-comment-indentation t)
1215 (bobp)
1216 (/= (following-char) ?#)
1217 (not (zerop (current-column)))))
1218 )))
Guido van Rossum503b2e81995-10-08 00:44:23 +00001219 ;; if we landed inside a string, go to the beginning of that
1220 ;; string. this handles triple quoted, multi-line spanning
1221 ;; strings.
1222 (py-goto-initial-line)
Guido van Rossum6ba11201996-08-20 19:57:53 +00001223 (+ (current-indentation)
1224 (if (py-statement-opens-block-p)
1225 py-indent-offset
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001226 (if (and honor-block-close-p (py-statement-closes-block-p))
Guido van Rossum6ba11201996-08-20 19:57:53 +00001227 (- py-indent-offset)
1228 0)))
1229 )))))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001230
1231(defun py-guess-indent-offset (&optional global)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001232 "Guess a good value for, and change, `py-indent-offset'.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001233By default (without a prefix arg), makes a buffer-local copy of
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001234`py-indent-offset' with the new value. This will not affect any other
Guido van Rossuma7925f11994-01-26 10:20:16 +00001235Python buffers. With a prefix arg, changes the global value of
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001236`py-indent-offset'. This affects all Python buffers (that don't have
Guido van Rossuma7925f11994-01-26 10:20:16 +00001237their own buffer-local copy), both those currently existing and those
1238created later in the Emacs session.
1239
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001240Some people use a different value for `py-indent-offset' than you use.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001241There's no excuse for such foolishness, but sometimes you have to deal
1242with their ugly code anyway. This function examines the file and sets
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001243`py-indent-offset' to what it thinks it was when they created the
1244mess.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001245
1246Specifically, it searches forward from the statement containing point,
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001247looking for a line that opens a block of code. `py-indent-offset' is
1248set to the difference in indentation between that line and the Python
Guido van Rossuma7925f11994-01-26 10:20:16 +00001249statement following it. If the search doesn't succeed going forward,
1250it's tried again going backward."
1251 (interactive "P") ; raw prefix arg
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001252 (let (new-value
1253 (start (point))
1254 restart
1255 (found nil)
1256 colon-indent)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001257 (py-goto-initial-line)
1258 (while (not (or found (eobp)))
1259 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1260 (progn
1261 (setq restart (point))
1262 (py-goto-initial-line)
1263 (if (py-statement-opens-block-p)
1264 (setq found t)
1265 (goto-char restart)))))
1266 (if found
1267 ()
1268 (goto-char start)
1269 (py-goto-initial-line)
1270 (while (not (or found (bobp)))
1271 (setq found
1272 (and
1273 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1274 (or (py-goto-initial-line) t) ; always true -- side effect
1275 (py-statement-opens-block-p)))))
1276 (setq colon-indent (current-indentation)
1277 found (and found (zerop (py-next-statement 1)))
1278 new-value (- (current-indentation) colon-indent))
1279 (goto-char start)
1280 (if found
1281 (progn
1282 (funcall (if global 'kill-local-variable 'make-local-variable)
1283 'py-indent-offset)
1284 (setq py-indent-offset new-value)
1285 (message "%s value of py-indent-offset set to %d"
1286 (if global "Global" "Local")
1287 py-indent-offset))
1288 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1289
1290(defun py-shift-region (start end count)
1291 (save-excursion
1292 (goto-char end) (beginning-of-line) (setq end (point))
1293 (goto-char start) (beginning-of-line) (setq start (point))
1294 (indent-rigidly start end count)))
1295
1296(defun py-shift-region-left (start end &optional count)
1297 "Shift region of Python code to the left.
1298The lines from the line containing the start of the current region up
1299to (but not including) the line containing the end of the region are
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001300shifted to the left, by `py-indent-offset' columns.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001301
1302If a prefix argument is given, the region is instead shifted by that
Guido van Rossum6ba11201996-08-20 19:57:53 +00001303many columns. With no active region, outdent only the current line.
1304You cannot outdent the region if any line is already at column zero."
1305 (interactive
1306 (let ((p (point))
1307 (m (mark))
1308 (arg current-prefix-arg))
1309 (if m
1310 (list (min p m) (max p m) arg)
1311 (list p (save-excursion (forward-line 1) (point)) arg))))
1312 ;; if any line is at column zero, don't shift the region
1313 (save-excursion
1314 (goto-char start)
1315 (while (< (point) end)
1316 (back-to-indentation)
1317 (if (and (zerop (current-column))
1318 (not (looking-at "\\s *$")))
1319 (error "Region is at left edge."))
1320 (forward-line 1)))
1321 (py-shift-region start end (- (prefix-numeric-value
1322 (or count py-indent-offset))))
1323 (py-keep-region-active))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001324
1325(defun py-shift-region-right (start end &optional count)
1326 "Shift region of Python code to the right.
1327The lines from the line containing the start of the current region up
1328to (but not including) the line containing the end of the region are
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001329shifted to the right, by `py-indent-offset' columns.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001330
1331If a prefix argument is given, the region is instead shifted by that
Guido van Rossum6ba11201996-08-20 19:57:53 +00001332many columns. With no active region, indent only the current line."
1333 (interactive
1334 (let ((p (point))
1335 (m (mark))
1336 (arg current-prefix-arg))
1337 (if m
1338 (list (min p m) (max p m) arg)
1339 (list p (save-excursion (forward-line 1) (point)) arg))))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001340 (py-shift-region start end (prefix-numeric-value
Guido van Rossum6ba11201996-08-20 19:57:53 +00001341 (or count py-indent-offset)))
1342 (py-keep-region-active))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001343
1344(defun py-indent-region (start end &optional indent-offset)
1345 "Reindent a region of Python code.
Guido van Rossum6ba11201996-08-20 19:57:53 +00001346
Guido van Rossuma7925f11994-01-26 10:20:16 +00001347The lines from the line containing the start of the current region up
1348to (but not including) the line containing the end of the region are
1349reindented. If the first line of the region has a non-whitespace
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001350character in the first column, the first line is left alone and the
1351rest of the region is reindented with respect to it. Else the entire
Guido van Rossum6ba11201996-08-20 19:57:53 +00001352region is reindented with respect to the (closest code or indenting
1353comment) statement immediately preceding the region.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001354
1355This is useful when code blocks are moved or yanked, when enclosing
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001356control structures are introduced or removed, or to reformat code
1357using a new value for the indentation offset.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001358
1359If a numeric prefix argument is given, it will be used as the value of
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001360the indentation offset. Else the value of `py-indent-offset' will be
Guido van Rossuma7925f11994-01-26 10:20:16 +00001361used.
1362
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001363Warning: The region must be consistently indented before this function
Guido van Rossuma7925f11994-01-26 10:20:16 +00001364is called! This function does not compute proper indentation from
1365scratch (that's impossible in Python), it merely adjusts the existing
1366indentation to be correct in context.
1367
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001368Warning: This function really has no idea what to do with
1369non-indenting comment lines, and shifts them as if they were indenting
1370comment lines. Fixing this appears to require telepathy.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001371
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001372Special cases: whitespace is deleted from blank lines; continuation
1373lines are shifted by the same amount their initial line was shifted,
1374in order to preserve their relative indentation with respect to their
Guido van Rossuma7925f11994-01-26 10:20:16 +00001375initial line; and comment lines beginning in column 1 are ignored."
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001376 (interactive "*r\nP") ; region; raw prefix arg
Guido van Rossuma7925f11994-01-26 10:20:16 +00001377 (save-excursion
1378 (goto-char end) (beginning-of-line) (setq end (point-marker))
1379 (goto-char start) (beginning-of-line)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001380 (let ((py-indent-offset (prefix-numeric-value
1381 (or indent-offset py-indent-offset)))
1382 (indents '(-1)) ; stack of active indent levels
1383 (target-column 0) ; column to which to indent
1384 (base-shifted-by 0) ; amount last base line was shifted
1385 (indent-base (if (looking-at "[ \t\n]")
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001386 (py-compute-indentation t)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001387 0))
1388 ci)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001389 (while (< (point) end)
1390 (setq ci (current-indentation))
1391 ;; figure out appropriate target column
1392 (cond
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001393 ((or (eq (following-char) ?#) ; comment in column 1
1394 (looking-at "[ \t]*$")) ; entirely blank
1395 (setq target-column 0))
1396 ((py-continuation-line-p) ; shift relative to base line
1397 (setq target-column (+ ci base-shifted-by)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001398 (t ; new base line
1399 (if (> ci (car indents)) ; going deeper; push it
1400 (setq indents (cons ci indents))
1401 ;; else we should have seen this indent before
1402 (setq indents (memq ci indents)) ; pop deeper indents
1403 (if (null indents)
1404 (error "Bad indentation in region, at line %d"
1405 (save-restriction
1406 (widen)
1407 (1+ (count-lines 1 (point)))))))
1408 (setq target-column (+ indent-base
1409 (* py-indent-offset
1410 (- (length indents) 2))))
1411 (setq base-shifted-by (- target-column ci))))
1412 ;; shift as needed
1413 (if (/= ci target-column)
1414 (progn
1415 (delete-horizontal-space)
1416 (indent-to target-column)))
1417 (forward-line 1))))
1418 (set-marker end nil))
1419
Guido van Rossum6ba11201996-08-20 19:57:53 +00001420(defun py-comment-region (beg end &optional arg)
1421 "Like `comment-region' but uses double hash (`#') comment starter."
1422 (interactive "r\nP")
1423 (let ((comment-start py-block-comment-prefix))
1424 (comment-region beg end arg)))
1425
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001426
1427;; Functions for moving point
Guido van Rossuma7925f11994-01-26 10:20:16 +00001428(defun py-previous-statement (count)
1429 "Go to the start of previous Python statement.
1430If the statement at point is the i'th Python statement, goes to the
1431start of statement i-COUNT. If there is no such statement, goes to the
1432first statement. Returns count of statements left to move.
1433`Statements' do not include blank, comment, or continuation lines."
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001434 (interactive "p") ; numeric prefix arg
Guido van Rossuma7925f11994-01-26 10:20:16 +00001435 (if (< count 0) (py-next-statement (- count))
1436 (py-goto-initial-line)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001437 (let (start)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001438 (while (and
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001439 (setq start (point)) ; always true -- side effect
Guido van Rossuma7925f11994-01-26 10:20:16 +00001440 (> count 0)
1441 (zerop (forward-line -1))
1442 (py-goto-statement-at-or-above))
1443 (setq count (1- count)))
1444 (if (> count 0) (goto-char start)))
1445 count))
1446
1447(defun py-next-statement (count)
1448 "Go to the start of next Python statement.
1449If the statement at point is the i'th Python statement, goes to the
1450start of statement i+COUNT. If there is no such statement, goes to the
1451last statement. Returns count of statements left to move. `Statements'
1452do not include blank, comment, or continuation lines."
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001453 (interactive "p") ; numeric prefix arg
Guido van Rossuma7925f11994-01-26 10:20:16 +00001454 (if (< count 0) (py-previous-statement (- count))
1455 (beginning-of-line)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001456 (let (start)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001457 (while (and
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001458 (setq start (point)) ; always true -- side effect
Guido van Rossuma7925f11994-01-26 10:20:16 +00001459 (> count 0)
1460 (py-goto-statement-below))
1461 (setq count (1- count)))
1462 (if (> count 0) (goto-char start)))
1463 count))
1464
1465(defun py-goto-block-up (&optional nomark)
1466 "Move up to start of current block.
1467Go to the statement that starts the smallest enclosing block; roughly
1468speaking, this will be the closest preceding statement that ends with a
1469colon and is indented less than the statement you started on. If
1470successful, also sets the mark to the starting point.
1471
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001472`\\[py-mark-block]' can be used afterward to mark the whole code
1473block, if desired.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001474
1475If called from a program, the mark will not be set if optional argument
1476NOMARK is not nil."
1477 (interactive)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001478 (let ((start (point))
1479 (found nil)
1480 initial-indent)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001481 (py-goto-initial-line)
1482 ;; if on blank or non-indenting comment line, use the preceding stmt
1483 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1484 (progn
1485 (py-goto-statement-at-or-above)
1486 (setq found (py-statement-opens-block-p))))
1487 ;; search back for colon line indented less
1488 (setq initial-indent (current-indentation))
1489 (if (zerop initial-indent)
1490 ;; force fast exit
1491 (goto-char (point-min)))
1492 (while (not (or found (bobp)))
1493 (setq found
1494 (and
1495 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1496 (or (py-goto-initial-line) t) ; always true -- side effect
1497 (< (current-indentation) initial-indent)
1498 (py-statement-opens-block-p))))
1499 (if found
1500 (progn
1501 (or nomark (push-mark start))
1502 (back-to-indentation))
1503 (goto-char start)
1504 (error "Enclosing block not found"))))
1505
1506(defun beginning-of-python-def-or-class (&optional class)
1507 "Move point to start of def (or class, with prefix arg).
1508
1509Searches back for the closest preceding `def'. If you supply a prefix
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001510arg, looks for a `class' instead. The docs assume the `def' case;
1511just substitute `class' for `def' for the other case.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001512
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001513If point is in a def statement already, and after the `d', simply
1514moves point to the start of the statement.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001515
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001516Else (point is not in a def statement, or at or before the `d' of a
1517def statement), searches for the closest preceding def statement, and
1518leaves point at its start. If no such statement can be found, leaves
1519point at the start of the buffer.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001520
1521Returns t iff a def statement is found by these rules.
1522
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001523Note that doing this command repeatedly will take you closer to the
1524start of the buffer each time.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001525
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001526If you want to mark the current def/class, see
1527`\\[mark-python-def-or-class]'."
Guido van Rossuma7925f11994-01-26 10:20:16 +00001528 (interactive "P") ; raw prefix arg
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001529 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1530 (start-of-line (progn (beginning-of-line) (point)))
1531 (start-of-stmt (progn (py-goto-initial-line) (point))))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001532 (if (or (/= start-of-stmt start-of-line)
1533 (not at-or-before-p))
1534 (end-of-line)) ; OK to match on this line
1535 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001536 nil 'move)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001537
1538(defun end-of-python-def-or-class (&optional class)
1539 "Move point beyond end of def (or class, with prefix arg) body.
1540
1541By default, looks for an appropriate `def'. If you supply a prefix arg,
1542looks for a `class' instead. The docs assume the `def' case; just
1543substitute `class' for `def' for the other case.
1544
1545If point is in a def statement already, this is the def we use.
1546
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001547Else if the def found by `\\[beginning-of-python-def-or-class]'
1548contains the statement you started on, that's the def we use.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001549
1550Else we search forward for the closest following def, and use that.
1551
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001552If a def can be found by these rules, point is moved to the start of
1553the line immediately following the def block, and the position of the
1554start of the def is returned.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001555
1556Else point is moved to the end of the buffer, and nil is returned.
1557
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001558Note that doing this command repeatedly will take you closer to the
1559end of the buffer each time.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001560
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001561If you want to mark the current def/class, see
1562`\\[mark-python-def-or-class]'."
Guido van Rossuma7925f11994-01-26 10:20:16 +00001563 (interactive "P") ; raw prefix arg
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001564 (let ((start (progn (py-goto-initial-line) (point)))
1565 (which (if class "class" "def"))
1566 (state 'not-found))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001567 ;; move point to start of appropriate def/class
1568 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1569 (setq state 'at-beginning)
1570 ;; else see if beginning-of-python-def-or-class hits container
1571 (if (and (beginning-of-python-def-or-class class)
1572 (progn (py-goto-beyond-block)
1573 (> (point) start)))
1574 (setq state 'at-end)
1575 ;; else search forward
1576 (goto-char start)
1577 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1578 (progn (setq state 'at-beginning)
1579 (beginning-of-line)))))
1580 (cond
1581 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1582 ((eq state 'at-end) t)
1583 ((eq state 'not-found) nil)
1584 (t (error "internal error in end-of-python-def-or-class")))))
1585
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001586
1587;; Functions for marking regions
Guido van Rossuma7925f11994-01-26 10:20:16 +00001588(defun py-mark-block (&optional extend just-move)
1589 "Mark following block of lines. With prefix arg, mark structure.
1590Easier to use than explain. It sets the region to an `interesting'
1591block of succeeding lines. If point is on a blank line, it goes down to
1592the next non-blank line. That will be the start of the region. The end
1593of the region depends on the kind of line at the start:
1594
1595 - If a comment, the region will include all succeeding comment lines up
1596 to (but not including) the next non-comment line (if any).
1597
1598 - Else if a prefix arg is given, and the line begins one of these
1599 structures:
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001600
1601 if elif else try except finally for while def class
1602
Guido van Rossuma7925f11994-01-26 10:20:16 +00001603 the region will be set to the body of the structure, including
1604 following blocks that `belong' to it, but excluding trailing blank
1605 and comment lines. E.g., if on a `try' statement, the `try' block
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001606 and all (if any) of the following `except' and `finally' blocks
1607 that belong to the `try' structure will be in the region. Ditto
1608 for if/elif/else, for/else and while/else structures, and (a bit
1609 degenerate, since they're always one-block structures) def and
1610 class blocks.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001611
1612 - Else if no prefix argument is given, and the line begins a Python
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001613 block (see list above), and the block is not a `one-liner' (i.e.,
1614 the statement ends with a colon, not with code), the region will
1615 include all succeeding lines up to (but not including) the next
1616 code statement (if any) that's indented no more than the starting
1617 line, except that trailing blank and comment lines are excluded.
1618 E.g., if the starting line begins a multi-statement `def'
1619 structure, the region will be set to the full function definition,
1620 but without any trailing `noise' lines.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001621
1622 - Else the region will include all succeeding lines up to (but not
1623 including) the next blank line, or code or indenting-comment line
1624 indented strictly less than the starting line. Trailing indenting
1625 comment lines are included in this case, but not trailing blank
1626 lines.
1627
1628A msg identifying the location of the mark is displayed in the echo
1629area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1630
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001631If called from a program, optional argument EXTEND plays the role of
1632the prefix arg, and if optional argument JUST-MOVE is not nil, just
1633moves to the end of the block (& does not set mark or display a msg)."
Guido van Rossuma7925f11994-01-26 10:20:16 +00001634 (interactive "P") ; raw prefix arg
1635 (py-goto-initial-line)
1636 ;; skip over blank lines
1637 (while (and
1638 (looking-at "[ \t]*$") ; while blank line
1639 (not (eobp))) ; & somewhere to go
1640 (forward-line 1))
1641 (if (eobp)
1642 (error "Hit end of buffer without finding a non-blank stmt"))
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001643 (let ((initial-pos (point))
1644 (initial-indent (current-indentation))
1645 last-pos ; position of last stmt in region
1646 (followers
1647 '((if elif else) (elif elif else) (else)
1648 (try except finally) (except except) (finally)
1649 (for else) (while else)
1650 (def) (class) ) )
1651 first-symbol next-symbol)
Guido van Rossuma7925f11994-01-26 10:20:16 +00001652
1653 (cond
1654 ;; if comment line, suck up the following comment lines
1655 ((looking-at "[ \t]*#")
1656 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1657 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1658 (setq last-pos (point)))
1659
1660 ;; else if line is a block line and EXTEND given, suck up
1661 ;; the whole structure
1662 ((and extend
1663 (setq first-symbol (py-suck-up-first-keyword) )
1664 (assq first-symbol followers))
1665 (while (and
1666 (or (py-goto-beyond-block) t) ; side effect
1667 (forward-line -1) ; side effect
1668 (setq last-pos (point)) ; side effect
1669 (py-goto-statement-below)
1670 (= (current-indentation) initial-indent)
1671 (setq next-symbol (py-suck-up-first-keyword))
1672 (memq next-symbol (cdr (assq first-symbol followers))))
1673 (setq first-symbol next-symbol)))
1674
1675 ;; else if line *opens* a block, search for next stmt indented <=
1676 ((py-statement-opens-block-p)
1677 (while (and
1678 (setq last-pos (point)) ; always true -- side effect
1679 (py-goto-statement-below)
1680 (> (current-indentation) initial-indent))
1681 nil))
1682
1683 ;; else plain code line; stop at next blank line, or stmt or
1684 ;; indenting comment line indented <
1685 (t
1686 (while (and
1687 (setq last-pos (point)) ; always true -- side effect
1688 (or (py-goto-beyond-final-line) t)
1689 (not (looking-at "[ \t]*$")) ; stop at blank line
1690 (or
1691 (>= (current-indentation) initial-indent)
1692 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1693 nil)))
1694
1695 ;; skip to end of last stmt
1696 (goto-char last-pos)
1697 (py-goto-beyond-final-line)
1698
1699 ;; set mark & display
1700 (if just-move
1701 () ; just return
1702 (push-mark (point) 'no-msg)
1703 (forward-line -1)
1704 (message "Mark set after: %s" (py-suck-up-leading-text))
1705 (goto-char initial-pos))))
1706
1707(defun mark-python-def-or-class (&optional class)
1708 "Set region to body of def (or class, with prefix arg) enclosing point.
1709Pushes the current mark, then point, on the mark ring (all language
1710modes do this, but although it's handy it's never documented ...).
1711
1712In most Emacs language modes, this function bears at least a
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001713hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1714`\\[beginning-of-python-def-or-class]'.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001715
1716And in earlier versions of Python mode, all 3 were tightly connected.
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001717Turned out that was more confusing than useful: the `goto start' and
1718`goto end' commands are usually used to search through a file, and
1719people expect them to act a lot like `search backward' and `search
1720forward' string-search commands. But because Python `def' and `class'
1721can nest to arbitrary levels, finding the smallest def containing
1722point cannot be done via a simple backward search: the def containing
1723point may not be the closest preceding def, or even the closest
1724preceding def that's indented less. The fancy algorithm required is
1725appropriate for the usual uses of this `mark' command, but not for the
1726`goto' variations.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001727
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001728So the def marked by this command may not be the one either of the
1729`goto' commands find: If point is on a blank or non-indenting comment
1730line, moves back to start of the closest preceding code statement or
1731indenting comment line. If this is a `def' statement, that's the def
1732we use. Else searches for the smallest enclosing `def' block and uses
1733that. Else signals an error.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001734
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001735When an enclosing def is found: The mark is left immediately beyond
1736the last line of the def block. Point is left at the start of the
1737def, except that: if the def is preceded by a number of comment lines
1738followed by (at most) one optional blank line, point is left at the
1739start of the comments; else if the def is preceded by a blank line,
1740point is left at its start.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001741
1742The intent is to mark the containing def/class and its associated
1743documentation, to make moving and duplicating functions and classes
1744pleasant."
1745 (interactive "P") ; raw prefix arg
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001746 (let ((start (point))
1747 (which (if class "class" "def")))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001748 (push-mark start)
1749 (if (not (py-go-up-tree-to-keyword which))
1750 (progn (goto-char start)
1751 (error "Enclosing %s not found" which))
1752 ;; else enclosing def/class found
1753 (setq start (point))
1754 (py-goto-beyond-block)
1755 (push-mark (point))
1756 (goto-char start)
1757 (if (zerop (forward-line -1)) ; if there is a preceding line
1758 (progn
1759 (if (looking-at "[ \t]*$") ; it's blank
1760 (setq start (point)) ; so reset start point
1761 (goto-char start)) ; else try again
1762 (if (zerop (forward-line -1))
1763 (if (looking-at "[ \t]*#") ; a comment
1764 ;; look back for non-comment line
1765 ;; tricky: note that the regexp matches a blank
1766 ;; line, cuz \n is in the 2nd character class
1767 (and
1768 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1769 (forward-line 1))
1770 ;; no comment, so go back
1771 (goto-char start))))))))
1772
Guido van Rossum6ba11201996-08-20 19:57:53 +00001773;; ripped from cc-mode
1774(defun py-forward-into-nomenclature (&optional arg)
1775 "Move forward to end of a nomenclature section or word.
1776With arg, to it arg times.
1777
1778A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1779 (interactive "p")
1780 (let ((case-fold-search nil))
1781 (if (> arg 0)
1782 (re-search-forward
1783 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1784 (point-max) t arg)
1785 (while (and (< arg 0)
1786 (re-search-backward
1787 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
1788 (point-min) 0))
1789 (forward-char 1)
1790 (setq arg (1+ arg)))))
1791 (py-keep-region-active))
1792
1793(defun py-backward-into-nomenclature (&optional arg)
1794 "Move backward to beginning of a nomenclature section or word.
1795With optional ARG, move that many times. If ARG is negative, move
1796forward.
1797
1798A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1799 (interactive "p")
1800 (py-forward-into-nomenclature (- arg))
1801 (py-keep-region-active))
1802
Guido van Rossuma7925f11994-01-26 10:20:16 +00001803
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001804
1805;; Documentation functions
Guido van Rossuma7925f11994-01-26 10:20:16 +00001806
1807;; dump the long form of the mode blurb; does the usual doc escapes,
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001808;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1809;; out of the right places, along with the keys they're on & current
1810;; values
Guido van Rossuma7925f11994-01-26 10:20:16 +00001811(defun py-dump-help-string (str)
1812 (with-output-to-temp-buffer "*Help*"
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001813 (let ((locals (buffer-local-variables))
1814 funckind funcname func funcdoc
1815 (start 0) mstart end
1816 keys )
Guido van Rossuma7925f11994-01-26 10:20:16 +00001817 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1818 (setq mstart (match-beginning 0) end (match-end 0)
1819 funckind (substring str (match-beginning 1) (match-end 1))
1820 funcname (substring str (match-beginning 2) (match-end 2))
1821 func (intern funcname))
1822 (princ (substitute-command-keys (substring str start mstart)))
1823 (cond
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001824 ((equal funckind "c") ; command
1825 (setq funcdoc (documentation func)
1826 keys (concat
1827 "Key(s): "
1828 (mapconcat 'key-description
1829 (where-is-internal func py-mode-map)
1830 ", "))))
1831 ((equal funckind "v") ; variable
Guido van Rossuma83f3b81996-10-23 20:55:00 +00001832 (setq funcdoc (documentation-property func 'variable-documentation)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001833 keys (if (assq func locals)
1834 (concat
1835 "Local/Global values: "
1836 (prin1-to-string (symbol-value func))
1837 " / "
1838 (prin1-to-string (default-value func)))
1839 (concat
1840 "Value: "
1841 (prin1-to-string (symbol-value func))))))
1842 (t ; unexpected
1843 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00001844 (princ (format "\n-> %s:\t%s\t%s\n\n"
1845 (if (equal funckind "c") "Command" "Variable")
1846 funcname keys))
1847 (princ funcdoc)
1848 (terpri)
1849 (setq start end))
1850 (princ (substitute-command-keys (substring str start))))
1851 (print-help-return-message)))
1852
1853(defun py-describe-mode ()
1854 "Dump long form of Python-mode docs."
1855 (interactive)
1856 (py-dump-help-string "Major mode for editing Python files.
1857Knows about Python indentation, tokens, comments and continuation lines.
1858Paragraphs are separated by blank lines only.
1859
1860Major sections below begin with the string `@'; specific function and
1861variable docs begin with `->'.
1862
1863@EXECUTING PYTHON CODE
1864
1865\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1866\\[py-execute-region]\tsends the current region
1867\\[py-shell]\tstarts a Python interpreter window; this will be used by
1868\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1869%c:py-execute-buffer
1870%c:py-execute-region
1871%c:py-shell
1872
1873@VARIABLES
1874
1875py-indent-offset\tindentation increment
Guido van Rossum6ba11201996-08-20 19:57:53 +00001876py-block-comment-prefix\tcomment string used by comment-region
Guido van Rossuma7925f11994-01-26 10:20:16 +00001877
1878py-python-command\tshell command to invoke Python interpreter
1879py-scroll-process-buffer\talways scroll Python process buffer
1880py-temp-directory\tdirectory used for temp files (if needed)
1881
1882py-beep-if-tab-change\tring the bell if tab-width is changed
1883%v:py-indent-offset
Guido van Rossuma7925f11994-01-26 10:20:16 +00001884%v:py-block-comment-prefix
1885%v:py-python-command
1886%v:py-scroll-process-buffer
1887%v:py-temp-directory
1888%v:py-beep-if-tab-change
1889
1890@KINDS OF LINES
1891
1892Each physical line in the file is either a `continuation line' (the
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001893preceding line ends with a backslash that's not part of a comment, or
1894the paren/bracket/brace nesting level at the start of the line is
1895non-zero, or both) or an `initial line' (everything else).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001896
1897An initial line is in turn a `blank line' (contains nothing except
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001898possibly blanks or tabs), a `comment line' (leftmost non-blank
1899character is `#'), or a `code line' (everything else).
Guido van Rossuma7925f11994-01-26 10:20:16 +00001900
1901Comment Lines
1902
1903Although all comment lines are treated alike by Python, Python mode
1904recognizes two kinds that act differently with respect to indentation.
1905
1906An `indenting comment line' is a comment line with a blank, tab or
1907nothing after the initial `#'. The indentation commands (see below)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001908treat these exactly as if they were code lines: a line following an
Guido van Rossuma7925f11994-01-26 10:20:16 +00001909indenting comment line will be indented like the comment line. All
1910other comment lines (those with a non-whitespace character immediately
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001911following the initial `#') are `non-indenting comment lines', and
1912their indentation is ignored by the indentation commands.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001913
1914Indenting comment lines are by far the usual case, and should be used
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001915whenever possible. Non-indenting comment lines are useful in cases
1916like these:
Guido van Rossuma7925f11994-01-26 10:20:16 +00001917
1918\ta = b # a very wordy single-line comment that ends up being
1919\t #... continued onto another line
1920
1921\tif a == b:
1922##\t\tprint 'panic!' # old code we've `commented out'
1923\t\treturn a
1924
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001925Since the `#...' and `##' comment lines have a non-whitespace
1926character following the initial `#', Python mode ignores them when
1927computing the proper indentation for the next line.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001928
1929Continuation Lines and Statements
1930
1931The Python-mode commands generally work on statements instead of on
1932individual lines, where a `statement' is a comment or blank line, or a
1933code line and all of its following continuation lines (if any)
1934considered as a single logical unit. The commands in this mode
1935generally (when it makes sense) automatically move to the start of the
Guido van Rossumdeaa1051995-03-10 16:17:03 +00001936statement containing point, even if point happens to be in the middle
1937of some continuation line.
Guido van Rossuma7925f11994-01-26 10:20:16 +00001938
Guido van Rossuma7925f11994-01-26 10:20:16 +00001939
1940@INDENTATION
1941
1942Primarily for entering new code:
1943\t\\[indent-for-tab-command]\t indent line appropriately
1944\t\\[py-newline-and-indent]\t insert newline, then indent
1945\t\\[py-delete-char]\t reduce indentation, or delete single character
1946
1947Primarily for reindenting existing code:
1948\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1949\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1950
1951\t\\[py-indent-region]\t reindent region to match its context
1952\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1953\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1954
1955Unlike most programming languages, Python uses indentation, and only
1956indentation, to specify block structure. Hence the indentation supplied
1957automatically by Python-mode is just an educated guess: only you know
1958the block structure you intend, so only you can supply correct
1959indentation.
1960
1961The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1962the indentation of preceding statements. E.g., assuming
1963py-indent-offset is 4, after you enter
1964\tif a > 0: \\[py-newline-and-indent]
1965the cursor will be moved to the position of the `_' (_ is not a
1966character in the file, it's just used here to indicate the location of
1967the cursor):
1968\tif a > 0:
1969\t _
1970If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1971to
1972\tif a > 0:
1973\t c = d
1974\t _
1975Python-mode cannot know whether that's what you intended, or whether
1976\tif a > 0:
1977\t c = d
1978\t_
1979was your intent. In general, Python-mode either reproduces the
1980indentation of the (closest code or indenting-comment) preceding
1981statement, or adds an extra py-indent-offset blanks if the preceding
1982statement has `:' as its last significant (non-whitespace and non-
1983comment) character. If the suggested indentation is too much, use
1984\\[py-delete-char] to reduce it.
1985
Guido van Rossum0ec5c5d1994-04-25 08:12:43 +00001986Continuation lines are given extra indentation. If you don't like the
1987suggested indentation, change it to something you do like, and Python-
1988mode will strive to indent later lines of the statement in the same way.
1989
1990If a line is a continuation line by virtue of being in an unclosed
1991paren/bracket/brace structure (`list', for short), the suggested
Guido van Rossum9274e2d1994-04-26 07:35:17 +00001992indentation depends on whether the current line contains the first item
1993in the list. If it does, it's indented py-indent-offset columns beyond
1994the indentation of the line containing the open bracket. If you don't
1995like that, change it by hand. The remaining items in the list will mimic
1996whatever indentation you give to the first item.
Guido van Rossume531e4b1994-04-16 08:29:27 +00001997
1998If a line is a continuation line because the line preceding it ends with
Guido van Rossum0ec5c5d1994-04-25 08:12:43 +00001999a backslash, the third and following lines of the statement inherit their
2000indentation from the line preceding them. The indentation of the second
2001line in the statement depends on the form of the first (base) line: if
2002the base line is an assignment statement with anything more interesting
2003than the backslash following the leftmost assigning `=', the second line
2004is indented two columns beyond that `='. Else it's indented to two
2005columns beyond the leftmost solid chunk of non-whitespace characters on
2006the base line.
Guido van Rossume531e4b1994-04-16 08:29:27 +00002007
Guido van Rossuma7925f11994-01-26 10:20:16 +00002008Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2009repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2010structure you intend.
2011%c:indent-for-tab-command
2012%c:py-newline-and-indent
2013%c:py-delete-char
2014
2015
2016The next function may be handy when editing code you didn't write:
2017%c:py-guess-indent-offset
2018
2019
2020The remaining `indent' functions apply to a region of Python code. They
2021assume the block structure (equals indentation, in Python) of the region
2022is correct, and alter the indentation in various ways while preserving
2023the block structure:
2024%c:py-indent-region
2025%c:py-shift-region-left
2026%c:py-shift-region-right
2027
2028@MARKING & MANIPULATING REGIONS OF CODE
2029
2030\\[py-mark-block]\t mark block of lines
2031\\[mark-python-def-or-class]\t mark smallest enclosing def
2032\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Guido van Rossum6ba11201996-08-20 19:57:53 +00002033\\[comment-region]\t comment out region of code
2034\\[universal-argument] \\[comment-region]\t uncomment region of code
Guido van Rossuma7925f11994-01-26 10:20:16 +00002035%c:py-mark-block
2036%c:mark-python-def-or-class
Guido van Rossum6ba11201996-08-20 19:57:53 +00002037%c:comment-region
Guido van Rossuma7925f11994-01-26 10:20:16 +00002038
2039@MOVING POINT
2040
2041\\[py-previous-statement]\t move to statement preceding point
2042\\[py-next-statement]\t move to statement following point
2043\\[py-goto-block-up]\t move up to start of current block
2044\\[beginning-of-python-def-or-class]\t move to start of def
2045\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2046\\[end-of-python-def-or-class]\t move to end of def
2047\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2048
2049The first two move to one statement beyond the statement that contains
2050point. A numeric prefix argument tells them to move that many
2051statements instead. Blank lines, comment lines, and continuation lines
2052do not count as `statements' for these commands. So, e.g., you can go
2053to the first code statement in a file by entering
2054\t\\[beginning-of-buffer]\t to move to the top of the file
2055\t\\[py-next-statement]\t to skip over initial comments and blank lines
2056Or do `\\[py-previous-statement]' with a huge prefix argument.
2057%c:py-previous-statement
2058%c:py-next-statement
2059%c:py-goto-block-up
2060%c:beginning-of-python-def-or-class
2061%c:end-of-python-def-or-class
2062
2063@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2064
2065`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2066
2067`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2068overall class and def structure of a module.
2069
2070`\\[back-to-indentation]' moves point to a line's first non-blank character.
2071
2072`\\[indent-relative]' is handy for creating odd indentation.
2073
2074@OTHER EMACS HINTS
2075
2076If you don't like the default value of a variable, change its value to
2077whatever you do like by putting a `setq' line in your .emacs file.
2078E.g., to set the indentation increment to 4, put this line in your
2079.emacs:
2080\t(setq py-indent-offset 4)
2081To see the value of a variable, do `\\[describe-variable]' and enter the variable
2082name at the prompt.
2083
2084When entering a key sequence like `C-c C-n', it is not necessary to
2085release the CONTROL key after doing the `C-c' part -- it suffices to
2086press the CONTROL key, press and release `c' (while still holding down
2087CONTROL), press and release `n' (while still holding down CONTROL), &
2088then release CONTROL.
2089
2090Entering Python mode calls with no arguments the value of the variable
Guido van Rossuma67bb7e1994-11-10 23:01:59 +00002091`python-mode-hook', if that value exists and is not nil; for backward
2092compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2093the Elisp manual for details.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002094
2095Obscure: When python-mode is first loaded, it looks for all bindings
2096to newline-and-indent in the global keymap, and shadows them with
2097local bindings to py-newline-and-indent."))
2098
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002099
2100;; Helper functions
Guido van Rossuma7925f11994-01-26 10:20:16 +00002101(defvar py-parse-state-re
2102 (concat
2103 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2104 "\\|"
2105 "^[^ #\t\n]"))
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002106
Guido van Rossuma7925f11994-01-26 10:20:16 +00002107;; returns the parse state at point (see parse-partial-sexp docs)
2108(defun py-parse-state ()
2109 (save-excursion
Guido van Rossum6ba11201996-08-20 19:57:53 +00002110 (let ((here (point))
2111 pps done ci)
2112 (while (not done)
2113 ;; back up to the first preceding line (if any; else start of
2114 ;; buffer) that begins with a popular Python keyword, or a
2115 ;; non- whitespace and non-comment character. These are good
2116 ;; places to start parsing to see whether where we started is
2117 ;; at a non-zero nesting level. It may be slow for people who
2118 ;; write huge code blocks or huge lists ... tough beans.
2119 (re-search-backward py-parse-state-re nil 'move)
2120 (setq ci (current-indentation))
2121 (beginning-of-line)
2122 (save-excursion
2123 (setq pps (parse-partial-sexp (point) here)))
2124 ;; make sure we don't land inside a triple-quoted string
2125 (setq done (or (zerop ci)
2126 (not (nth 3 pps))
2127 (bobp)))
2128 )
2129 pps)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002130
2131;; if point is at a non-zero nesting level, returns the number of the
2132;; character that opens the smallest enclosing unclosed list; else
2133;; returns nil.
2134(defun py-nesting-level ()
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002135 (let ((status (py-parse-state)) )
Guido van Rossuma7925f11994-01-26 10:20:16 +00002136 (if (zerop (car status))
2137 nil ; not in a nest
2138 (car (cdr status))))) ; char# of open bracket
2139
2140;; t iff preceding line ends with backslash that's not in a comment
2141(defun py-backslash-continuation-line-p ()
2142 (save-excursion
2143 (beginning-of-line)
2144 (and
2145 ;; use a cheap test first to avoid the regexp if possible
2146 ;; use 'eq' because char-after may return nil
2147 (eq (char-after (- (point) 2)) ?\\ )
2148 ;; make sure; since eq test passed, there is a preceding line
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002149 (forward-line -1) ; always true -- side effect
Guido van Rossuma7925f11994-01-26 10:20:16 +00002150 (looking-at py-continued-re))))
2151
2152;; t iff current line is a continuation line
2153(defun py-continuation-line-p ()
2154 (save-excursion
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002155 (beginning-of-line)
Guido van Rossuma7925f11994-01-26 10:20:16 +00002156 (or (py-backslash-continuation-line-p)
2157 (py-nesting-level))))
2158
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002159;; go to initial line of current statement; usually this is the line
2160;; we're on, but if we're on the 2nd or following lines of a
2161;; continuation block, we need to go up to the first line of the
2162;; block.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002163;;
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002164;; Tricky: We want to avoid quadratic-time behavior for long continued
2165;; blocks, whether of the backslash or open-bracket varieties, or a
2166;; mix of the two. The following manages to do that in the usual
2167;; cases.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002168(defun py-goto-initial-line ()
2169 (let ( open-bracket-pos )
2170 (while (py-continuation-line-p)
2171 (beginning-of-line)
2172 (if (py-backslash-continuation-line-p)
2173 (while (py-backslash-continuation-line-p)
2174 (forward-line -1))
2175 ;; else zip out of nested brackets/braces/parens
2176 (while (setq open-bracket-pos (py-nesting-level))
2177 (goto-char open-bracket-pos)))))
2178 (beginning-of-line))
2179
2180;; go to point right beyond final line of current statement; usually
2181;; this is the start of the next line, but if this is a multi-line
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002182;; statement we need to skip over the continuation lines. Tricky:
2183;; Again we need to be clever to avoid quadratic time behavior.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002184(defun py-goto-beyond-final-line ()
2185 (forward-line 1)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002186 (let (state)
Guido van Rossuma7925f11994-01-26 10:20:16 +00002187 (while (and (py-continuation-line-p)
2188 (not (eobp)))
2189 ;; skip over the backslash flavor
2190 (while (and (py-backslash-continuation-line-p)
2191 (not (eobp)))
2192 (forward-line 1))
2193 ;; if in nest, zip to the end of the nest
2194 (setq state (py-parse-state))
2195 (if (and (not (zerop (car state)))
2196 (not (eobp)))
2197 (progn
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002198 ;; BUG ALERT: I could swear, from reading the docs, that
Guido van Rossuma7925f11994-01-26 10:20:16 +00002199 ;; the 3rd argument should be plain 0
2200 (parse-partial-sexp (point) (point-max) (- 0 (car state))
2201 nil state)
2202 (forward-line 1))))))
2203
2204;; t iff statement opens a block == iff it ends with a colon that's
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002205;; not in a comment. point should be at the start of a statement
Guido van Rossuma7925f11994-01-26 10:20:16 +00002206(defun py-statement-opens-block-p ()
2207 (save-excursion
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002208 (let ((start (point))
2209 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2210 (searching t)
2211 (answer nil)
2212 state)
Guido van Rossuma7925f11994-01-26 10:20:16 +00002213 (goto-char start)
2214 (while searching
2215 ;; look for a colon with nothing after it except whitespace, and
2216 ;; maybe a comment
2217 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2218 finish t)
2219 (if (eq (point) finish) ; note: no `else' clause; just
2220 ; keep searching if we're not at
2221 ; the end yet
2222 ;; sure looks like it opens a block -- but it might
2223 ;; be in a comment
2224 (progn
2225 (setq searching nil) ; search is done either way
2226 (setq state (parse-partial-sexp start
2227 (match-beginning 0)))
2228 (setq answer (not (nth 4 state)))))
2229 ;; search failed: couldn't find another interesting colon
2230 (setq searching nil)))
2231 answer)))
2232
Guido van Rossum6ba11201996-08-20 19:57:53 +00002233(defun py-statement-closes-block-p ()
2234 ;; true iff the current statement `closes' a block == the line
Guido van Rossuma83f3b81996-10-23 20:55:00 +00002235 ;; starts with `return', `raise', `break', `continue', and `pass'.
2236 ;; doesn't catch embedded statements
Guido van Rossum6ba11201996-08-20 19:57:53 +00002237 (let ((here (point)))
2238 (back-to-indentation)
2239 (prog1
Guido van Rossuma83f3b81996-10-23 20:55:00 +00002240 (looking-at "\\(return\\|raise\\|break\\|continue\\|pass\\)\\>")
Guido van Rossum6ba11201996-08-20 19:57:53 +00002241 (goto-char here))))
2242
Guido van Rossuma7925f11994-01-26 10:20:16 +00002243;; go to point right beyond final line of block begun by the current
2244;; line. This is the same as where py-goto-beyond-final-line goes
2245;; unless we're on colon line, in which case we go to the end of the
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002246;; block. assumes point is at bolp
Guido van Rossuma7925f11994-01-26 10:20:16 +00002247(defun py-goto-beyond-block ()
2248 (if (py-statement-opens-block-p)
2249 (py-mark-block nil 'just-move)
2250 (py-goto-beyond-final-line)))
2251
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002252;; go to start of first statement (not blank or comment or
2253;; continuation line) at or preceding point. returns t if there is
2254;; one, else nil
Guido van Rossuma7925f11994-01-26 10:20:16 +00002255(defun py-goto-statement-at-or-above ()
2256 (py-goto-initial-line)
2257 (if (looking-at py-blank-or-comment-re)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002258 ;; skip back over blank & comment lines
2259 ;; note: will skip a blank or comment line that happens to be
2260 ;; a continuation line too
2261 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2262 (progn (py-goto-initial-line) t)
2263 nil)
Guido van Rossuma7925f11994-01-26 10:20:16 +00002264 t))
2265
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002266;; go to start of first statement (not blank or comment or
2267;; continuation line) following the statement containing point returns
2268;; t if there is one, else nil
Guido van Rossuma7925f11994-01-26 10:20:16 +00002269(defun py-goto-statement-below ()
2270 (beginning-of-line)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002271 (let ((start (point)))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002272 (py-goto-beyond-final-line)
2273 (while (and
2274 (looking-at py-blank-or-comment-re)
2275 (not (eobp)))
2276 (forward-line 1))
2277 (if (eobp)
2278 (progn (goto-char start) nil)
2279 t)))
2280
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002281;; go to start of statement, at or preceding point, starting with
2282;; keyword KEY. Skips blank lines and non-indenting comments upward
2283;; first. If that statement starts with KEY, done, else go back to
2284;; first enclosing block starting with KEY. If successful, leaves
2285;; point at the start of the KEY line & returns t. Else leaves point
2286;; at an undefined place & returns nil.
Guido van Rossuma7925f11994-01-26 10:20:16 +00002287(defun py-go-up-tree-to-keyword (key)
2288 ;; skip blanks and non-indenting #
2289 (py-goto-initial-line)
2290 (while (and
2291 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2292 (zerop (forward-line -1))) ; go back
2293 nil)
2294 (py-goto-initial-line)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002295 (let* ((re (concat "[ \t]*" key "\\b"))
2296 (case-fold-search nil) ; let* so looking-at sees this
2297 (found (looking-at re))
2298 (dead nil))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002299 (while (not (or found dead))
2300 (condition-case nil ; in case no enclosing block
2301 (py-goto-block-up 'no-mark)
2302 (error (setq dead t)))
2303 (or dead (setq found (looking-at re))))
2304 (beginning-of-line)
2305 found))
2306
2307;; return string in buffer from start of indentation to end of line;
2308;; prefix "..." if leading whitespace was skipped
2309(defun py-suck-up-leading-text ()
2310 (save-excursion
2311 (back-to-indentation)
2312 (concat
2313 (if (bolp) "" "...")
2314 (buffer-substring (point) (progn (end-of-line) (point))))))
2315
2316;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2317;; as a Lisp symbol; return nil if none
2318(defun py-suck-up-first-keyword ()
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002319 (let ((case-fold-search nil))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002320 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2321 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2322 nil)))
2323
2324(defun py-make-temp-name ()
2325 (make-temp-name
2326 (concat (file-name-as-directory py-temp-directory) "python")))
2327
2328(defun py-delete-file-silently (fname)
2329 (condition-case nil
2330 (delete-file fname)
2331 (error nil)))
2332
2333(defun py-kill-emacs-hook ()
2334 ;; delete our temp files
2335 (while py-file-queue
2336 (py-delete-file-silently (car py-file-queue))
2337 (setq py-file-queue (cdr py-file-queue)))
Guido van Rossum581d1721994-04-28 08:31:52 +00002338 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002339 ;; run the hook we inherited, if any
2340 (and py-inherited-kill-emacs-hook
2341 (funcall py-inherited-kill-emacs-hook))))
2342
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002343;; make PROCESS's buffer visible, append STRING to it, and force
2344;; display; also make shell-mode believe the user typed this string,
2345;; so that kill-output-from-shell and show-output-from-shell work
2346;; "right"
Guido van Rossuma7925f11994-01-26 10:20:16 +00002347(defun py-append-to-process-buffer (process string)
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002348 (let ((cbuf (current-buffer))
2349 (pbuf (process-buffer process))
2350 (py-scroll-process-buffer t))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002351 (set-buffer pbuf)
2352 (goto-char (point-max))
2353 (move-marker (process-mark process) (point))
Guido van Rossumd4901c81995-08-28 03:12:57 +00002354 (if (not (or py-this-is-emacs-19-p
2355 py-this-is-lucid-emacs-p))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002356 (move-marker last-input-start (point))) ; muck w/ shell-mode
2357 (funcall (process-filter process) process string)
Guido van Rossumd4901c81995-08-28 03:12:57 +00002358 (if (not (or py-this-is-emacs-19-p
2359 py-this-is-lucid-emacs-p))
Guido van Rossuma7925f11994-01-26 10:20:16 +00002360 (move-marker last-input-end (point))) ; muck w/ shell-mode
2361 (set-buffer cbuf))
2362 (sit-for 0))
2363
Guido van Rossuma83f3b81996-10-23 20:55:00 +00002364(defun py-current-defun ()
2365 ;; tell add-log.el how to find the current function/method/variable
2366 (save-excursion
2367 (if (re-search-backward py-defun-start-re nil t)
2368 (or (match-string 3)
2369 (let ((method (match-string 2)))
2370 (if (and (not (zerop (length (match-string 1))))
2371 (re-search-backward py-class-start-re nil t))
2372 (concat (match-string 1) "." method)
2373 method)))
2374 nil)))
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002375
2376
Guido van Rossuma83f3b81996-10-23 20:55:00 +00002377(defconst py-version "2.83"
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002378 "`python-mode' version number.")
Guido van Rossumd4901c81995-08-28 03:12:57 +00002379(defconst py-help-address "python-mode@python.org"
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002380 "Address accepting submission of bug reports.")
2381
2382(defun py-version ()
2383 "Echo the current version of `python-mode' in the minibuffer."
2384 (interactive)
2385 (message "Using `python-mode' version %s" py-version)
2386 (py-keep-region-active))
2387
2388;; only works under Emacs 19
2389;(eval-when-compile
2390; (require 'reporter))
2391
2392(defun py-submit-bug-report (enhancement-p)
2393 "Submit via mail a bug report on `python-mode'.
2394With \\[universal-argument] just submit an enhancement request."
2395 (interactive
2396 (list (not (y-or-n-p
2397 "Is this a bug report? (hit `n' to send other comments) "))))
Guido van Rossum1d5645d1995-03-14 21:31:47 +00002398 (let ((reporter-prompt-for-summary-p (if enhancement-p
2399 "(Very) brief summary: "
2400 t)))
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002401 (require 'reporter)
2402 (reporter-submit-bug-report
2403 py-help-address ;address
Guido van Rossum1d5645d1995-03-14 21:31:47 +00002404 (concat "python-mode " py-version) ;pkgname
Guido van Rossumdeaa1051995-03-10 16:17:03 +00002405 ;; varlist
2406 (if enhancement-p nil
2407 '(py-python-command
2408 py-indent-offset
2409 py-block-comment-prefix
2410 py-scroll-process-buffer
2411 py-temp-directory
2412 py-beep-if-tab-change))
2413 nil ;pre-hooks
2414 nil ;post-hooks
2415 "Dear Barry,") ;salutation
2416 (if enhancement-p nil
2417 (set-mark (point))
2418 (insert
2419"Please replace this text with a sufficiently large code sample\n\
2420and an exact recipe so that I can reproduce your problem. Failure\n\
2421to do so may mean a greater delay in fixing your bug.\n\n")
2422 (exchange-point-and-mark)
2423 (py-keep-region-active))))
2424
2425
2426;; arrange to kill temp files when Emacs exists
2427(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2428 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2429 ;; have to trust that other people are as respectful of our hook
2430 ;; fiddling as we are of theirs
2431 (if (boundp 'py-inherited-kill-emacs-hook)
2432 ;; we were loaded before -- trust others not to have screwed us
2433 ;; in the meantime (no choice, really)
2434 nil
2435 ;; else arrange for our hook to run theirs
2436 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2437 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2438
2439
2440
2441(provide 'python-mode)
2442;;; python-mode.el ends here