blob: bdeaa2b14c7d275b73943107b0b6a7ef93dacfc5 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7d6b7d31997-08-08 16:19:03 +00009;; Version: 3.0
Barry Warsaw4669d7e1996-03-22 16:13:24 +000010;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000011
Barry Warsawcfec3591995-03-10 15:58:16 +000012;; This software is provided as-is, without express or implied
13;; warranty. Permission to use, copy, modify, distribute or sell this
14;; software, without fee, for any purpose and by any individual or
15;; organization, is hereby granted, provided that the above copyright
16;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000017
18;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000019
Barry Warsaw7b0f5681995-03-08 21:33:04 +000020;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000021;; by Tim Peters after an original idea by Michael A. Guravage. Tim
22;; subsequently left the net; in 1995, Barry Warsaw inherited the
23;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000024
25;; At some point this mode will undergo a rewrite to bring it more in
Barry Warsaw755c6711996-08-01 20:02:55 +000026;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
27;; 18 support. But all in all, the mode works exceedingly well, and
28;; I've simply been tweaking it as I go along. Ain't it wonderful
29;; that Python has a much more sane syntax than C? (or <shudder> C++?!
30;; :-). I can say that; I maintain cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
32;; The following statements, placed in your .emacs file or
33;; site-init.el, will cause this file to be autoloaded, and
34;; python-mode invoked, when visiting .py files (assuming this file is
35;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000037;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;; (setq auto-mode-alist
39;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000040;;
41;; If you want font-lock support for Python source code (a.k.a. syntax
42;; coloring, highlighting), add this to your .emacs file:
43;;
44;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000045;;
46;; But you better be sure you're version of Emacs supports
47;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
48;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000049
Barry Warsaw3fcaf611996-08-01 20:11:51 +000050;; Here's a brief list of recent additions/improvements/changes:
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000051;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000052;; - Wrapping and indentation within triple quote strings now works.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000053;; - `Standard' bug reporting mechanism (use C-c C-b)
54;; - py-mark-block was moved to C-c C-m
55;; - C-c C-v shows you the python-mode version
Barry Warsaw3fcaf611996-08-01 20:11:51 +000056;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000057;; - proper interaction with pending-del and del-sel modes.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000058;; - Better support for outdenting: py-electric-colon (:) and
59;; py-indent-line (TAB) improvements; one level of outdentation
Barry Warsaw7cb505c1996-10-23 20:44:59 +000060;; added after a return, raise, break, pass, or continue statement.
61;; Defeated by prefixing command with C-u.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000062;; - New py-electric-colon (:) command for improved outdenting Also
63;; py-indent-line (TAB) should handle outdented lines better
Barry Warsaw03970731996-07-03 23:12:52 +000064;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000065;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
66;; M-f and M-b respectively.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000067;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
68;; - py-indent-offset now defaults to 4
69;; - new variable py-honor-comment-indentation
70;; - comment-region bound to C-c #
71;; - py-delete-char obeys numeric arguments
72;; - Small modification to rule for "indenting comment lines", such
73;; lines must now also be indented less than or equal to the
74;; indentation of the previous statement.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000075
Barry Warsaw7b0f5681995-03-08 21:33:04 +000076;; Here's a brief to do list:
77;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000078;; - Better integration with gud-mode for debugging.
79;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000080;; - possibly force indent-tabs-mode == nil, and add a
81;; write-file-hooks that runs untabify on the whole buffer (to work
82;; around potential tab/space mismatch problems). In practice this
83;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000084;; - have py-execute-region on indented code act as if the region is
85;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000086;; - Add a py-goto-error or some such that would scan an exception in
87;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000088
Barry Warsaw7b0f5681995-03-08 21:33:04 +000089;; If you can think of more things you'd like to see, drop me a line.
90;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
91;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000092;; Note that I only test things on XEmacs 19 and to some degree on
93;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
94;; send me your patches. Byte compiler complaints can probably be
95;; safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000096
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097;;; Code:
98
99
100;; user definable variables
101;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000102
103(defvar py-python-command "python"
104 "*Shell command used to start Python interpreter.")
105
Barry Warsaw17914f41995-11-03 18:25:15 +0000106(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +0000107 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000108Note that `\\[py-guess-indent-offset]' can usually guess a good value
109when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000110
Barry Warsaw095e9c61995-09-19 20:01:42 +0000111(defvar py-align-multiline-strings-p t
112 "*Flag describing how multiline triple quoted strings are aligned.
113When this flag is non-nil, continuation lines are lined up under the
114preceding line's indentation. When this flag is nil, continuation
115lines are aligned to column zero.")
116
Barry Warsaw3fcaf611996-08-01 20:11:51 +0000117(defvar py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000118 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000119This should follow the convention for non-indenting comment lines so
120that the indentation commands won't get confused (i.e., the string
121should be of the form `#x...' where `x' is not a blank or a tab, and
122`...' is arbitrary).")
123
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000124(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000125 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000126
Barry Warsaw6d627751996-03-06 18:41:38 +0000127When nil, all comment lines are skipped for indentation purposes, and
128in Emacs 19, a faster algorithm is used.
129
130When t, lines that begin with a single `#' are a hint to subsequent
131line indentation. If the previous line is such a comment line (as
132opposed to one that starts with `py-block-comment-prefix'), then it's
133indentation is used as a hint for this line's indentation. Lines that
134begin with `py-block-comment-prefix' are ignored for indentation
135purposes.
136
137When not nil or t, comment lines that begin with a `#' are used as
138indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000139
Barry Warsaw7ae77681994-12-12 20:38:05 +0000140(defvar py-scroll-process-buffer t
141 "*Scroll Python process buffer as output arrives.
142If nil, the Python process buffer acts, with respect to scrolling, like
143Shell-mode buffers normally act. This is surprisingly complicated and
144so won't be explained here; in fact, you can't get the whole story
145without studying the Emacs C code.
146
147If non-nil, the behavior is different in two respects (which are
148slightly inaccurate in the interest of brevity):
149
150 - If the buffer is in a window, and you left point at its end, the
151 window will scroll as new output arrives, and point will move to the
152 buffer's end, even if the window is not the selected window (that
153 being the one the cursor is in). The usual behavior for shell-mode
154 windows is not to scroll, and to leave point where it was, if the
155 buffer is in a window other than the selected window.
156
157 - If the buffer is not visible in any window, and you left point at
158 its end, the buffer will be popped into a window as soon as more
159 output arrives. This is handy if you have a long-running
160 computation and don't want to tie up screen area waiting for the
161 output. The usual behavior for a shell-mode buffer is to stay
162 invisible until you explicitly visit it.
163
164Note the `and if you left point at its end' clauses in both of the
165above: you can `turn off' the special behaviors while output is in
166progress, by visiting the Python buffer and moving point to anywhere
167besides the end. Then the buffer won't scroll, point will remain where
168you leave it, and if you hide the buffer it will stay hidden until you
169visit it again. You can enable and disable the special behaviors as
170often as you like, while output is in progress, by (respectively) moving
171point to, or away from, the end of the buffer.
172
173Warning: If you expect a large amount of output, you'll probably be
174happier setting this option to nil.
175
176Obscure: `End of buffer' above should really say `at or beyond the
177process mark', but if you know what that means you didn't need to be
178told <grin>.")
179
180(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000181 (let ((ok '(lambda (x)
182 (and x
183 (setq x (expand-file-name x)) ; always true
184 (file-directory-p x)
185 (file-writable-p x)
186 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000187 (or (funcall ok (getenv "TMPDIR"))
188 (funcall ok "/usr/tmp")
189 (funcall ok "/tmp")
190 (funcall ok ".")
191 (error
192 "Couldn't find a usable temp directory -- set py-temp-directory")))
193 "*Directory used for temp files created by a *Python* process.
194By default, the first directory from this list that exists and that you
195can write into: the value (if any) of the environment variable TMPDIR,
196/usr/tmp, /tmp, or the current directory.")
197
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000198(defvar py-beep-if-tab-change t
199 "*Ring the bell if tab-width is changed.
200If a comment of the form
201
202 \t# vi:set tabsize=<number>:
203
204is found before the first code line when the file is entered, and the
205current value of (the general Emacs variable) `tab-width' does not
206equal <number>, `tab-width' is set to <number>, a message saying so is
207displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
208the Emacs bell is also rung as a warning.")
209
Barry Warsawfb07f401997-02-24 03:37:22 +0000210(defvar python-font-lock-keywords
Barry Warsaw2e049b21996-09-04 15:21:55 +0000211 (let* ((keywords '("and" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000212 "continue" "def" "del" "elif"
213 "else:" "except" "except:" "exec"
214 "finally:" "for" "from" "global"
215 "if" "import" "in" "is"
216 "lambda" "not" "or" "pass"
217 "print" "raise" "return" "try:"
218 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000219 ))
220 (kwregex (mapconcat 'identity keywords "\\|")))
221 (list
222 ;; keywords not at beginning of line
223 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
224 ;; keywords at beginning of line. i don't think regexps are
225 ;; powerful enough to handle these two cases in one regexp.
226 ;; prove me wrong!
227 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
228 ;; classes
229 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
230 1 font-lock-type-face)
231 ;; functions
232 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
233 1 font-lock-function-name-face)
234 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000235 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000236(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
237
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000238
Barry Warsaw81437461996-08-01 19:48:02 +0000239(defvar imenu-example--python-show-method-args-p nil
240 "*Controls echoing of arguments of functions & methods in the imenu buffer.
241When non-nil, arguments are printed.")
242
243
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000244
245;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
246;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
247
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000248(make-variable-buffer-local 'py-indent-offset)
249
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
251;; seems to be the standard way of checking this.
252;; BAW - This is *not* the right solution. When at all possible,
253;; instead of testing for the version of Emacs, use feature tests.
254
255(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
256(setq py-this-is-emacs-19-p
257 (and
258 (not py-this-is-lucid-emacs-p)
259 (string-match "^19\\." emacs-version)))
260
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261;; have to bind py-file-queue before installing the kill-emacs hook
262(defvar py-file-queue nil
263 "Queue of Python temp files awaiting execution.
264Currently-active file is at the head of the list.")
265
266;; define a mode-specific abbrev table for those who use such things
267(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000268 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269(define-abbrev-table 'python-mode-abbrev-table nil)
270
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271(defvar python-mode-hook nil
272 "*Hook called by `python-mode'.")
273
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000274;; in previous version of python-mode.el, the hook was incorrectly
275;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000276(and (fboundp 'make-obsolete-variable)
277 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
278
Barry Warsawb0539931996-12-17 22:05:07 +0000279(defvar py-delete-function 'backward-delete-char-untabify
280 "*Function called by `py-delete-char' when deleting characters.")
281
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000282(defvar py-mode-map ()
283 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000284
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285(if py-mode-map
286 ()
287 (setq py-mode-map (make-sparse-keymap))
288
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000289 ;; shadow global bindings for newline-and-indent w/ the py- version.
290 ;; BAW - this is extremely bad form, but I'm not going to change it
291 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000292 (mapcar (function (lambda (key)
293 (define-key
294 py-mode-map key 'py-newline-and-indent)))
295 (where-is-internal 'newline-and-indent))
296
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000297 ;; BAW - you could do it this way, but its not considered proper
298 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000299 (mapcar (function
300 (lambda (x)
301 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000302 '((":" . py-electric-colon)
303 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000304 ("\C-c|" . py-execute-region)
305 ("\C-c!" . py-shell)
306 ("\177" . py-delete-char)
307 ("\n" . py-newline-and-indent)
308 ("\C-c:" . py-guess-indent-offset)
309 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000310 ("\C-c\C-l" . py-shift-region-left)
311 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000312 ("\C-c<" . py-shift-region-left)
313 ("\C-c>" . py-shift-region-right)
314 ("\C-c\C-n" . py-next-statement)
315 ("\C-c\C-p" . py-previous-statement)
316 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000317 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000318 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000319 ("\C-c?" . py-describe-mode)
320 ("\C-c\C-hm" . py-describe-mode)
321 ("\e\C-a" . beginning-of-python-def-or-class)
322 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000323 ( "\e\C-h" . mark-python-def-or-class)))
324 ;; should do all keybindings this way
325 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
326 (define-key py-mode-map "\C-c\C-v" 'py-version)
327 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000328
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000329(defvar py-mode-syntax-table nil
330 "Syntax table used in `python-mode' buffers.")
331
Barry Warsaw7ae77681994-12-12 20:38:05 +0000332(if py-mode-syntax-table
333 ()
334 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000335 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000336 (mapcar (function
337 (lambda (x) (modify-syntax-entry
338 (car x) (cdr x) py-mode-syntax-table)))
339 '(( ?\( . "()" ) ( ?\) . ")(" )
340 ( ?\[ . "(]" ) ( ?\] . ")[" )
341 ( ?\{ . "(}" ) ( ?\} . "){" )
342 ;; fix operator symbols misassigned in the std table
343 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
344 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
345 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
346 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000347 ;; for historical reasons, underscore is word class
348 ;; instead of symbol class. it should be symbol class,
349 ;; but if you're tempted to change it, try binding M-f and
350 ;; M-b to py-forward-into-nomenclature and
351 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000352 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000353 ( ?\' . "\"") ; single quote is string quote
354 ( ?\" . "\"" ) ; double quote is string quote too
355 ( ?\` . "$") ; backquote is open and close paren
356 ( ?\# . "<") ; hash starts comment
357 ( ?\n . ">")))) ; newline ends comment
358
359(defconst py-stringlit-re
360 (concat
361 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
362 "\\|" ; or
363 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000364 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365
366;; this is tricky because a trailing backslash does not mean
367;; continuation if it's in a comment
368(defconst py-continued-re
369 (concat
370 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
371 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000372 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000373
374(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000375 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000376
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000377(defconst py-outdent-re
378 (concat "\\(" (mapconcat 'identity
379 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000380 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000381 "finally:"
382 "elif\\s +.*:")
383 "\\|")
384 "\\)")
385 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000387(defconst py-no-outdent-re
388 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000389 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000390 "except\\(\\s +.*\\)?:"
391 "while\\s +.*:"
392 "for\\s +.*:"
393 "if\\s +.*:"
Barry Warsawf67a57e1996-08-12 19:52:27 +0000394 "elif\\s +.*:"
395 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
396 )
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000397 "\\|")
398 "\\)")
399 "Regexp matching lines to not outdent after.")
400
Barry Warsawb3e81d51996-09-04 15:12:42 +0000401(defvar py-defun-start-re
402 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
403 "Regexp matching a function, method or variable assignment.
404
405If you change this, you probably have to change `py-current-defun' as well.
406This is only used by `py-current-defun' to find the name for add-log.el.")
407
408(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
409 "Regexp for finding a class name.
410
411If you change this, you probably have to change `py-current-defun' as well.
412This is only used by `py-current-defun' to find the name for add-log.el.")
413
Barry Warsawf7705781997-01-30 19:49:39 +0000414;; As of 30-Jan-1997, Emacs 19.34 works but XEmacs 19.15b90 and
415;; previous does not. It is suspected that Emacsen before 19.34 are
416;; also broken.
417(defvar py-parse-partial-sexp-works-p
418 (let ((buf (get-buffer-create " ---*---pps---*---"))
419 state status)
420 (save-excursion
421 (set-buffer buf)
422 (erase-buffer)
423 (insert "(line1\n line2)\nline3")
424 (lisp-mode)
425 (goto-char (point-min))
426 (setq state (parse-partial-sexp (point) (save-excursion
427 (forward-line 1)
428 (point))))
429 (parse-partial-sexp (point) (point-max) 0 nil state)
430 (setq status (not (= (point) (point-max))))
431 (kill-buffer buf)
432 status))
433 "Does `parse-partial-sexp' work in this Emacs?")
Barry Warsawb3e81d51996-09-04 15:12:42 +0000434
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000435
Barry Warsaw42f707f1996-07-29 21:05:05 +0000436;; Menu definitions, only relevent if you have the easymenu.el package
437;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000438(defvar py-menu nil
439 "Menu for Python Mode.
440
441This menu will get created automatically if you have the easymenu
442package. Note that the latest XEmacs 19 and Emacs 19 versions contain
443this package.")
444
Barry Warsaw42f707f1996-07-29 21:05:05 +0000445(if (condition-case nil
446 (require 'easymenu)
447 (error nil))
448 (easy-menu-define
449 py-menu py-mode-map "Python Mode menu"
450 '("Python"
Barry Warsaw941f70c1997-01-30 20:16:18 +0000451 ["Comment Out Region" py-comment-region (mark)]
452 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
Barry Warsaw42f707f1996-07-29 21:05:05 +0000453 "-"
454 ["Mark current block" py-mark-block t]
455 ["Mark current def" mark-python-def-or-class t]
456 ["Mark current class" (mark-python-def-or-class t) t]
457 "-"
458 ["Shift region left" py-shift-region-left (mark)]
459 ["Shift region right" py-shift-region-right (mark)]
460 "-"
461 ["Execute buffer" py-execute-buffer t]
462 ["Execute region" py-execute-region (mark)]
463 ["Start interpreter..." py-shell t]
464 "-"
465 ["Go to start of block" py-goto-block-up t]
466 ["Go to start of class" (beginning-of-python-def-or-class t) t]
467 ["Move to end of class" (end-of-python-def-or-class t) t]
468 ["Move to start of def" beginning-of-python-def-or-class t]
469 ["Move to end of def" end-of-python-def-or-class t]
470 "-"
471 ["Describe mode" py-describe-mode t]
472 )))
473
Barry Warsaw81437461996-08-01 19:48:02 +0000474
475
476;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
477(defvar imenu-example--python-class-regexp
478 (concat ; <<classes>>
479 "\\(" ;
480 "^[ \t]*" ; newline and maybe whitespace
481 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
482 ; possibly multiple superclasses
483 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
484 "[ \t]*:" ; and the final :
485 "\\)" ; >>classes<<
486 )
487 "Regexp for Python classes for use with the imenu package."
488 )
489
490(defvar imenu-example--python-method-regexp
491 (concat ; <<methods and functions>>
492 "\\(" ;
493 "^[ \t]*" ; new line and maybe whitespace
494 "\\(def[ \t]+" ; function definitions start with def
495 "\\([a-zA-Z0-9_]+\\)" ; name is here
496 ; function arguments...
497 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
498 "\\)" ; end of def
499 "[ \t]*:" ; and then the :
500 "\\)" ; >>methods and functions<<
501 )
502 "Regexp for Python methods/functions for use with the imenu package."
503 )
504
505(defvar imenu-example--python-method-no-arg-parens '(2 8)
506 "Indicies into groups of the Python regexp for use with imenu.
507
508Using these values will result in smaller imenu lists, as arguments to
509functions are not listed.
510
511See the variable `imenu-example--python-show-method-args-p' for more
512information.")
513
514(defvar imenu-example--python-method-arg-parens '(2 7)
515 "Indicies into groups of the Python regexp for use with imenu.
516Using these values will result in large imenu lists, as arguments to
517functions are listed.
518
519See the variable `imenu-example--python-show-method-args-p' for more
520information.")
521
522;; Note that in this format, this variable can still be used with the
523;; imenu--generic-function. Otherwise, there is no real reason to have
524;; it.
525(defvar imenu-example--generic-python-expression
526 (cons
527 (concat
528 imenu-example--python-class-regexp
529 "\\|" ; or...
530 imenu-example--python-method-regexp
531 )
532 imenu-example--python-method-no-arg-parens)
533 "Generic Python expression which may be used directly with imenu.
534Used by setting the variable `imenu-generic-expression' to this value.
535Also, see the function \\[imenu-example--create-python-index] for a
536better alternative for finding the index.")
537
538;; These next two variables are used when searching for the python
539;; class/definitions. Just saving some time in accessing the
540;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000541(defvar imenu-example--python-generic-regexp nil)
542(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000543
544
545;;;###autoload
546(eval-when-compile
547 ;; Imenu isn't used in XEmacs, so just ignore load errors
548 (condition-case ()
549 (progn
550 (require 'cl)
551 (require 'imenu))
552 (error nil)))
553
554(defun imenu-example--create-python-index ()
555 "Python interface function for imenu package.
556Finds all python classes and functions/methods. Calls function
557\\[imenu-example--create-python-index-engine]. See that function for
558the details of how this works."
559 (setq imenu-example--python-generic-regexp
560 (car imenu-example--generic-python-expression))
561 (setq imenu-example--python-generic-parens
562 (if imenu-example--python-show-method-args-p
563 imenu-example--python-method-arg-parens
564 imenu-example--python-method-no-arg-parens))
565 (goto-char (point-min))
566 (imenu-example--create-python-index-engine nil))
567
568(defun imenu-example--create-python-index-engine (&optional start-indent)
569 "Function for finding imenu definitions in Python.
570
571Finds all definitions (classes, methods, or functions) in a Python
572file for the imenu package.
573
574Returns a possibly nested alist of the form
575
576 (INDEX-NAME . INDEX-POSITION)
577
578The second element of the alist may be an alist, producing a nested
579list as in
580
581 (INDEX-NAME . INDEX-ALIST)
582
583This function should not be called directly, as it calls itself
584recursively and requires some setup. Rather this is the engine for
585the function \\[imenu-example--create-python-index].
586
587It works recursively by looking for all definitions at the current
588indention level. When it finds one, it adds it to the alist. If it
589finds a definition at a greater indentation level, it removes the
590previous definition from the alist. In it's place it adds all
591definitions found at the next indentation level. When it finds a
592definition that is less indented then the current level, it retuns the
593alist it has created thus far.
594
595The optional argument START-INDENT indicates the starting indentation
596at which to continue looking for Python classes, methods, or
597functions. If this is not supplied, the function uses the indentation
598of the first definition found."
599 (let ((index-alist '())
600 (sub-method-alist '())
601 looking-p
602 def-name prev-name
603 cur-indent def-pos
604 (class-paren (first imenu-example--python-generic-parens))
605 (def-paren (second imenu-example--python-generic-parens)))
606 (setq looking-p
607 (re-search-forward imenu-example--python-generic-regexp
608 (point-max) t))
609 (while looking-p
610 (save-excursion
611 ;; used to set def-name to this value but generic-extract-name is
612 ;; new to imenu-1.14. this way it still works with imenu-1.11
613 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
614 (let ((cur-paren (if (match-beginning class-paren)
615 class-paren def-paren)))
616 (setq def-name
617 (buffer-substring (match-beginning cur-paren)
618 (match-end cur-paren))))
619 (beginning-of-line)
620 (setq cur-indent (current-indentation)))
621
622 ;; HACK: want to go to the next correct definition location. we
623 ;; explicitly list them here. would be better to have them in a
624 ;; list.
625 (setq def-pos
626 (or (match-beginning class-paren)
627 (match-beginning def-paren)))
628
629 ;; if we don't have a starting indent level, take this one
630 (or start-indent
631 (setq start-indent cur-indent))
632
633 ;; if we don't have class name yet, take this one
634 (or prev-name
635 (setq prev-name def-name))
636
637 ;; what level is the next definition on? must be same, deeper
638 ;; or shallower indentation
639 (cond
640 ;; at the same indent level, add it to the list...
641 ((= start-indent cur-indent)
642
643 ;; if we don't have push, use the following...
644 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
645 (push (cons def-name def-pos) index-alist))
646
647 ;; deeper indented expression, recur...
648 ((< start-indent cur-indent)
649
650 ;; the point is currently on the expression we're supposed to
651 ;; start on, so go back to the last expression. The recursive
652 ;; call will find this place again and add it to the correct
653 ;; list
654 (re-search-backward imenu-example--python-generic-regexp
655 (point-min) 'move)
656 (setq sub-method-alist (imenu-example--create-python-index-engine
657 cur-indent))
658
659 (if sub-method-alist
660 ;; we put the last element on the index-alist on the start
661 ;; of the submethod alist so the user can still get to it.
662 (let ((save-elmt (pop index-alist)))
663 (push (cons (imenu-create-submenu-name prev-name)
664 (cons save-elmt sub-method-alist))
665 index-alist))))
666
667 ;; found less indented expression, we're done.
668 (t
669 (setq looking-p nil)
670 (re-search-backward imenu-example--python-generic-regexp
671 (point-min) t)))
672 (setq prev-name def-name)
673 (and looking-p
674 (setq looking-p
675 (re-search-forward imenu-example--python-generic-regexp
676 (point-max) 'move))))
677 (nreverse index-alist)))
678
Barry Warsaw42f707f1996-07-29 21:05:05 +0000679
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000680;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000681(defun python-mode ()
682 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683To submit a problem report, enter `\\[py-submit-bug-report]' from a
684`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
685documentation. To see what version of `python-mode' you are running,
686enter `\\[py-version]'.
687
688This mode knows about Python indentation, tokens, comments and
689continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000690
691COMMANDS
692\\{py-mode-map}
693VARIABLES
694
Barry Warsaw42f707f1996-07-29 21:05:05 +0000695py-indent-offset\t\tindentation increment
696py-block-comment-prefix\t\tcomment string used by comment-region
697py-python-command\t\tshell command to invoke Python interpreter
698py-scroll-process-buffer\t\talways scroll Python process buffer
699py-temp-directory\t\tdirectory used for temp files (if needed)
700py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000701 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000702 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000703 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000704 (make-local-variable 'font-lock-defaults)
705 (make-local-variable 'paragraph-separate)
706 (make-local-variable 'paragraph-start)
707 (make-local-variable 'require-final-newline)
708 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000709 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000710 (make-local-variable 'comment-start-skip)
711 (make-local-variable 'comment-column)
712 (make-local-variable 'indent-region-function)
713 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000714 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000715 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000716 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000717 (setq major-mode 'python-mode
718 mode-name "Python"
719 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000720 paragraph-separate "^[ \t]*$"
721 paragraph-start "^[ \t]*$"
722 require-final-newline t
723 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000724 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000725 comment-start-skip "# *"
726 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000727 indent-region-function 'py-indent-region
728 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000729 ;; tell add-log.el how to find the current function/method/variable
730 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000731 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000732 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000733 ;; add the menu
734 (if py-menu
735 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000736 ;; Emacs 19 requires this
737 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
738 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000739 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000740 ;;
741 ;; not sure where the magic comment has to be; to save time
742 ;; searching for a rarity, we give up if it's not found prior to the
743 ;; first executable statement.
744 ;;
745 ;; BAW - on first glance, this seems like complete hackery. Why was
746 ;; this necessary, and is it still necessary?
747 (let ((case-fold-search nil)
748 (start (point))
749 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000750 (if (re-search-forward
751 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
752 (prog2 (py-next-statement 1) (point) (goto-char 1))
753 t)
754 (progn
755 (setq new-tab-width
756 (string-to-int
757 (buffer-substring (match-beginning 1) (match-end 1))))
758 (if (= tab-width new-tab-width)
759 nil
760 (setq tab-width new-tab-width)
761 (message "Caution: tab-width changed to %d" new-tab-width)
762 (if py-beep-if-tab-change (beep)))))
763 (goto-char start))
764
Barry Warsaw755c6711996-08-01 20:02:55 +0000765 ;; install imenu
766 (setq imenu-create-index-function
767 (function imenu-example--create-python-index))
768 (if (fboundp 'imenu-add-to-menubar)
769 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
770
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000771 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000772 (if python-mode-hook
773 (run-hooks 'python-mode-hook)
774 (run-hooks 'py-mode-hook)))
775
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000776
Barry Warsaw826255b1996-03-22 16:09:34 +0000777(defun py-keep-region-active ()
Barry Warsawce60bc71996-08-01 18:17:14 +0000778 ;; do whatever is necessary to keep the region active in XEmacs.
779 ;; Ignore byte-compiler warnings you might see. Also note that
780 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
781 ;; require us to take explicit action.
Barry Warsaw826255b1996-03-22 16:09:34 +0000782 (and (boundp 'zmacs-region-stays)
783 (setq zmacs-region-stays t)))
784
Barry Warsawce60bc71996-08-01 18:17:14 +0000785
Barry Warsawb91b7431995-03-14 15:55:20 +0000786;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000787(defun py-outdent-p ()
788 ;; returns non-nil if the current line should outdent one level
789 (save-excursion
790 (and (progn (back-to-indentation)
791 (looking-at py-outdent-re))
792 (progn (backward-to-indentation 1)
793 (while (or (looking-at py-blank-or-comment-re)
794 (bobp))
795 (backward-to-indentation 1))
796 (not (looking-at py-no-outdent-re)))
797 )))
798
799
Barry Warsawb91b7431995-03-14 15:55:20 +0000800(defun py-electric-colon (arg)
801 "Insert a colon.
802In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000803argument is provided, that many colons are inserted non-electrically.
804Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000805 (interactive "P")
806 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000807 ;; are we in a string or comment?
808 (if (save-excursion
809 (let ((pps (parse-partial-sexp (save-excursion
810 (beginning-of-python-def-or-class)
811 (point))
812 (point))))
813 (not (or (nth 3 pps) (nth 4 pps)))))
814 (save-excursion
815 (let ((here (point))
816 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000817 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000818 (if (and (not arg)
819 (py-outdent-p)
820 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000821 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000822 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000823 )
824 (setq outdent py-indent-offset))
825 ;; Don't indent, only outdent. This assumes that any lines that
826 ;; are already outdented relative to py-compute-indentation were
827 ;; put there on purpose. Its highly annoying to have `:' indent
828 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
829 ;; there a better way to determine this???
830 (if (< (current-indentation) indent) nil
831 (goto-char here)
832 (beginning-of-line)
833 (delete-horizontal-space)
834 (indent-to (- indent outdent))
835 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000836
837
Barry Warsaw7ae77681994-12-12 20:38:05 +0000838;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000839;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000840(defun py-shell ()
841 "Start an interactive Python interpreter in another window.
842This is like Shell mode, except that Python is running in the window
843instead of a shell. See the `Interactive Shell' and `Shell Mode'
844sections of the Emacs manual for details, especially for the key
845bindings active in the `*Python*' buffer.
846
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000847See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000848behavior in the process window.
849
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000850Warning: Don't use an interactive Python if you change sys.ps1 or
851sys.ps2 from their default values, or if you're running code that
852prints `>>> ' or `... ' at the start of a line. `python-mode' can't
853distinguish your output from Python's output, and assumes that `>>> '
854at the start of a line is a prompt from Python. Similarly, the Emacs
855Shell mode code assumes that both `>>> ' and `... ' at the start of a
856line are Python prompts. Bad things can happen if you fool either
857mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000858
859Warning: If you do any editing *in* the process buffer *while* the
860buffer is accepting output from Python, do NOT attempt to `undo' the
861changes. Some of the output (nowhere near the parts you changed!) may
862be lost if you do. This appears to be an Emacs bug, an unfortunate
863interaction between undo and process filters; the same problem exists in
864non-Python process buffers using the default (Emacs-supplied) process
865filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000866 ;; BAW - should undo be disabled in the python process buffer, if
867 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000868 (interactive)
Barry Warsawe6648961997-07-10 15:58:36 +0000869 (require 'comint)
870 (switch-to-buffer-other-window (make-comint "Python" py-python-command))
871 (make-local-variable 'comint-prompt-regexp)
872 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
873 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
874 (set-syntax-table py-mode-syntax-table)
875 (local-set-key [tab] 'self-insert-command))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876
877(defun py-execute-region (start end)
878 "Send the region between START and END to a Python interpreter.
879If there is a *Python* process it is used.
880
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000881Hint: If you want to execute part of a Python file several times
882\(e.g., perhaps you're developing a function and want to flesh it out
883a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
884the region of interest, and send the code to a *Python* process via
885`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000886
887Following are subtleties to note when using a *Python* process:
888
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889If a *Python* process is used, the region is copied into a temporary
890file (in directory `py-temp-directory'), and an `execfile' command is
891sent to Python naming that file. If you send regions faster than
892Python can execute them, `python-mode' will save them into distinct
893temp files, and execute the next one in the queue the next time it
894sees a `>>> ' prompt from Python. Each time this happens, the process
895buffer is popped into a window (if it's not already in some window) so
896you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000897
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000898 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000899
900is inserted at the end.
901
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000902Caution: No more than 26 regions can be pending at any given time.
903This limit is (indirectly) inherited from libc's mktemp(3).
904`python-mode' does not try to protect you from exceeding the limit.
905It's extremely unlikely that you'll get anywhere close to the limit in
906practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907
908See the `\\[py-shell]' docs for additional warnings."
909 (interactive "r")
910 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000911 (let ((pyproc (get-process "Python"))
912 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000913 (if (null pyproc)
914 (shell-command-on-region start end py-python-command)
915 ;; else feed it thru a temp file
916 (setq fname (py-make-temp-name))
917 (write-region start end fname nil 'no-msg)
918 (setq py-file-queue (append py-file-queue (list fname)))
919 (if (cdr py-file-queue)
920 (message "File %s queued for execution" fname)
921 ;; else
922 (py-execute-file pyproc fname)))))
923
924(defun py-execute-file (pyproc fname)
925 (py-append-to-process-buffer
926 pyproc
927 (format "## working on region in file %s ...\n" fname))
928 (process-send-string pyproc (format "execfile('%s')\n" fname)))
929
930(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000931 (let ((curbuf (current-buffer))
932 (pbuf (process-buffer pyproc))
933 (pmark (process-mark pyproc))
934 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935
936 ;; make sure we switch to a different buffer at least once. if we
937 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000938 ;; window, and point is before the end, and lots of output is
939 ;; coming at a fast pace, then (a) simple cursor-movement commands
940 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
941 ;; to have a visible effect (the window just doesn't get updated,
942 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
943 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000944 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945 ;; #b makes no sense to me at all. #a almost makes sense: unless
946 ;; we actually change buffers, set_buffer_internal in buffer.c
947 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
948 ;; seems to make the Emacs command loop reluctant to update the
949 ;; display. Perhaps the default process filter in process.c's
950 ;; read_process_output has update_mode_lines++ for a similar
951 ;; reason? beats me ...
952
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000953 (unwind-protect
954 ;; make sure current buffer is restored
955 ;; BAW - we want to check to see if this still applies
956 (progn
957 ;; mysterious ugly hack
958 (if (eq curbuf pbuf)
959 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000961 (set-buffer pbuf)
962 (let* ((start (point))
963 (goback (< start pmark))
964 (goend (and (not goback) (= start (point-max))))
965 (buffer-read-only nil))
966 (goto-char pmark)
967 (insert string)
968 (move-marker pmark (point))
969 (setq file-finished
970 (and py-file-queue
971 (equal ">>> "
972 (buffer-substring
973 (prog2 (beginning-of-line) (point)
974 (goto-char pmark))
975 (point)))))
976 (if goback (goto-char start)
977 ;; else
978 (if py-scroll-process-buffer
979 (let* ((pop-up-windows t)
980 (pwin (display-buffer pbuf)))
981 (set-window-point pwin (point)))))
982 (set-buffer curbuf)
983 (if file-finished
984 (progn
985 (py-delete-file-silently (car py-file-queue))
986 (setq py-file-queue (cdr py-file-queue))
987 (if py-file-queue
988 (py-execute-file pyproc (car py-file-queue)))))
989 (and goend
990 (progn (set-buffer pbuf)
991 (goto-char (point-max))))
992 ))
993 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000994
995(defun py-execute-buffer ()
996 "Send the contents of the buffer to a Python interpreter.
997If there is a *Python* process buffer it is used. If a clipping
998restriction is in effect, only the accessible portion of the buffer is
999sent. A trailing newline will be supplied if needed.
1000
1001See the `\\[py-execute-region]' docs for an account of some subtleties."
1002 (interactive)
1003 (py-execute-region (point-min) (point-max)))
1004
1005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001006
1007;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001008(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001009 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001010
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001012Deletion is performed by calling the function in `py-delete-function'
1013with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001014
1015Else if point is at the leftmost non-blank character of a line that is
1016neither a continuation line nor a non-indenting comment line, or if
1017point is at the end of a blank line, reduces the indentation to match
1018that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001019opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001020of where you are. With numeric count, outdents that many blocks (but
1021not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022
1023Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001024needed so that only a single column position is deleted. Numeric
1025argument delets that many characters."
1026 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027 (if (or (/= (current-indentation) (current-column))
1028 (bolp)
1029 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001030 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001031 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001032 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001033 ;; else indent the same as the colon line that opened the block
1034
1035 ;; force non-blank so py-goto-block-up doesn't ignore it
1036 (insert-char ?* 1)
1037 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001038 (let ((base-indent 0) ; indentation of base line
1039 (base-text "") ; and text of base line
1040 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001041 (save-excursion
1042 (while (< 0 count)
1043 (condition-case nil ; in case no enclosing block
1044 (progn
1045 (py-goto-block-up 'no-mark)
1046 (setq base-indent (current-indentation)
1047 base-text (py-suck-up-leading-text)
1048 base-found-p t))
1049 (error nil))
1050 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001051 (delete-char 1) ; toss the dummy character
1052 (delete-horizontal-space)
1053 (indent-to base-indent)
1054 (if base-found-p
1055 (message "Closes block: %s" base-text)))))
1056
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001057;; required for pending-del and delsel modes
1058(put 'py-delete-char 'delete-selection 'supersede)
1059(put 'py-delete-char 'pending-delete 'supersede)
1060
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001061(defun py-indent-line (&optional arg)
1062 "Fix the indentation of the current line according to Python rules.
1063With \\[universal-argument], ignore outdenting rules for block
1064closing statements (e.g. return, raise, break, continue, pass)
1065
1066This function is normally bound to `indent-line-function' so
1067\\[indent-for-tab-command] will call it."
1068 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 (let* ((ci (current-indentation))
1070 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001071 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001072 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001073 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001074 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075 (if (/= ci need)
1076 (save-excursion
1077 (beginning-of-line)
1078 (delete-horizontal-space)
1079 (indent-to need)))
1080 (if move-to-indentation-p (back-to-indentation))))
1081
1082(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084This is just `strives to' because correct indentation can't be computed
1085from scratch for Python code. In general, deletes the whitespace before
1086point, inserts a newline, and takes an educated guess as to how you want
1087the new line indented."
1088 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001089 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001090 (if (< ci (current-column)) ; if point beyond indentation
1091 (newline-and-indent)
1092 ;; else try to act like newline-and-indent "normally" acts
1093 (beginning-of-line)
1094 (insert-char ?\n 1)
1095 (move-to-column ci))))
1096
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001097(defun py-compute-indentation (honor-block-close-p)
1098 ;; implements all the rules for indentation computation. when
1099 ;; honor-block-close-p is non-nil, statements such as return, raise,
1100 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001101 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001102 (let ((pps (parse-partial-sexp (save-excursion
1103 (beginning-of-python-def-or-class)
1104 (point))
1105 (point))))
1106 (beginning-of-line)
1107 (cond
1108 ;; are we inside a string or comment?
1109 ((or (nth 3 pps) (nth 4 pps))
1110 (save-excursion
1111 (if (not py-align-multiline-strings-p) 0
1112 ;; skip back over blank & non-indenting comment lines
1113 ;; note: will skip a blank or non-indenting comment line
1114 ;; that happens to be a continuation line too
1115 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1116 (back-to-indentation)
1117 (current-column))))
1118 ;; are we on a continuation line?
1119 ((py-continuation-line-p)
1120 (let ((startpos (point))
1121 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001122 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001123 (if open-bracket-pos
1124 (progn
1125 ;; align with first item in list; else a normal
1126 ;; indent beyond the line with the open bracket
1127 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1128 ;; is the first list item on the same line?
1129 (skip-chars-forward " \t")
1130 (if (null (memq (following-char) '(?\n ?# ?\\)))
1131 ; yes, so line up with it
1132 (current-column)
1133 ;; first list item on another line, or doesn't exist yet
1134 (forward-line 1)
1135 (while (and (< (point) startpos)
1136 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1137 (forward-line 1))
1138 (if (< (point) startpos)
1139 ;; again mimic the first list item
1140 (current-indentation)
1141 ;; else they're about to enter the first item
1142 (goto-char open-bracket-pos)
1143 (+ (current-indentation) py-indent-offset))))
1144
1145 ;; else on backslash continuation line
1146 (forward-line -1)
1147 (if (py-continuation-line-p) ; on at least 3rd line in block
1148 (current-indentation) ; so just continue the pattern
1149 ;; else started on 2nd line in block, so indent more.
1150 ;; if base line is an assignment with a start on a RHS,
1151 ;; indent to 2 beyond the leftmost "="; else skip first
1152 ;; chunk of non-whitespace characters on base line, + 1 more
1153 ;; column
1154 (end-of-line)
1155 (setq endpos (point) searching t)
1156 (back-to-indentation)
1157 (setq startpos (point))
1158 ;; look at all "=" from left to right, stopping at first
1159 ;; one not nested in a list or string
1160 (while searching
1161 (skip-chars-forward "^=" endpos)
1162 (if (= (point) endpos)
1163 (setq searching nil)
1164 (forward-char 1)
1165 (setq state (parse-partial-sexp startpos (point)))
1166 (if (and (zerop (car state)) ; not in a bracket
1167 (null (nth 3 state))) ; & not in a string
1168 (progn
1169 (setq searching nil) ; done searching in any case
1170 (setq found
1171 (not (or
1172 (eq (following-char) ?=)
1173 (memq (char-after (- (point) 2))
1174 '(?< ?> ?!)))))))))
1175 (if (or (not found) ; not an assignment
1176 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1177 (progn
1178 (goto-char startpos)
1179 (skip-chars-forward "^ \t\n")))
1180 (1+ (current-column))))))
1181
1182 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001183 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001184
Barry Warsawa7891711996-08-01 15:53:09 +00001185 ;; Dfn: "Indenting comment line". A line containing only a
1186 ;; comment, but which is treated like a statement for
1187 ;; indentation calculation purposes. Such lines are only
1188 ;; treated specially by the mode; they are not treated
1189 ;; specially by the Python interpreter.
1190
1191 ;; The rules for indenting comment lines are a line where:
1192 ;; - the first non-whitespace character is `#', and
1193 ;; - the character following the `#' is whitespace, and
1194 ;; - the line is outdented with respect to (i.e. to the left
1195 ;; of) the indentation of the preceding non-blank line.
1196
1197 ;; The first non-blank line following an indenting comment
1198 ;; line is given the same amount of indentation as the
1199 ;; indenting comment line.
1200
1201 ;; All other comment-only lines are ignored for indentation
1202 ;; purposes.
1203
1204 ;; Are we looking at a comment-only line which is *not* an
1205 ;; indenting comment line? If so, we assume that its been
1206 ;; placed at the desired indentation, so leave it alone.
1207 ;; Indenting comment lines are aligned as statements down
1208 ;; below.
1209 ((and (looking-at "[ \t]*#[^ \t\n]")
1210 ;; NOTE: this test will not be performed in older Emacsen
1211 (fboundp 'forward-comment)
1212 (<= (current-indentation)
1213 (save-excursion
1214 (forward-comment (- (point-max)))
1215 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001216 (current-indentation))
1217
1218 ;; else indentation based on that of the statement that
1219 ;; precedes us; use the first line of that statement to
1220 ;; establish the base, in case the user forced a non-std
1221 ;; indentation for the continuation lines (if any)
1222 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001223 ;; skip back over blank & non-indenting comment lines note:
1224 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001225 ;; happens to be a continuation line too. use fast Emacs 19
1226 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001227 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001228 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001229 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001230 (let (done)
1231 (while (not done)
1232 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1233 nil 'move)
1234 (setq done (or (eq py-honor-comment-indentation t)
1235 (bobp)
1236 (/= (following-char) ?#)
1237 (not (zerop (current-column)))))
1238 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001239 ;; if we landed inside a string, go to the beginning of that
1240 ;; string. this handles triple quoted, multi-line spanning
1241 ;; strings.
1242 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001243 (+ (current-indentation)
1244 (if (py-statement-opens-block-p)
1245 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001246 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001247 (- py-indent-offset)
1248 0)))
1249 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001250
1251(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001252 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001253By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001254`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001255Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001256`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257their own buffer-local copy), both those currently existing and those
1258created later in the Emacs session.
1259
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001260Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001261There's no excuse for such foolishness, but sometimes you have to deal
1262with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001263`py-indent-offset' to what it thinks it was when they created the
1264mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001265
1266Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001267looking for a line that opens a block of code. `py-indent-offset' is
1268set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001269statement following it. If the search doesn't succeed going forward,
1270it's tried again going backward."
1271 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001272 (let (new-value
1273 (start (point))
1274 restart
1275 (found nil)
1276 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277 (py-goto-initial-line)
1278 (while (not (or found (eobp)))
1279 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1280 (progn
1281 (setq restart (point))
1282 (py-goto-initial-line)
1283 (if (py-statement-opens-block-p)
1284 (setq found t)
1285 (goto-char restart)))))
1286 (if found
1287 ()
1288 (goto-char start)
1289 (py-goto-initial-line)
1290 (while (not (or found (bobp)))
1291 (setq found
1292 (and
1293 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1294 (or (py-goto-initial-line) t) ; always true -- side effect
1295 (py-statement-opens-block-p)))))
1296 (setq colon-indent (current-indentation)
1297 found (and found (zerop (py-next-statement 1)))
1298 new-value (- (current-indentation) colon-indent))
1299 (goto-char start)
1300 (if found
1301 (progn
1302 (funcall (if global 'kill-local-variable 'make-local-variable)
1303 'py-indent-offset)
1304 (setq py-indent-offset new-value)
1305 (message "%s value of py-indent-offset set to %d"
1306 (if global "Global" "Local")
1307 py-indent-offset))
1308 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1309
1310(defun py-shift-region (start end count)
1311 (save-excursion
1312 (goto-char end) (beginning-of-line) (setq end (point))
1313 (goto-char start) (beginning-of-line) (setq start (point))
1314 (indent-rigidly start end count)))
1315
1316(defun py-shift-region-left (start end &optional count)
1317 "Shift region of Python code to the left.
1318The lines from the line containing the start of the current region up
1319to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001320shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001321
1322If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001323many columns. With no active region, outdent only the current line.
1324You cannot outdent the region if any line is already at column zero."
1325 (interactive
1326 (let ((p (point))
1327 (m (mark))
1328 (arg current-prefix-arg))
1329 (if m
1330 (list (min p m) (max p m) arg)
1331 (list p (save-excursion (forward-line 1) (point)) arg))))
1332 ;; if any line is at column zero, don't shift the region
1333 (save-excursion
1334 (goto-char start)
1335 (while (< (point) end)
1336 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001337 (if (and (zerop (current-column))
1338 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001339 (error "Region is at left edge."))
1340 (forward-line 1)))
1341 (py-shift-region start end (- (prefix-numeric-value
1342 (or count py-indent-offset))))
1343 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001344
1345(defun py-shift-region-right (start end &optional count)
1346 "Shift region of Python code to the right.
1347The 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
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001349shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001350
1351If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001352many columns. With no active region, indent only the current line."
1353 (interactive
1354 (let ((p (point))
1355 (m (mark))
1356 (arg current-prefix-arg))
1357 (if m
1358 (list (min p m) (max p m) arg)
1359 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001360 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001361 (or count py-indent-offset)))
1362 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001363
1364(defun py-indent-region (start end &optional indent-offset)
1365 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001366
Barry Warsaw7ae77681994-12-12 20:38:05 +00001367The lines from the line containing the start of the current region up
1368to (but not including) the line containing the end of the region are
1369reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001370character in the first column, the first line is left alone and the
1371rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001372region is reindented with respect to the (closest code or indenting
1373comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001374
1375This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001376control structures are introduced or removed, or to reformat code
1377using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001378
1379If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001380the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001381used.
1382
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001383Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384is called! This function does not compute proper indentation from
1385scratch (that's impossible in Python), it merely adjusts the existing
1386indentation to be correct in context.
1387
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001388Warning: This function really has no idea what to do with
1389non-indenting comment lines, and shifts them as if they were indenting
1390comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001391
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392Special cases: whitespace is deleted from blank lines; continuation
1393lines are shifted by the same amount their initial line was shifted,
1394in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001395initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001396 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001397 (save-excursion
1398 (goto-char end) (beginning-of-line) (setq end (point-marker))
1399 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001400 (let ((py-indent-offset (prefix-numeric-value
1401 (or indent-offset py-indent-offset)))
1402 (indents '(-1)) ; stack of active indent levels
1403 (target-column 0) ; column to which to indent
1404 (base-shifted-by 0) ; amount last base line was shifted
1405 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001406 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001407 0))
1408 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001409 (while (< (point) end)
1410 (setq ci (current-indentation))
1411 ;; figure out appropriate target column
1412 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001413 ((or (eq (following-char) ?#) ; comment in column 1
1414 (looking-at "[ \t]*$")) ; entirely blank
1415 (setq target-column 0))
1416 ((py-continuation-line-p) ; shift relative to base line
1417 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418 (t ; new base line
1419 (if (> ci (car indents)) ; going deeper; push it
1420 (setq indents (cons ci indents))
1421 ;; else we should have seen this indent before
1422 (setq indents (memq ci indents)) ; pop deeper indents
1423 (if (null indents)
1424 (error "Bad indentation in region, at line %d"
1425 (save-restriction
1426 (widen)
1427 (1+ (count-lines 1 (point)))))))
1428 (setq target-column (+ indent-base
1429 (* py-indent-offset
1430 (- (length indents) 2))))
1431 (setq base-shifted-by (- target-column ci))))
1432 ;; shift as needed
1433 (if (/= ci target-column)
1434 (progn
1435 (delete-horizontal-space)
1436 (indent-to target-column)))
1437 (forward-line 1))))
1438 (set-marker end nil))
1439
Barry Warsawa7891711996-08-01 15:53:09 +00001440(defun py-comment-region (beg end &optional arg)
1441 "Like `comment-region' but uses double hash (`#') comment starter."
1442 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001443 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001444 (comment-region beg end arg)))
1445
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001446
1447;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001448(defun py-previous-statement (count)
1449 "Go to the start of previous Python statement.
1450If the statement at point is the i'th Python statement, goes to the
1451start of statement i-COUNT. If there is no such statement, goes to the
1452first statement. Returns count of statements left to move.
1453`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001454 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455 (if (< count 0) (py-next-statement (- count))
1456 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001458 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001459 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001460 (> count 0)
1461 (zerop (forward-line -1))
1462 (py-goto-statement-at-or-above))
1463 (setq count (1- count)))
1464 (if (> count 0) (goto-char start)))
1465 count))
1466
1467(defun py-next-statement (count)
1468 "Go to the start of next Python statement.
1469If the statement at point is the i'th Python statement, goes to the
1470start of statement i+COUNT. If there is no such statement, goes to the
1471last statement. Returns count of statements left to move. `Statements'
1472do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001473 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001474 (if (< count 0) (py-previous-statement (- count))
1475 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001476 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001477 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001478 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001479 (> count 0)
1480 (py-goto-statement-below))
1481 (setq count (1- count)))
1482 (if (> count 0) (goto-char start)))
1483 count))
1484
1485(defun py-goto-block-up (&optional nomark)
1486 "Move up to start of current block.
1487Go to the statement that starts the smallest enclosing block; roughly
1488speaking, this will be the closest preceding statement that ends with a
1489colon and is indented less than the statement you started on. If
1490successful, also sets the mark to the starting point.
1491
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492`\\[py-mark-block]' can be used afterward to mark the whole code
1493block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001494
1495If called from a program, the mark will not be set if optional argument
1496NOMARK is not nil."
1497 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001498 (let ((start (point))
1499 (found nil)
1500 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001501 (py-goto-initial-line)
1502 ;; if on blank or non-indenting comment line, use the preceding stmt
1503 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1504 (progn
1505 (py-goto-statement-at-or-above)
1506 (setq found (py-statement-opens-block-p))))
1507 ;; search back for colon line indented less
1508 (setq initial-indent (current-indentation))
1509 (if (zerop initial-indent)
1510 ;; force fast exit
1511 (goto-char (point-min)))
1512 (while (not (or found (bobp)))
1513 (setq found
1514 (and
1515 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1516 (or (py-goto-initial-line) t) ; always true -- side effect
1517 (< (current-indentation) initial-indent)
1518 (py-statement-opens-block-p))))
1519 (if found
1520 (progn
1521 (or nomark (push-mark start))
1522 (back-to-indentation))
1523 (goto-char start)
1524 (error "Enclosing block not found"))))
1525
1526(defun beginning-of-python-def-or-class (&optional class)
1527 "Move point to start of def (or class, with prefix arg).
1528
1529Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001530arg, looks for a `class' instead. The docs assume the `def' case;
1531just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001532
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001533If point is in a def statement already, and after the `d', simply
1534moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001535
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001536Else (point is not in a def statement, or at or before the `d' of a
1537def statement), searches for the closest preceding def statement, and
1538leaves point at its start. If no such statement can be found, leaves
1539point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540
1541Returns t iff a def statement is found by these rules.
1542
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001543Note that doing this command repeatedly will take you closer to the
1544start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546If you want to mark the current def/class, see
1547`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001549 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1550 (start-of-line (progn (beginning-of-line) (point)))
1551 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552 (if (or (/= start-of-stmt start-of-line)
1553 (not at-or-before-p))
1554 (end-of-line)) ; OK to match on this line
1555 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001557
1558(defun end-of-python-def-or-class (&optional class)
1559 "Move point beyond end of def (or class, with prefix arg) body.
1560
1561By default, looks for an appropriate `def'. If you supply a prefix arg,
1562looks for a `class' instead. The docs assume the `def' case; just
1563substitute `class' for `def' for the other case.
1564
1565If point is in a def statement already, this is the def we use.
1566
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001567Else if the def found by `\\[beginning-of-python-def-or-class]'
1568contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569
1570Else we search forward for the closest following def, and use that.
1571
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001572If a def can be found by these rules, point is moved to the start of
1573the line immediately following the def block, and the position of the
1574start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001575
1576Else point is moved to the end of the buffer, and nil is returned.
1577
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001578Note that doing this command repeatedly will take you closer to the
1579end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001580
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001581If you want to mark the current def/class, see
1582`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001583 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001584 (let ((start (progn (py-goto-initial-line) (point)))
1585 (which (if class "class" "def"))
1586 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001587 ;; move point to start of appropriate def/class
1588 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1589 (setq state 'at-beginning)
1590 ;; else see if beginning-of-python-def-or-class hits container
1591 (if (and (beginning-of-python-def-or-class class)
1592 (progn (py-goto-beyond-block)
1593 (> (point) start)))
1594 (setq state 'at-end)
1595 ;; else search forward
1596 (goto-char start)
1597 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1598 (progn (setq state 'at-beginning)
1599 (beginning-of-line)))))
1600 (cond
1601 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1602 ((eq state 'at-end) t)
1603 ((eq state 'not-found) nil)
1604 (t (error "internal error in end-of-python-def-or-class")))))
1605
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001606
1607;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001608(defun py-mark-block (&optional extend just-move)
1609 "Mark following block of lines. With prefix arg, mark structure.
1610Easier to use than explain. It sets the region to an `interesting'
1611block of succeeding lines. If point is on a blank line, it goes down to
1612the next non-blank line. That will be the start of the region. The end
1613of the region depends on the kind of line at the start:
1614
1615 - If a comment, the region will include all succeeding comment lines up
1616 to (but not including) the next non-comment line (if any).
1617
1618 - Else if a prefix arg is given, and the line begins one of these
1619 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001620
1621 if elif else try except finally for while def class
1622
Barry Warsaw7ae77681994-12-12 20:38:05 +00001623 the region will be set to the body of the structure, including
1624 following blocks that `belong' to it, but excluding trailing blank
1625 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001626 and all (if any) of the following `except' and `finally' blocks
1627 that belong to the `try' structure will be in the region. Ditto
1628 for if/elif/else, for/else and while/else structures, and (a bit
1629 degenerate, since they're always one-block structures) def and
1630 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001631
1632 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001633 block (see list above), and the block is not a `one-liner' (i.e.,
1634 the statement ends with a colon, not with code), the region will
1635 include all succeeding lines up to (but not including) the next
1636 code statement (if any) that's indented no more than the starting
1637 line, except that trailing blank and comment lines are excluded.
1638 E.g., if the starting line begins a multi-statement `def'
1639 structure, the region will be set to the full function definition,
1640 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641
1642 - Else the region will include all succeeding lines up to (but not
1643 including) the next blank line, or code or indenting-comment line
1644 indented strictly less than the starting line. Trailing indenting
1645 comment lines are included in this case, but not trailing blank
1646 lines.
1647
1648A msg identifying the location of the mark is displayed in the echo
1649area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1650
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001651If called from a program, optional argument EXTEND plays the role of
1652the prefix arg, and if optional argument JUST-MOVE is not nil, just
1653moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654 (interactive "P") ; raw prefix arg
1655 (py-goto-initial-line)
1656 ;; skip over blank lines
1657 (while (and
1658 (looking-at "[ \t]*$") ; while blank line
1659 (not (eobp))) ; & somewhere to go
1660 (forward-line 1))
1661 (if (eobp)
1662 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001663 (let ((initial-pos (point))
1664 (initial-indent (current-indentation))
1665 last-pos ; position of last stmt in region
1666 (followers
1667 '((if elif else) (elif elif else) (else)
1668 (try except finally) (except except) (finally)
1669 (for else) (while else)
1670 (def) (class) ) )
1671 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001672
1673 (cond
1674 ;; if comment line, suck up the following comment lines
1675 ((looking-at "[ \t]*#")
1676 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1677 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1678 (setq last-pos (point)))
1679
1680 ;; else if line is a block line and EXTEND given, suck up
1681 ;; the whole structure
1682 ((and extend
1683 (setq first-symbol (py-suck-up-first-keyword) )
1684 (assq first-symbol followers))
1685 (while (and
1686 (or (py-goto-beyond-block) t) ; side effect
1687 (forward-line -1) ; side effect
1688 (setq last-pos (point)) ; side effect
1689 (py-goto-statement-below)
1690 (= (current-indentation) initial-indent)
1691 (setq next-symbol (py-suck-up-first-keyword))
1692 (memq next-symbol (cdr (assq first-symbol followers))))
1693 (setq first-symbol next-symbol)))
1694
1695 ;; else if line *opens* a block, search for next stmt indented <=
1696 ((py-statement-opens-block-p)
1697 (while (and
1698 (setq last-pos (point)) ; always true -- side effect
1699 (py-goto-statement-below)
1700 (> (current-indentation) initial-indent))
1701 nil))
1702
1703 ;; else plain code line; stop at next blank line, or stmt or
1704 ;; indenting comment line indented <
1705 (t
1706 (while (and
1707 (setq last-pos (point)) ; always true -- side effect
1708 (or (py-goto-beyond-final-line) t)
1709 (not (looking-at "[ \t]*$")) ; stop at blank line
1710 (or
1711 (>= (current-indentation) initial-indent)
1712 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1713 nil)))
1714
1715 ;; skip to end of last stmt
1716 (goto-char last-pos)
1717 (py-goto-beyond-final-line)
1718
1719 ;; set mark & display
1720 (if just-move
1721 () ; just return
1722 (push-mark (point) 'no-msg)
1723 (forward-line -1)
1724 (message "Mark set after: %s" (py-suck-up-leading-text))
1725 (goto-char initial-pos))))
1726
1727(defun mark-python-def-or-class (&optional class)
1728 "Set region to body of def (or class, with prefix arg) enclosing point.
1729Pushes the current mark, then point, on the mark ring (all language
1730modes do this, but although it's handy it's never documented ...).
1731
1732In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001733hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1734`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001735
1736And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001737Turned out that was more confusing than useful: the `goto start' and
1738`goto end' commands are usually used to search through a file, and
1739people expect them to act a lot like `search backward' and `search
1740forward' string-search commands. But because Python `def' and `class'
1741can nest to arbitrary levels, finding the smallest def containing
1742point cannot be done via a simple backward search: the def containing
1743point may not be the closest preceding def, or even the closest
1744preceding def that's indented less. The fancy algorithm required is
1745appropriate for the usual uses of this `mark' command, but not for the
1746`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001747
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001748So the def marked by this command may not be the one either of the
1749`goto' commands find: If point is on a blank or non-indenting comment
1750line, moves back to start of the closest preceding code statement or
1751indenting comment line. If this is a `def' statement, that's the def
1752we use. Else searches for the smallest enclosing `def' block and uses
1753that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755When an enclosing def is found: The mark is left immediately beyond
1756the last line of the def block. Point is left at the start of the
1757def, except that: if the def is preceded by a number of comment lines
1758followed by (at most) one optional blank line, point is left at the
1759start of the comments; else if the def is preceded by a blank line,
1760point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001761
1762The intent is to mark the containing def/class and its associated
1763documentation, to make moving and duplicating functions and classes
1764pleasant."
1765 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001766 (let ((start (point))
1767 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768 (push-mark start)
1769 (if (not (py-go-up-tree-to-keyword which))
1770 (progn (goto-char start)
1771 (error "Enclosing %s not found" which))
1772 ;; else enclosing def/class found
1773 (setq start (point))
1774 (py-goto-beyond-block)
1775 (push-mark (point))
1776 (goto-char start)
1777 (if (zerop (forward-line -1)) ; if there is a preceding line
1778 (progn
1779 (if (looking-at "[ \t]*$") ; it's blank
1780 (setq start (point)) ; so reset start point
1781 (goto-char start)) ; else try again
1782 (if (zerop (forward-line -1))
1783 (if (looking-at "[ \t]*#") ; a comment
1784 ;; look back for non-comment line
1785 ;; tricky: note that the regexp matches a blank
1786 ;; line, cuz \n is in the 2nd character class
1787 (and
1788 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1789 (forward-line 1))
1790 ;; no comment, so go back
1791 (goto-char start))))))))
1792
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001793;; ripped from cc-mode
1794(defun py-forward-into-nomenclature (&optional arg)
1795 "Move forward to end of a nomenclature section or word.
1796With arg, to it arg times.
1797
1798A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1799 (interactive "p")
1800 (let ((case-fold-search nil))
1801 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001802 (re-search-forward
1803 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1804 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001805 (while (and (< arg 0)
1806 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001807 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001808 (point-min) 0))
1809 (forward-char 1)
1810 (setq arg (1+ arg)))))
1811 (py-keep-region-active))
1812
1813(defun py-backward-into-nomenclature (&optional arg)
1814 "Move backward to beginning of a nomenclature section or word.
1815With optional ARG, move that many times. If ARG is negative, move
1816forward.
1817
1818A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1819 (interactive "p")
1820 (py-forward-into-nomenclature (- arg))
1821 (py-keep-region-active))
1822
1823
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001824
1825;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826
1827;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001828;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1829;; out of the right places, along with the keys they're on & current
1830;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001831(defun py-dump-help-string (str)
1832 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833 (let ((locals (buffer-local-variables))
1834 funckind funcname func funcdoc
1835 (start 0) mstart end
1836 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001837 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1838 (setq mstart (match-beginning 0) end (match-end 0)
1839 funckind (substring str (match-beginning 1) (match-end 1))
1840 funcname (substring str (match-beginning 2) (match-end 2))
1841 func (intern funcname))
1842 (princ (substitute-command-keys (substring str start mstart)))
1843 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001844 ((equal funckind "c") ; command
1845 (setq funcdoc (documentation func)
1846 keys (concat
1847 "Key(s): "
1848 (mapconcat 'key-description
1849 (where-is-internal func py-mode-map)
1850 ", "))))
1851 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001852 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853 keys (if (assq func locals)
1854 (concat
1855 "Local/Global values: "
1856 (prin1-to-string (symbol-value func))
1857 " / "
1858 (prin1-to-string (default-value func)))
1859 (concat
1860 "Value: "
1861 (prin1-to-string (symbol-value func))))))
1862 (t ; unexpected
1863 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864 (princ (format "\n-> %s:\t%s\t%s\n\n"
1865 (if (equal funckind "c") "Command" "Variable")
1866 funcname keys))
1867 (princ funcdoc)
1868 (terpri)
1869 (setq start end))
1870 (princ (substitute-command-keys (substring str start))))
1871 (print-help-return-message)))
1872
1873(defun py-describe-mode ()
1874 "Dump long form of Python-mode docs."
1875 (interactive)
1876 (py-dump-help-string "Major mode for editing Python files.
1877Knows about Python indentation, tokens, comments and continuation lines.
1878Paragraphs are separated by blank lines only.
1879
1880Major sections below begin with the string `@'; specific function and
1881variable docs begin with `->'.
1882
1883@EXECUTING PYTHON CODE
1884
1885\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1886\\[py-execute-region]\tsends the current region
1887\\[py-shell]\tstarts a Python interpreter window; this will be used by
1888\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1889%c:py-execute-buffer
1890%c:py-execute-region
1891%c:py-shell
1892
1893@VARIABLES
1894
1895py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001896py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001897
1898py-python-command\tshell command to invoke Python interpreter
1899py-scroll-process-buffer\talways scroll Python process buffer
1900py-temp-directory\tdirectory used for temp files (if needed)
1901
1902py-beep-if-tab-change\tring the bell if tab-width is changed
1903%v:py-indent-offset
1904%v:py-block-comment-prefix
1905%v:py-python-command
1906%v:py-scroll-process-buffer
1907%v:py-temp-directory
1908%v:py-beep-if-tab-change
1909
1910@KINDS OF LINES
1911
1912Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001913preceding line ends with a backslash that's not part of a comment, or
1914the paren/bracket/brace nesting level at the start of the line is
1915non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001916
1917An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918possibly blanks or tabs), a `comment line' (leftmost non-blank
1919character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001920
1921Comment Lines
1922
1923Although all comment lines are treated alike by Python, Python mode
1924recognizes two kinds that act differently with respect to indentation.
1925
1926An `indenting comment line' is a comment line with a blank, tab or
1927nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001928treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929indenting comment line will be indented like the comment line. All
1930other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001931following the initial `#') are `non-indenting comment lines', and
1932their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001933
1934Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001935whenever possible. Non-indenting comment lines are useful in cases
1936like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937
1938\ta = b # a very wordy single-line comment that ends up being
1939\t #... continued onto another line
1940
1941\tif a == b:
1942##\t\tprint 'panic!' # old code we've `commented out'
1943\t\treturn a
1944
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945Since the `#...' and `##' comment lines have a non-whitespace
1946character following the initial `#', Python mode ignores them when
1947computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948
1949Continuation Lines and Statements
1950
1951The Python-mode commands generally work on statements instead of on
1952individual lines, where a `statement' is a comment or blank line, or a
1953code line and all of its following continuation lines (if any)
1954considered as a single logical unit. The commands in this mode
1955generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001956statement containing point, even if point happens to be in the middle
1957of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958
1959
1960@INDENTATION
1961
1962Primarily for entering new code:
1963\t\\[indent-for-tab-command]\t indent line appropriately
1964\t\\[py-newline-and-indent]\t insert newline, then indent
1965\t\\[py-delete-char]\t reduce indentation, or delete single character
1966
1967Primarily for reindenting existing code:
1968\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1969\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1970
1971\t\\[py-indent-region]\t reindent region to match its context
1972\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1973\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1974
1975Unlike most programming languages, Python uses indentation, and only
1976indentation, to specify block structure. Hence the indentation supplied
1977automatically by Python-mode is just an educated guess: only you know
1978the block structure you intend, so only you can supply correct
1979indentation.
1980
1981The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1982the indentation of preceding statements. E.g., assuming
1983py-indent-offset is 4, after you enter
1984\tif a > 0: \\[py-newline-and-indent]
1985the cursor will be moved to the position of the `_' (_ is not a
1986character in the file, it's just used here to indicate the location of
1987the cursor):
1988\tif a > 0:
1989\t _
1990If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1991to
1992\tif a > 0:
1993\t c = d
1994\t _
1995Python-mode cannot know whether that's what you intended, or whether
1996\tif a > 0:
1997\t c = d
1998\t_
1999was your intent. In general, Python-mode either reproduces the
2000indentation of the (closest code or indenting-comment) preceding
2001statement, or adds an extra py-indent-offset blanks if the preceding
2002statement has `:' as its last significant (non-whitespace and non-
2003comment) character. If the suggested indentation is too much, use
2004\\[py-delete-char] to reduce it.
2005
2006Continuation lines are given extra indentation. If you don't like the
2007suggested indentation, change it to something you do like, and Python-
2008mode will strive to indent later lines of the statement in the same way.
2009
2010If a line is a continuation line by virtue of being in an unclosed
2011paren/bracket/brace structure (`list', for short), the suggested
2012indentation depends on whether the current line contains the first item
2013in the list. If it does, it's indented py-indent-offset columns beyond
2014the indentation of the line containing the open bracket. If you don't
2015like that, change it by hand. The remaining items in the list will mimic
2016whatever indentation you give to the first item.
2017
2018If a line is a continuation line because the line preceding it ends with
2019a backslash, the third and following lines of the statement inherit their
2020indentation from the line preceding them. The indentation of the second
2021line in the statement depends on the form of the first (base) line: if
2022the base line is an assignment statement with anything more interesting
2023than the backslash following the leftmost assigning `=', the second line
2024is indented two columns beyond that `='. Else it's indented to two
2025columns beyond the leftmost solid chunk of non-whitespace characters on
2026the base line.
2027
2028Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2029repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2030structure you intend.
2031%c:indent-for-tab-command
2032%c:py-newline-and-indent
2033%c:py-delete-char
2034
2035
2036The next function may be handy when editing code you didn't write:
2037%c:py-guess-indent-offset
2038
2039
2040The remaining `indent' functions apply to a region of Python code. They
2041assume the block structure (equals indentation, in Python) of the region
2042is correct, and alter the indentation in various ways while preserving
2043the block structure:
2044%c:py-indent-region
2045%c:py-shift-region-left
2046%c:py-shift-region-right
2047
2048@MARKING & MANIPULATING REGIONS OF CODE
2049
2050\\[py-mark-block]\t mark block of lines
2051\\[mark-python-def-or-class]\t mark smallest enclosing def
2052\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002053\\[comment-region]\t comment out region of code
2054\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002055%c:py-mark-block
2056%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002057%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002058
2059@MOVING POINT
2060
2061\\[py-previous-statement]\t move to statement preceding point
2062\\[py-next-statement]\t move to statement following point
2063\\[py-goto-block-up]\t move up to start of current block
2064\\[beginning-of-python-def-or-class]\t move to start of def
2065\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2066\\[end-of-python-def-or-class]\t move to end of def
2067\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2068
2069The first two move to one statement beyond the statement that contains
2070point. A numeric prefix argument tells them to move that many
2071statements instead. Blank lines, comment lines, and continuation lines
2072do not count as `statements' for these commands. So, e.g., you can go
2073to the first code statement in a file by entering
2074\t\\[beginning-of-buffer]\t to move to the top of the file
2075\t\\[py-next-statement]\t to skip over initial comments and blank lines
2076Or do `\\[py-previous-statement]' with a huge prefix argument.
2077%c:py-previous-statement
2078%c:py-next-statement
2079%c:py-goto-block-up
2080%c:beginning-of-python-def-or-class
2081%c:end-of-python-def-or-class
2082
2083@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2084
2085`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2086
2087`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2088overall class and def structure of a module.
2089
2090`\\[back-to-indentation]' moves point to a line's first non-blank character.
2091
2092`\\[indent-relative]' is handy for creating odd indentation.
2093
2094@OTHER EMACS HINTS
2095
2096If you don't like the default value of a variable, change its value to
2097whatever you do like by putting a `setq' line in your .emacs file.
2098E.g., to set the indentation increment to 4, put this line in your
2099.emacs:
2100\t(setq py-indent-offset 4)
2101To see the value of a variable, do `\\[describe-variable]' and enter the variable
2102name at the prompt.
2103
2104When entering a key sequence like `C-c C-n', it is not necessary to
2105release the CONTROL key after doing the `C-c' part -- it suffices to
2106press the CONTROL key, press and release `c' (while still holding down
2107CONTROL), press and release `n' (while still holding down CONTROL), &
2108then release CONTROL.
2109
2110Entering Python mode calls with no arguments the value of the variable
2111`python-mode-hook', if that value exists and is not nil; for backward
2112compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2113the Elisp manual for details.
2114
2115Obscure: When python-mode is first loaded, it looks for all bindings
2116to newline-and-indent in the global keymap, and shadows them with
2117local bindings to py-newline-and-indent."))
2118
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002119
2120;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002121(defvar py-parse-state-re
2122 (concat
2123 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2124 "\\|"
2125 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002126
Barry Warsaw7ae77681994-12-12 20:38:05 +00002127;; returns the parse state at point (see parse-partial-sexp docs)
2128(defun py-parse-state ()
2129 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002130 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002131 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002132 (while (not done)
2133 ;; back up to the first preceding line (if any; else start of
2134 ;; buffer) that begins with a popular Python keyword, or a
2135 ;; non- whitespace and non-comment character. These are good
2136 ;; places to start parsing to see whether where we started is
2137 ;; at a non-zero nesting level. It may be slow for people who
2138 ;; write huge code blocks or huge lists ... tough beans.
2139 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002140 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002141 (beginning-of-line)
2142 (save-excursion
2143 (setq pps (parse-partial-sexp (point) here)))
2144 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002145 (setq done (or (zerop ci)
2146 (not (nth 3 pps))
2147 (bobp)))
2148 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002149 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002150
2151;; if point is at a non-zero nesting level, returns the number of the
2152;; character that opens the smallest enclosing unclosed list; else
2153;; returns nil.
2154(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002155 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156 (if (zerop (car status))
2157 nil ; not in a nest
2158 (car (cdr status))))) ; char# of open bracket
2159
2160;; t iff preceding line ends with backslash that's not in a comment
2161(defun py-backslash-continuation-line-p ()
2162 (save-excursion
2163 (beginning-of-line)
2164 (and
2165 ;; use a cheap test first to avoid the regexp if possible
2166 ;; use 'eq' because char-after may return nil
2167 (eq (char-after (- (point) 2)) ?\\ )
2168 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002169 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170 (looking-at py-continued-re))))
2171
2172;; t iff current line is a continuation line
2173(defun py-continuation-line-p ()
2174 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002175 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002176 (or (py-backslash-continuation-line-p)
2177 (py-nesting-level))))
2178
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002179;; go to initial line of current statement; usually this is the line
2180;; we're on, but if we're on the 2nd or following lines of a
2181;; continuation block, we need to go up to the first line of the
2182;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002184;; Tricky: We want to avoid quadratic-time behavior for long continued
2185;; blocks, whether of the backslash or open-bracket varieties, or a
2186;; mix of the two. The following manages to do that in the usual
2187;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002188(defun py-goto-initial-line ()
2189 (let ( open-bracket-pos )
2190 (while (py-continuation-line-p)
2191 (beginning-of-line)
2192 (if (py-backslash-continuation-line-p)
2193 (while (py-backslash-continuation-line-p)
2194 (forward-line -1))
2195 ;; else zip out of nested brackets/braces/parens
2196 (while (setq open-bracket-pos (py-nesting-level))
2197 (goto-char open-bracket-pos)))))
2198 (beginning-of-line))
2199
2200;; go to point right beyond final line of current statement; usually
2201;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002202;; statement we need to skip over the continuation lines. Tricky:
2203;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002204(defun py-goto-beyond-final-line ()
2205 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002206 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002207 (while (and (py-continuation-line-p)
2208 (not (eobp)))
2209 ;; skip over the backslash flavor
2210 (while (and (py-backslash-continuation-line-p)
2211 (not (eobp)))
2212 (forward-line 1))
2213 ;; if in nest, zip to the end of the nest
2214 (setq state (py-parse-state))
2215 (if (and (not (zerop (car state)))
2216 (not (eobp)))
2217 (progn
Barry Warsawf7705781997-01-30 19:49:39 +00002218 (parse-partial-sexp (point) (point-max)
2219 (if py-parse-partial-sexp-works-p
2220 0 (- 0 (car state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002221 nil state)
2222 (forward-line 1))))))
2223
2224;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002225;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226(defun py-statement-opens-block-p ()
2227 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002228 (let ((start (point))
2229 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2230 (searching t)
2231 (answer nil)
2232 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233 (goto-char start)
2234 (while searching
2235 ;; look for a colon with nothing after it except whitespace, and
2236 ;; maybe a comment
2237 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2238 finish t)
2239 (if (eq (point) finish) ; note: no `else' clause; just
2240 ; keep searching if we're not at
2241 ; the end yet
2242 ;; sure looks like it opens a block -- but it might
2243 ;; be in a comment
2244 (progn
2245 (setq searching nil) ; search is done either way
2246 (setq state (parse-partial-sexp start
2247 (match-beginning 0)))
2248 (setq answer (not (nth 4 state)))))
2249 ;; search failed: couldn't find another interesting colon
2250 (setq searching nil)))
2251 answer)))
2252
Barry Warsawf831d811996-07-31 20:42:59 +00002253(defun py-statement-closes-block-p ()
2254 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002255 ;; starts with `return', `raise', `break', `continue', and `pass'.
2256 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002257 (let ((here (point)))
2258 (back-to-indentation)
2259 (prog1
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002260 (looking-at "\\(return\\|raise\\|break\\|continue\\|pass\\)\\>")
Barry Warsawf831d811996-07-31 20:42:59 +00002261 (goto-char here))))
2262
Barry Warsaw7ae77681994-12-12 20:38:05 +00002263;; go to point right beyond final line of block begun by the current
2264;; line. This is the same as where py-goto-beyond-final-line goes
2265;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002266;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002267(defun py-goto-beyond-block ()
2268 (if (py-statement-opens-block-p)
2269 (py-mark-block nil 'just-move)
2270 (py-goto-beyond-final-line)))
2271
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002272;; go to start of first statement (not blank or comment or
2273;; continuation line) at or preceding point. returns t if there is
2274;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002275(defun py-goto-statement-at-or-above ()
2276 (py-goto-initial-line)
2277 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002278 ;; skip back over blank & comment lines
2279 ;; note: will skip a blank or comment line that happens to be
2280 ;; a continuation line too
2281 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2282 (progn (py-goto-initial-line) t)
2283 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002284 t))
2285
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002286;; go to start of first statement (not blank or comment or
2287;; continuation line) following the statement containing point returns
2288;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002289(defun py-goto-statement-below ()
2290 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002291 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002292 (py-goto-beyond-final-line)
2293 (while (and
2294 (looking-at py-blank-or-comment-re)
2295 (not (eobp)))
2296 (forward-line 1))
2297 (if (eobp)
2298 (progn (goto-char start) nil)
2299 t)))
2300
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301;; go to start of statement, at or preceding point, starting with
2302;; keyword KEY. Skips blank lines and non-indenting comments upward
2303;; first. If that statement starts with KEY, done, else go back to
2304;; first enclosing block starting with KEY. If successful, leaves
2305;; point at the start of the KEY line & returns t. Else leaves point
2306;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002307(defun py-go-up-tree-to-keyword (key)
2308 ;; skip blanks and non-indenting #
2309 (py-goto-initial-line)
2310 (while (and
2311 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2312 (zerop (forward-line -1))) ; go back
2313 nil)
2314 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002315 (let* ((re (concat "[ \t]*" key "\\b"))
2316 (case-fold-search nil) ; let* so looking-at sees this
2317 (found (looking-at re))
2318 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002319 (while (not (or found dead))
2320 (condition-case nil ; in case no enclosing block
2321 (py-goto-block-up 'no-mark)
2322 (error (setq dead t)))
2323 (or dead (setq found (looking-at re))))
2324 (beginning-of-line)
2325 found))
2326
2327;; return string in buffer from start of indentation to end of line;
2328;; prefix "..." if leading whitespace was skipped
2329(defun py-suck-up-leading-text ()
2330 (save-excursion
2331 (back-to-indentation)
2332 (concat
2333 (if (bolp) "" "...")
2334 (buffer-substring (point) (progn (end-of-line) (point))))))
2335
2336;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2337;; as a Lisp symbol; return nil if none
2338(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002339 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002340 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2341 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2342 nil)))
2343
2344(defun py-make-temp-name ()
2345 (make-temp-name
2346 (concat (file-name-as-directory py-temp-directory) "python")))
2347
2348(defun py-delete-file-silently (fname)
2349 (condition-case nil
2350 (delete-file fname)
2351 (error nil)))
2352
2353(defun py-kill-emacs-hook ()
2354 ;; delete our temp files
2355 (while py-file-queue
2356 (py-delete-file-silently (car py-file-queue))
2357 (setq py-file-queue (cdr py-file-queue)))
2358 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2359 ;; run the hook we inherited, if any
2360 (and py-inherited-kill-emacs-hook
2361 (funcall py-inherited-kill-emacs-hook))))
2362
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002363;; make PROCESS's buffer visible, append STRING to it, and force
2364;; display; also make shell-mode believe the user typed this string,
2365;; so that kill-output-from-shell and show-output-from-shell work
2366;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002367(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002368 (let ((cbuf (current-buffer))
2369 (pbuf (process-buffer process))
2370 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002371 (set-buffer pbuf)
2372 (goto-char (point-max))
2373 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002374 (if (not (or py-this-is-emacs-19-p
2375 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002376 (move-marker last-input-start (point))) ; muck w/ shell-mode
2377 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002378 (if (not (or py-this-is-emacs-19-p
2379 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002380 (move-marker last-input-end (point))) ; muck w/ shell-mode
2381 (set-buffer cbuf))
2382 (sit-for 0))
2383
Barry Warsaw3622e0d1996-10-29 15:32:57 +00002384;; older Emacsen don't have this function
2385(if (not (fboundp 'match-string))
2386 (defun match-string (n)
2387 (let ((beg (match-beginning n))
2388 (end (match-end n)))
2389 (if (and beg end)
2390 (buffer-substring beg end)
2391 nil))))
2392
Barry Warsawb3e81d51996-09-04 15:12:42 +00002393(defun py-current-defun ()
2394 ;; tell add-log.el how to find the current function/method/variable
2395 (save-excursion
2396 (if (re-search-backward py-defun-start-re nil t)
2397 (or (match-string 3)
2398 (let ((method (match-string 2)))
2399 (if (and (not (zerop (length (match-string 1))))
2400 (re-search-backward py-class-start-re nil t))
2401 (concat (match-string 1) "." method)
2402 method)))
2403 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002404
2405
Barry Warsaw850437a1995-03-08 21:50:28 +00002406(defconst py-version "$Revision$"
2407 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002408(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002409 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002410
Barry Warsaw850437a1995-03-08 21:50:28 +00002411(defun py-version ()
2412 "Echo the current version of `python-mode' in the minibuffer."
2413 (interactive)
2414 (message "Using `python-mode' version %s" py-version)
2415 (py-keep-region-active))
2416
2417;; only works under Emacs 19
2418;(eval-when-compile
2419; (require 'reporter))
2420
2421(defun py-submit-bug-report (enhancement-p)
2422 "Submit via mail a bug report on `python-mode'.
2423With \\[universal-argument] just submit an enhancement request."
2424 (interactive
2425 (list (not (y-or-n-p
2426 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002427 (let ((reporter-prompt-for-summary-p (if enhancement-p
2428 "(Very) brief summary: "
2429 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002430 (require 'reporter)
2431 (reporter-submit-bug-report
2432 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002433 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002434 ;; varlist
2435 (if enhancement-p nil
2436 '(py-python-command
2437 py-indent-offset
2438 py-block-comment-prefix
2439 py-scroll-process-buffer
2440 py-temp-directory
2441 py-beep-if-tab-change))
2442 nil ;pre-hooks
2443 nil ;post-hooks
2444 "Dear Barry,") ;salutation
2445 (if enhancement-p nil
2446 (set-mark (point))
2447 (insert
2448"Please replace this text with a sufficiently large code sample\n\
2449and an exact recipe so that I can reproduce your problem. Failure\n\
2450to do so may mean a greater delay in fixing your bug.\n\n")
2451 (exchange-point-and-mark)
2452 (py-keep-region-active))))
2453
2454
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002455;; arrange to kill temp files when Emacs exists
2456(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2457 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2458 ;; have to trust that other people are as respectful of our hook
2459 ;; fiddling as we are of theirs
2460 (if (boundp 'py-inherited-kill-emacs-hook)
2461 ;; we were loaded before -- trust others not to have screwed us
2462 ;; in the meantime (no choice, really)
2463 nil
2464 ;; else arrange for our hook to run theirs
2465 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2466 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2467
2468
2469
2470(provide 'python-mode)
2471;;; python-mode.el ends here