blob: 07876302aca9b178d23feb5b597ee14b1f5e839a [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 Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000020
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000022;; by Tim Peters after an original idea by Michael A. Guravage. Tim
23;; subsequently left the net; in 1995, Barry Warsaw inherited the
24;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
Barry Warsaw755c6711996-08-01 20:02:55 +000027;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
28;; 18 support. But all in all, the mode works exceedingly well, and
29;; I've simply been tweaking it as I go along. Ain't it wonderful
30;; that Python has a much more sane syntax than C? (or <shudder> C++?!
31;; :-). I can say that; I maintain cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
33;; The following statements, placed in your .emacs file or
34;; site-init.el, will cause this file to be autoloaded, and
35;; python-mode invoked, when visiting .py files (assuming this file is
36;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000037;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000041;;
42;; If you want font-lock support for Python source code (a.k.a. syntax
43;; coloring, highlighting), add this to your .emacs file:
44;;
45;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000046;;
47;; But you better be sure you're version of Emacs supports
48;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
49;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000050
Barry Warsaw3fcaf611996-08-01 20:11:51 +000051;; Here's a brief list of recent additions/improvements/changes:
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000052;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000053;; - Wrapping and indentation within triple quote strings now works.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000054;; - `Standard' bug reporting mechanism (use C-c C-b)
55;; - py-mark-block was moved to C-c C-m
56;; - C-c C-v shows you the python-mode version
Barry Warsaw3fcaf611996-08-01 20:11:51 +000057;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000058;; - proper interaction with pending-del and del-sel modes.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000059;; - Better support for outdenting: py-electric-colon (:) and
60;; py-indent-line (TAB) improvements; one level of outdentation
Barry Warsaw7cb505c1996-10-23 20:44:59 +000061;; added after a return, raise, break, pass, or continue statement.
62;; Defeated by prefixing command with C-u.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000063;; - New py-electric-colon (:) command for improved outdenting Also
64;; py-indent-line (TAB) should handle outdented lines better
Barry Warsaw03970731996-07-03 23:12:52 +000065;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000066;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
67;; M-f and M-b respectively.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000068;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
69;; - py-indent-offset now defaults to 4
70;; - new variable py-honor-comment-indentation
71;; - comment-region bound to C-c #
72;; - py-delete-char obeys numeric arguments
73;; - Small modification to rule for "indenting comment lines", such
74;; lines must now also be indented less than or equal to the
75;; indentation of the previous statement.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000076
Barry Warsaw7b0f5681995-03-08 21:33:04 +000077;; Here's a brief to do list:
78;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079;; - Better integration with gud-mode for debugging.
80;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000081;; - possibly force indent-tabs-mode == nil, and add a
82;; write-file-hooks that runs untabify on the whole buffer (to work
83;; around potential tab/space mismatch problems). In practice this
84;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000085;; - have py-execute-region on indented code act as if the region is
86;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000087;; - Add a py-goto-error or some such that would scan an exception in
88;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000089
Barry Warsaw7b0f5681995-03-08 21:33:04 +000090;; If you can think of more things you'd like to see, drop me a line.
91;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
92;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000093;; Note that I only test things on XEmacs 19 and to some degree on
94;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
95;; send me your patches. Byte compiler complaints can probably be
96;; safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000097
Barry Warsaw7b0f5681995-03-08 21:33:04 +000098;;; Code:
99
100
101;; user definable variables
102;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000103
104(defvar py-python-command "python"
105 "*Shell command used to start Python interpreter.")
106
Barry Warsaw17914f41995-11-03 18:25:15 +0000107(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +0000108 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000109Note that `\\[py-guess-indent-offset]' can usually guess a good value
110when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000111
Barry Warsaw095e9c61995-09-19 20:01:42 +0000112(defvar py-align-multiline-strings-p t
113 "*Flag describing how multiline triple quoted strings are aligned.
114When this flag is non-nil, continuation lines are lined up under the
115preceding line's indentation. When this flag is nil, continuation
116lines are aligned to column zero.")
117
Barry Warsaw3fcaf611996-08-01 20:11:51 +0000118(defvar py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000119 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000120This should follow the convention for non-indenting comment lines so
121that the indentation commands won't get confused (i.e., the string
122should be of the form `#x...' where `x' is not a blank or a tab, and
123`...' is arbitrary).")
124
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000125(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000126 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000127
Barry Warsaw6d627751996-03-06 18:41:38 +0000128When nil, all comment lines are skipped for indentation purposes, and
129in Emacs 19, a faster algorithm is used.
130
131When t, lines that begin with a single `#' are a hint to subsequent
132line indentation. If the previous line is such a comment line (as
133opposed to one that starts with `py-block-comment-prefix'), then it's
134indentation is used as a hint for this line's indentation. Lines that
135begin with `py-block-comment-prefix' are ignored for indentation
136purposes.
137
138When not nil or t, comment lines that begin with a `#' are used as
139indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000140
Barry Warsaw7ae77681994-12-12 20:38:05 +0000141(defvar py-scroll-process-buffer t
142 "*Scroll Python process buffer as output arrives.
143If nil, the Python process buffer acts, with respect to scrolling, like
144Shell-mode buffers normally act. This is surprisingly complicated and
145so won't be explained here; in fact, you can't get the whole story
146without studying the Emacs C code.
147
148If non-nil, the behavior is different in two respects (which are
149slightly inaccurate in the interest of brevity):
150
151 - If the buffer is in a window, and you left point at its end, the
152 window will scroll as new output arrives, and point will move to the
153 buffer's end, even if the window is not the selected window (that
154 being the one the cursor is in). The usual behavior for shell-mode
155 windows is not to scroll, and to leave point where it was, if the
156 buffer is in a window other than the selected window.
157
158 - If the buffer is not visible in any window, and you left point at
159 its end, the buffer will be popped into a window as soon as more
160 output arrives. This is handy if you have a long-running
161 computation and don't want to tie up screen area waiting for the
162 output. The usual behavior for a shell-mode buffer is to stay
163 invisible until you explicitly visit it.
164
165Note the `and if you left point at its end' clauses in both of the
166above: you can `turn off' the special behaviors while output is in
167progress, by visiting the Python buffer and moving point to anywhere
168besides the end. Then the buffer won't scroll, point will remain where
169you leave it, and if you hide the buffer it will stay hidden until you
170visit it again. You can enable and disable the special behaviors as
171often as you like, while output is in progress, by (respectively) moving
172point to, or away from, the end of the buffer.
173
174Warning: If you expect a large amount of output, you'll probably be
175happier setting this option to nil.
176
177Obscure: `End of buffer' above should really say `at or beyond the
178process mark', but if you know what that means you didn't need to be
179told <grin>.")
180
181(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000182 (let ((ok '(lambda (x)
183 (and x
184 (setq x (expand-file-name x)) ; always true
185 (file-directory-p x)
186 (file-writable-p x)
187 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000188 (or (funcall ok (getenv "TMPDIR"))
189 (funcall ok "/usr/tmp")
190 (funcall ok "/tmp")
191 (funcall ok ".")
192 (error
193 "Couldn't find a usable temp directory -- set py-temp-directory")))
194 "*Directory used for temp files created by a *Python* process.
195By default, the first directory from this list that exists and that you
196can write into: the value (if any) of the environment variable TMPDIR,
197/usr/tmp, /tmp, or the current directory.")
198
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000199(defvar py-beep-if-tab-change t
200 "*Ring the bell if tab-width is changed.
201If a comment of the form
202
203 \t# vi:set tabsize=<number>:
204
205is found before the first code line when the file is entered, and the
206current value of (the general Emacs variable) `tab-width' does not
207equal <number>, `tab-width' is set to <number>, a message saying so is
208displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
209the Emacs bell is also rung as a warning.")
210
Barry Warsawfb07f401997-02-24 03:37:22 +0000211(defvar python-font-lock-keywords
Barry Warsaw2e049b21996-09-04 15:21:55 +0000212 (let* ((keywords '("and" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000213 "continue" "def" "del" "elif"
214 "else:" "except" "except:" "exec"
215 "finally:" "for" "from" "global"
216 "if" "import" "in" "is"
217 "lambda" "not" "or" "pass"
218 "print" "raise" "return" "try:"
219 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000220 ))
221 (kwregex (mapconcat 'identity keywords "\\|")))
222 (list
223 ;; keywords not at beginning of line
224 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
225 ;; keywords at beginning of line. i don't think regexps are
226 ;; powerful enough to handle these two cases in one regexp.
227 ;; prove me wrong!
228 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
229 ;; classes
230 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
231 1 font-lock-type-face)
232 ;; functions
233 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
234 1 font-lock-function-name-face)
235 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000236 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000237(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
238
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000239
Barry Warsaw81437461996-08-01 19:48:02 +0000240(defvar imenu-example--python-show-method-args-p nil
241 "*Controls echoing of arguments of functions & methods in the imenu buffer.
242When non-nil, arguments are printed.")
243
244
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000245
246;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
247;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
248
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000249(make-variable-buffer-local 'py-indent-offset)
250
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000251;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
252;; seems to be the standard way of checking this.
253;; BAW - This is *not* the right solution. When at all possible,
254;; instead of testing for the version of Emacs, use feature tests.
255
256(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
257(setq py-this-is-emacs-19-p
258 (and
259 (not py-this-is-lucid-emacs-p)
260 (string-match "^19\\." emacs-version)))
261
Barry Warsaw7ae77681994-12-12 20:38:05 +0000262;; have to bind py-file-queue before installing the kill-emacs hook
263(defvar py-file-queue nil
264 "Queue of Python temp files awaiting execution.
265Currently-active file is at the head of the list.")
266
267;; define a mode-specific abbrev table for those who use such things
268(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000269 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000270(define-abbrev-table 'python-mode-abbrev-table nil)
271
Barry Warsaw7ae77681994-12-12 20:38:05 +0000272(defvar python-mode-hook nil
273 "*Hook called by `python-mode'.")
274
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000275;; in previous version of python-mode.el, the hook was incorrectly
276;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000277(and (fboundp 'make-obsolete-variable)
278 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
279
Barry Warsawb0539931996-12-17 22:05:07 +0000280(defvar py-delete-function 'backward-delete-char-untabify
281 "*Function called by `py-delete-char' when deleting characters.")
282
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283(defvar py-mode-map ()
284 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285
Barry Warsaw7ae77681994-12-12 20:38:05 +0000286(if py-mode-map
287 ()
288 (setq py-mode-map (make-sparse-keymap))
289
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000290 ;; shadow global bindings for newline-and-indent w/ the py- version.
291 ;; BAW - this is extremely bad form, but I'm not going to change it
292 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000293 (mapcar (function (lambda (key)
294 (define-key
295 py-mode-map key 'py-newline-and-indent)))
296 (where-is-internal 'newline-and-indent))
297
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298 ;; BAW - you could do it this way, but its not considered proper
299 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000300 (mapcar (function
301 (lambda (x)
302 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000303 '((":" . py-electric-colon)
304 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000305 ("\C-c|" . py-execute-region)
306 ("\C-c!" . py-shell)
307 ("\177" . py-delete-char)
308 ("\n" . py-newline-and-indent)
309 ("\C-c:" . py-guess-indent-offset)
310 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000311 ("\C-c\C-l" . py-shift-region-left)
312 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000313 ("\C-c<" . py-shift-region-left)
314 ("\C-c>" . py-shift-region-right)
315 ("\C-c\C-n" . py-next-statement)
316 ("\C-c\C-p" . py-previous-statement)
317 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000318 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000319 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000320 ("\C-c?" . py-describe-mode)
321 ("\C-c\C-hm" . py-describe-mode)
322 ("\e\C-a" . beginning-of-python-def-or-class)
323 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000324 ( "\e\C-h" . mark-python-def-or-class)))
325 ;; should do all keybindings this way
326 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
327 (define-key py-mode-map "\C-c\C-v" 'py-version)
328 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000329
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000330(defvar py-mode-syntax-table nil
331 "Syntax table used in `python-mode' buffers.")
332
Barry Warsaw7ae77681994-12-12 20:38:05 +0000333(if py-mode-syntax-table
334 ()
335 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000336 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000337 (mapcar (function
338 (lambda (x) (modify-syntax-entry
339 (car x) (cdr x) py-mode-syntax-table)))
340 '(( ?\( . "()" ) ( ?\) . ")(" )
341 ( ?\[ . "(]" ) ( ?\] . ")[" )
342 ( ?\{ . "(}" ) ( ?\} . "){" )
343 ;; fix operator symbols misassigned in the std table
344 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
345 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
346 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
347 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000348 ;; for historical reasons, underscore is word class
349 ;; instead of symbol class. it should be symbol class,
350 ;; but if you're tempted to change it, try binding M-f and
351 ;; M-b to py-forward-into-nomenclature and
352 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000353 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000354 ( ?\' . "\"") ; single quote is string quote
355 ( ?\" . "\"" ) ; double quote is string quote too
356 ( ?\` . "$") ; backquote is open and close paren
357 ( ?\# . "<") ; hash starts comment
358 ( ?\n . ">")))) ; newline ends comment
359
360(defconst py-stringlit-re
361 (concat
362 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
363 "\\|" ; or
364 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000365 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000366
367;; this is tricky because a trailing backslash does not mean
368;; continuation if it's in a comment
369(defconst py-continued-re
370 (concat
371 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
372 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000373 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000374
375(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000376 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000377
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000378(defconst py-outdent-re
379 (concat "\\(" (mapconcat 'identity
380 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000381 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000382 "finally:"
383 "elif\\s +.*:")
384 "\\|")
385 "\\)")
386 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000388(defconst py-no-outdent-re
389 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000390 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000391 "except\\(\\s +.*\\)?:"
392 "while\\s +.*:"
393 "for\\s +.*:"
394 "if\\s +.*:"
Barry Warsawf67a57e1996-08-12 19:52:27 +0000395 "elif\\s +.*:"
396 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
397 )
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000398 "\\|")
399 "\\)")
400 "Regexp matching lines to not outdent after.")
401
Barry Warsawb3e81d51996-09-04 15:12:42 +0000402(defvar py-defun-start-re
403 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
404 "Regexp matching a function, method or variable assignment.
405
406If you change this, you probably have to change `py-current-defun' as well.
407This is only used by `py-current-defun' to find the name for add-log.el.")
408
409(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
410 "Regexp for finding a class name.
411
412If you change this, you probably have to change `py-current-defun' as well.
413This is only used by `py-current-defun' to find the name for add-log.el.")
414
Barry Warsawf7705781997-01-30 19:49:39 +0000415;; As of 30-Jan-1997, Emacs 19.34 works but XEmacs 19.15b90 and
416;; previous does not. It is suspected that Emacsen before 19.34 are
417;; also broken.
418(defvar py-parse-partial-sexp-works-p
419 (let ((buf (get-buffer-create " ---*---pps---*---"))
420 state status)
421 (save-excursion
422 (set-buffer buf)
423 (erase-buffer)
424 (insert "(line1\n line2)\nline3")
425 (lisp-mode)
426 (goto-char (point-min))
427 (setq state (parse-partial-sexp (point) (save-excursion
428 (forward-line 1)
429 (point))))
430 (parse-partial-sexp (point) (point-max) 0 nil state)
431 (setq status (not (= (point) (point-max))))
432 (kill-buffer buf)
433 status))
434 "Does `parse-partial-sexp' work in this Emacs?")
Barry Warsawb3e81d51996-09-04 15:12:42 +0000435
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000436
Barry Warsaw42f707f1996-07-29 21:05:05 +0000437;; Menu definitions, only relevent if you have the easymenu.el package
438;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000439(defvar py-menu nil
440 "Menu for Python Mode.
441
442This menu will get created automatically if you have the easymenu
443package. Note that the latest XEmacs 19 and Emacs 19 versions contain
444this package.")
445
Barry Warsaw42f707f1996-07-29 21:05:05 +0000446(if (condition-case nil
447 (require 'easymenu)
448 (error nil))
449 (easy-menu-define
450 py-menu py-mode-map "Python Mode menu"
451 '("Python"
Barry Warsaw941f70c1997-01-30 20:16:18 +0000452 ["Comment Out Region" py-comment-region (mark)]
453 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
Barry Warsaw42f707f1996-07-29 21:05:05 +0000454 "-"
455 ["Mark current block" py-mark-block t]
456 ["Mark current def" mark-python-def-or-class t]
457 ["Mark current class" (mark-python-def-or-class t) t]
458 "-"
459 ["Shift region left" py-shift-region-left (mark)]
460 ["Shift region right" py-shift-region-right (mark)]
461 "-"
462 ["Execute buffer" py-execute-buffer t]
463 ["Execute region" py-execute-region (mark)]
464 ["Start interpreter..." py-shell t]
465 "-"
466 ["Go to start of block" py-goto-block-up t]
467 ["Go to start of class" (beginning-of-python-def-or-class t) t]
468 ["Move to end of class" (end-of-python-def-or-class t) t]
469 ["Move to start of def" beginning-of-python-def-or-class t]
470 ["Move to end of def" end-of-python-def-or-class t]
471 "-"
472 ["Describe mode" py-describe-mode t]
473 )))
474
Barry Warsaw81437461996-08-01 19:48:02 +0000475
476
477;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
478(defvar imenu-example--python-class-regexp
479 (concat ; <<classes>>
480 "\\(" ;
481 "^[ \t]*" ; newline and maybe whitespace
482 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
483 ; possibly multiple superclasses
484 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
485 "[ \t]*:" ; and the final :
486 "\\)" ; >>classes<<
487 )
488 "Regexp for Python classes for use with the imenu package."
489 )
490
491(defvar imenu-example--python-method-regexp
492 (concat ; <<methods and functions>>
493 "\\(" ;
494 "^[ \t]*" ; new line and maybe whitespace
495 "\\(def[ \t]+" ; function definitions start with def
496 "\\([a-zA-Z0-9_]+\\)" ; name is here
497 ; function arguments...
498 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
499 "\\)" ; end of def
500 "[ \t]*:" ; and then the :
501 "\\)" ; >>methods and functions<<
502 )
503 "Regexp for Python methods/functions for use with the imenu package."
504 )
505
506(defvar imenu-example--python-method-no-arg-parens '(2 8)
507 "Indicies into groups of the Python regexp for use with imenu.
508
509Using these values will result in smaller imenu lists, as arguments to
510functions are not listed.
511
512See the variable `imenu-example--python-show-method-args-p' for more
513information.")
514
515(defvar imenu-example--python-method-arg-parens '(2 7)
516 "Indicies into groups of the Python regexp for use with imenu.
517Using these values will result in large imenu lists, as arguments to
518functions are listed.
519
520See the variable `imenu-example--python-show-method-args-p' for more
521information.")
522
523;; Note that in this format, this variable can still be used with the
524;; imenu--generic-function. Otherwise, there is no real reason to have
525;; it.
526(defvar imenu-example--generic-python-expression
527 (cons
528 (concat
529 imenu-example--python-class-regexp
530 "\\|" ; or...
531 imenu-example--python-method-regexp
532 )
533 imenu-example--python-method-no-arg-parens)
534 "Generic Python expression which may be used directly with imenu.
535Used by setting the variable `imenu-generic-expression' to this value.
536Also, see the function \\[imenu-example--create-python-index] for a
537better alternative for finding the index.")
538
539;; These next two variables are used when searching for the python
540;; class/definitions. Just saving some time in accessing the
541;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000542(defvar imenu-example--python-generic-regexp nil)
543(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000544
545
546;;;###autoload
547(eval-when-compile
548 ;; Imenu isn't used in XEmacs, so just ignore load errors
549 (condition-case ()
550 (progn
551 (require 'cl)
552 (require 'imenu))
553 (error nil)))
554
555(defun imenu-example--create-python-index ()
556 "Python interface function for imenu package.
557Finds all python classes and functions/methods. Calls function
558\\[imenu-example--create-python-index-engine]. See that function for
559the details of how this works."
560 (setq imenu-example--python-generic-regexp
561 (car imenu-example--generic-python-expression))
562 (setq imenu-example--python-generic-parens
563 (if imenu-example--python-show-method-args-p
564 imenu-example--python-method-arg-parens
565 imenu-example--python-method-no-arg-parens))
566 (goto-char (point-min))
567 (imenu-example--create-python-index-engine nil))
568
569(defun imenu-example--create-python-index-engine (&optional start-indent)
570 "Function for finding imenu definitions in Python.
571
572Finds all definitions (classes, methods, or functions) in a Python
573file for the imenu package.
574
575Returns a possibly nested alist of the form
576
577 (INDEX-NAME . INDEX-POSITION)
578
579The second element of the alist may be an alist, producing a nested
580list as in
581
582 (INDEX-NAME . INDEX-ALIST)
583
584This function should not be called directly, as it calls itself
585recursively and requires some setup. Rather this is the engine for
586the function \\[imenu-example--create-python-index].
587
588It works recursively by looking for all definitions at the current
589indention level. When it finds one, it adds it to the alist. If it
590finds a definition at a greater indentation level, it removes the
591previous definition from the alist. In it's place it adds all
592definitions found at the next indentation level. When it finds a
593definition that is less indented then the current level, it retuns the
594alist it has created thus far.
595
596The optional argument START-INDENT indicates the starting indentation
597at which to continue looking for Python classes, methods, or
598functions. If this is not supplied, the function uses the indentation
599of the first definition found."
600 (let ((index-alist '())
601 (sub-method-alist '())
602 looking-p
603 def-name prev-name
604 cur-indent def-pos
605 (class-paren (first imenu-example--python-generic-parens))
606 (def-paren (second imenu-example--python-generic-parens)))
607 (setq looking-p
608 (re-search-forward imenu-example--python-generic-regexp
609 (point-max) t))
610 (while looking-p
611 (save-excursion
612 ;; used to set def-name to this value but generic-extract-name is
613 ;; new to imenu-1.14. this way it still works with imenu-1.11
614 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
615 (let ((cur-paren (if (match-beginning class-paren)
616 class-paren def-paren)))
617 (setq def-name
618 (buffer-substring (match-beginning cur-paren)
619 (match-end cur-paren))))
620 (beginning-of-line)
621 (setq cur-indent (current-indentation)))
622
623 ;; HACK: want to go to the next correct definition location. we
624 ;; explicitly list them here. would be better to have them in a
625 ;; list.
626 (setq def-pos
627 (or (match-beginning class-paren)
628 (match-beginning def-paren)))
629
630 ;; if we don't have a starting indent level, take this one
631 (or start-indent
632 (setq start-indent cur-indent))
633
634 ;; if we don't have class name yet, take this one
635 (or prev-name
636 (setq prev-name def-name))
637
638 ;; what level is the next definition on? must be same, deeper
639 ;; or shallower indentation
640 (cond
641 ;; at the same indent level, add it to the list...
642 ((= start-indent cur-indent)
643
644 ;; if we don't have push, use the following...
645 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
646 (push (cons def-name def-pos) index-alist))
647
648 ;; deeper indented expression, recur...
649 ((< start-indent cur-indent)
650
651 ;; the point is currently on the expression we're supposed to
652 ;; start on, so go back to the last expression. The recursive
653 ;; call will find this place again and add it to the correct
654 ;; list
655 (re-search-backward imenu-example--python-generic-regexp
656 (point-min) 'move)
657 (setq sub-method-alist (imenu-example--create-python-index-engine
658 cur-indent))
659
660 (if sub-method-alist
661 ;; we put the last element on the index-alist on the start
662 ;; of the submethod alist so the user can still get to it.
663 (let ((save-elmt (pop index-alist)))
664 (push (cons (imenu-create-submenu-name prev-name)
665 (cons save-elmt sub-method-alist))
666 index-alist))))
667
668 ;; found less indented expression, we're done.
669 (t
670 (setq looking-p nil)
671 (re-search-backward imenu-example--python-generic-regexp
672 (point-min) t)))
673 (setq prev-name def-name)
674 (and looking-p
675 (setq looking-p
676 (re-search-forward imenu-example--python-generic-regexp
677 (point-max) 'move))))
678 (nreverse index-alist)))
679
Barry Warsaw42f707f1996-07-29 21:05:05 +0000680
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000681;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000682(defun python-mode ()
683 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000684To submit a problem report, enter `\\[py-submit-bug-report]' from a
685`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
686documentation. To see what version of `python-mode' you are running,
687enter `\\[py-version]'.
688
689This mode knows about Python indentation, tokens, comments and
690continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000691
692COMMANDS
693\\{py-mode-map}
694VARIABLES
695
Barry Warsaw42f707f1996-07-29 21:05:05 +0000696py-indent-offset\t\tindentation increment
697py-block-comment-prefix\t\tcomment string used by comment-region
698py-python-command\t\tshell command to invoke Python interpreter
699py-scroll-process-buffer\t\talways scroll Python process buffer
700py-temp-directory\t\tdirectory used for temp files (if needed)
701py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000702 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000703 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000704 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000705 (make-local-variable 'font-lock-defaults)
706 (make-local-variable 'paragraph-separate)
707 (make-local-variable 'paragraph-start)
708 (make-local-variable 'require-final-newline)
709 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000710 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000711 (make-local-variable 'comment-start-skip)
712 (make-local-variable 'comment-column)
713 (make-local-variable 'indent-region-function)
714 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000715 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000716 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000717 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000718 (setq major-mode 'python-mode
719 mode-name "Python"
720 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000721 paragraph-separate "^[ \t]*$"
722 paragraph-start "^[ \t]*$"
723 require-final-newline t
724 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000725 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000726 comment-start-skip "# *"
727 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000728 indent-region-function 'py-indent-region
729 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000730 ;; tell add-log.el how to find the current function/method/variable
731 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000732 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000733 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000734 ;; add the menu
735 (if py-menu
736 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000737 ;; Emacs 19 requires this
738 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
739 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000740 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000741 ;;
742 ;; not sure where the magic comment has to be; to save time
743 ;; searching for a rarity, we give up if it's not found prior to the
744 ;; first executable statement.
745 ;;
746 ;; BAW - on first glance, this seems like complete hackery. Why was
747 ;; this necessary, and is it still necessary?
748 (let ((case-fold-search nil)
749 (start (point))
750 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000751 (if (re-search-forward
752 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
753 (prog2 (py-next-statement 1) (point) (goto-char 1))
754 t)
755 (progn
756 (setq new-tab-width
757 (string-to-int
758 (buffer-substring (match-beginning 1) (match-end 1))))
759 (if (= tab-width new-tab-width)
760 nil
761 (setq tab-width new-tab-width)
762 (message "Caution: tab-width changed to %d" new-tab-width)
763 (if py-beep-if-tab-change (beep)))))
764 (goto-char start))
765
Barry Warsaw755c6711996-08-01 20:02:55 +0000766 ;; install imenu
767 (setq imenu-create-index-function
768 (function imenu-example--create-python-index))
769 (if (fboundp 'imenu-add-to-menubar)
770 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
771
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000772 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000773 (if python-mode-hook
774 (run-hooks 'python-mode-hook)
775 (run-hooks 'py-mode-hook)))
776
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000777
Barry Warsaw826255b1996-03-22 16:09:34 +0000778(defun py-keep-region-active ()
Barry Warsawce60bc71996-08-01 18:17:14 +0000779 ;; do whatever is necessary to keep the region active in XEmacs.
780 ;; Ignore byte-compiler warnings you might see. Also note that
781 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
782 ;; require us to take explicit action.
Barry Warsaw826255b1996-03-22 16:09:34 +0000783 (and (boundp 'zmacs-region-stays)
784 (setq zmacs-region-stays t)))
785
Barry Warsawce60bc71996-08-01 18:17:14 +0000786
Barry Warsawb91b7431995-03-14 15:55:20 +0000787;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000788(defun py-outdent-p ()
789 ;; returns non-nil if the current line should outdent one level
790 (save-excursion
791 (and (progn (back-to-indentation)
792 (looking-at py-outdent-re))
793 (progn (backward-to-indentation 1)
794 (while (or (looking-at py-blank-or-comment-re)
795 (bobp))
796 (backward-to-indentation 1))
797 (not (looking-at py-no-outdent-re)))
798 )))
799
800
Barry Warsawb91b7431995-03-14 15:55:20 +0000801(defun py-electric-colon (arg)
802 "Insert a colon.
803In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000804argument is provided, that many colons are inserted non-electrically.
805Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000806 (interactive "P")
807 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000808 ;; are we in a string or comment?
809 (if (save-excursion
810 (let ((pps (parse-partial-sexp (save-excursion
811 (beginning-of-python-def-or-class)
812 (point))
813 (point))))
814 (not (or (nth 3 pps) (nth 4 pps)))))
815 (save-excursion
816 (let ((here (point))
817 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000818 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000819 (if (and (not arg)
820 (py-outdent-p)
821 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000822 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000823 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000824 )
825 (setq outdent py-indent-offset))
826 ;; Don't indent, only outdent. This assumes that any lines that
827 ;; are already outdented relative to py-compute-indentation were
828 ;; put there on purpose. Its highly annoying to have `:' indent
829 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
830 ;; there a better way to determine this???
831 (if (< (current-indentation) indent) nil
832 (goto-char here)
833 (beginning-of-line)
834 (delete-horizontal-space)
835 (indent-to (- indent outdent))
836 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000837
838
Barry Warsaw7ae77681994-12-12 20:38:05 +0000839;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000840;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000841(defun py-shell ()
842 "Start an interactive Python interpreter in another window.
843This is like Shell mode, except that Python is running in the window
844instead of a shell. See the `Interactive Shell' and `Shell Mode'
845sections of the Emacs manual for details, especially for the key
846bindings active in the `*Python*' buffer.
847
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000848See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000849behavior in the process window.
850
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000851Warning: Don't use an interactive Python if you change sys.ps1 or
852sys.ps2 from their default values, or if you're running code that
853prints `>>> ' or `... ' at the start of a line. `python-mode' can't
854distinguish your output from Python's output, and assumes that `>>> '
855at the start of a line is a prompt from Python. Similarly, the Emacs
856Shell mode code assumes that both `>>> ' and `... ' at the start of a
857line are Python prompts. Bad things can happen if you fool either
858mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000859
860Warning: If you do any editing *in* the process buffer *while* the
861buffer is accepting output from Python, do NOT attempt to `undo' the
862changes. Some of the output (nowhere near the parts you changed!) may
863be lost if you do. This appears to be an Emacs bug, an unfortunate
864interaction between undo and process filters; the same problem exists in
865non-Python process buffers using the default (Emacs-supplied) process
866filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000867 ;; BAW - should undo be disabled in the python process buffer, if
868 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000869 (interactive)
Barry Warsawe6648961997-07-10 15:58:36 +0000870 (require 'comint)
871 (switch-to-buffer-other-window (make-comint "Python" py-python-command))
872 (make-local-variable 'comint-prompt-regexp)
873 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
874 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
875 (set-syntax-table py-mode-syntax-table)
876 (local-set-key [tab] 'self-insert-command))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877
878(defun py-execute-region (start end)
879 "Send the region between START and END to a Python interpreter.
880If there is a *Python* process it is used.
881
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000882Hint: If you want to execute part of a Python file several times
883\(e.g., perhaps you're developing a function and want to flesh it out
884a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
885the region of interest, and send the code to a *Python* process via
886`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887
888Following are subtleties to note when using a *Python* process:
889
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000890If a *Python* process is used, the region is copied into a temporary
891file (in directory `py-temp-directory'), and an `execfile' command is
892sent to Python naming that file. If you send regions faster than
893Python can execute them, `python-mode' will save them into distinct
894temp files, and execute the next one in the queue the next time it
895sees a `>>> ' prompt from Python. Each time this happens, the process
896buffer is popped into a window (if it's not already in some window) so
897you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000899 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000900
901is inserted at the end.
902
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000903Caution: No more than 26 regions can be pending at any given time.
904This limit is (indirectly) inherited from libc's mktemp(3).
905`python-mode' does not try to protect you from exceeding the limit.
906It's extremely unlikely that you'll get anywhere close to the limit in
907practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000908
909See the `\\[py-shell]' docs for additional warnings."
910 (interactive "r")
911 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000912 (let ((pyproc (get-process "Python"))
913 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000914 (if (null pyproc)
915 (shell-command-on-region start end py-python-command)
916 ;; else feed it thru a temp file
917 (setq fname (py-make-temp-name))
918 (write-region start end fname nil 'no-msg)
919 (setq py-file-queue (append py-file-queue (list fname)))
920 (if (cdr py-file-queue)
921 (message "File %s queued for execution" fname)
922 ;; else
923 (py-execute-file pyproc fname)))))
924
925(defun py-execute-file (pyproc fname)
926 (py-append-to-process-buffer
927 pyproc
928 (format "## working on region in file %s ...\n" fname))
929 (process-send-string pyproc (format "execfile('%s')\n" fname)))
930
931(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000932 (let ((curbuf (current-buffer))
933 (pbuf (process-buffer pyproc))
934 (pmark (process-mark pyproc))
935 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000936
937 ;; make sure we switch to a different buffer at least once. if we
938 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000939 ;; window, and point is before the end, and lots of output is
940 ;; coming at a fast pace, then (a) simple cursor-movement commands
941 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
942 ;; to have a visible effect (the window just doesn't get updated,
943 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
944 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000945 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000946 ;; #b makes no sense to me at all. #a almost makes sense: unless
947 ;; we actually change buffers, set_buffer_internal in buffer.c
948 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
949 ;; seems to make the Emacs command loop reluctant to update the
950 ;; display. Perhaps the default process filter in process.c's
951 ;; read_process_output has update_mode_lines++ for a similar
952 ;; reason? beats me ...
953
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000954 (unwind-protect
955 ;; make sure current buffer is restored
956 ;; BAW - we want to check to see if this still applies
957 (progn
958 ;; mysterious ugly hack
959 (if (eq curbuf pbuf)
960 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000961
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000962 (set-buffer pbuf)
963 (let* ((start (point))
964 (goback (< start pmark))
965 (goend (and (not goback) (= start (point-max))))
966 (buffer-read-only nil))
967 (goto-char pmark)
968 (insert string)
969 (move-marker pmark (point))
970 (setq file-finished
971 (and py-file-queue
972 (equal ">>> "
973 (buffer-substring
974 (prog2 (beginning-of-line) (point)
975 (goto-char pmark))
976 (point)))))
977 (if goback (goto-char start)
978 ;; else
979 (if py-scroll-process-buffer
980 (let* ((pop-up-windows t)
981 (pwin (display-buffer pbuf)))
982 (set-window-point pwin (point)))))
983 (set-buffer curbuf)
984 (if file-finished
985 (progn
986 (py-delete-file-silently (car py-file-queue))
987 (setq py-file-queue (cdr py-file-queue))
988 (if py-file-queue
989 (py-execute-file pyproc (car py-file-queue)))))
990 (and goend
991 (progn (set-buffer pbuf)
992 (goto-char (point-max))))
993 ))
994 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
996(defun py-execute-buffer ()
997 "Send the contents of the buffer to a Python interpreter.
998If there is a *Python* process buffer it is used. If a clipping
999restriction is in effect, only the accessible portion of the buffer is
1000sent. A trailing newline will be supplied if needed.
1001
1002See the `\\[py-execute-region]' docs for an account of some subtleties."
1003 (interactive)
1004 (py-execute-region (point-min) (point-max)))
1005
1006
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007
1008;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001009(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001010 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001011
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001013Deletion is performed by calling the function in `py-delete-function'
1014with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001015
1016Else if point is at the leftmost non-blank character of a line that is
1017neither a continuation line nor a non-indenting comment line, or if
1018point is at the end of a blank line, reduces the indentation to match
1019that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001021of where you are. With numeric count, outdents that many blocks (but
1022not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023
1024Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001025needed so that only a single column position is deleted. Numeric
1026argument delets that many characters."
1027 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001028 (if (or (/= (current-indentation) (current-column))
1029 (bolp)
1030 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001031 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001032 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001033 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001034 ;; else indent the same as the colon line that opened the block
1035
1036 ;; force non-blank so py-goto-block-up doesn't ignore it
1037 (insert-char ?* 1)
1038 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001039 (let ((base-indent 0) ; indentation of base line
1040 (base-text "") ; and text of base line
1041 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001042 (save-excursion
1043 (while (< 0 count)
1044 (condition-case nil ; in case no enclosing block
1045 (progn
1046 (py-goto-block-up 'no-mark)
1047 (setq base-indent (current-indentation)
1048 base-text (py-suck-up-leading-text)
1049 base-found-p t))
1050 (error nil))
1051 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052 (delete-char 1) ; toss the dummy character
1053 (delete-horizontal-space)
1054 (indent-to base-indent)
1055 (if base-found-p
1056 (message "Closes block: %s" base-text)))))
1057
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001058;; required for pending-del and delsel modes
1059(put 'py-delete-char 'delete-selection 'supersede)
1060(put 'py-delete-char 'pending-delete 'supersede)
1061
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001062(defun py-indent-line (&optional arg)
1063 "Fix the indentation of the current line according to Python rules.
1064With \\[universal-argument], ignore outdenting rules for block
1065closing statements (e.g. return, raise, break, continue, pass)
1066
1067This function is normally bound to `indent-line-function' so
1068\\[indent-for-tab-command] will call it."
1069 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001070 (let* ((ci (current-indentation))
1071 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001072 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001073 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001074 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001075 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (if (/= ci need)
1077 (save-excursion
1078 (beginning-of-line)
1079 (delete-horizontal-space)
1080 (indent-to need)))
1081 (if move-to-indentation-p (back-to-indentation))))
1082
1083(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001084 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001085This is just `strives to' because correct indentation can't be computed
1086from scratch for Python code. In general, deletes the whitespace before
1087point, inserts a newline, and takes an educated guess as to how you want
1088the new line indented."
1089 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001090 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001091 (if (< ci (current-column)) ; if point beyond indentation
1092 (newline-and-indent)
1093 ;; else try to act like newline-and-indent "normally" acts
1094 (beginning-of-line)
1095 (insert-char ?\n 1)
1096 (move-to-column ci))))
1097
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001098(defun py-compute-indentation (honor-block-close-p)
1099 ;; implements all the rules for indentation computation. when
1100 ;; honor-block-close-p is non-nil, statements such as return, raise,
1101 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001102 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001103 (let ((pps (parse-partial-sexp (save-excursion
1104 (beginning-of-python-def-or-class)
1105 (point))
1106 (point))))
1107 (beginning-of-line)
1108 (cond
1109 ;; are we inside a string or comment?
1110 ((or (nth 3 pps) (nth 4 pps))
1111 (save-excursion
1112 (if (not py-align-multiline-strings-p) 0
1113 ;; skip back over blank & non-indenting comment lines
1114 ;; note: will skip a blank or non-indenting comment line
1115 ;; that happens to be a continuation line too
1116 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1117 (back-to-indentation)
1118 (current-column))))
1119 ;; are we on a continuation line?
1120 ((py-continuation-line-p)
1121 (let ((startpos (point))
1122 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001123 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001124 (if open-bracket-pos
1125 (progn
1126 ;; align with first item in list; else a normal
1127 ;; indent beyond the line with the open bracket
1128 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1129 ;; is the first list item on the same line?
1130 (skip-chars-forward " \t")
1131 (if (null (memq (following-char) '(?\n ?# ?\\)))
1132 ; yes, so line up with it
1133 (current-column)
1134 ;; first list item on another line, or doesn't exist yet
1135 (forward-line 1)
1136 (while (and (< (point) startpos)
1137 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1138 (forward-line 1))
1139 (if (< (point) startpos)
1140 ;; again mimic the first list item
1141 (current-indentation)
1142 ;; else they're about to enter the first item
1143 (goto-char open-bracket-pos)
1144 (+ (current-indentation) py-indent-offset))))
1145
1146 ;; else on backslash continuation line
1147 (forward-line -1)
1148 (if (py-continuation-line-p) ; on at least 3rd line in block
1149 (current-indentation) ; so just continue the pattern
1150 ;; else started on 2nd line in block, so indent more.
1151 ;; if base line is an assignment with a start on a RHS,
1152 ;; indent to 2 beyond the leftmost "="; else skip first
1153 ;; chunk of non-whitespace characters on base line, + 1 more
1154 ;; column
1155 (end-of-line)
1156 (setq endpos (point) searching t)
1157 (back-to-indentation)
1158 (setq startpos (point))
1159 ;; look at all "=" from left to right, stopping at first
1160 ;; one not nested in a list or string
1161 (while searching
1162 (skip-chars-forward "^=" endpos)
1163 (if (= (point) endpos)
1164 (setq searching nil)
1165 (forward-char 1)
1166 (setq state (parse-partial-sexp startpos (point)))
1167 (if (and (zerop (car state)) ; not in a bracket
1168 (null (nth 3 state))) ; & not in a string
1169 (progn
1170 (setq searching nil) ; done searching in any case
1171 (setq found
1172 (not (or
1173 (eq (following-char) ?=)
1174 (memq (char-after (- (point) 2))
1175 '(?< ?> ?!)))))))))
1176 (if (or (not found) ; not an assignment
1177 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1178 (progn
1179 (goto-char startpos)
1180 (skip-chars-forward "^ \t\n")))
1181 (1+ (current-column))))))
1182
1183 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001184 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001185
Barry Warsawa7891711996-08-01 15:53:09 +00001186 ;; Dfn: "Indenting comment line". A line containing only a
1187 ;; comment, but which is treated like a statement for
1188 ;; indentation calculation purposes. Such lines are only
1189 ;; treated specially by the mode; they are not treated
1190 ;; specially by the Python interpreter.
1191
1192 ;; The rules for indenting comment lines are a line where:
1193 ;; - the first non-whitespace character is `#', and
1194 ;; - the character following the `#' is whitespace, and
1195 ;; - the line is outdented with respect to (i.e. to the left
1196 ;; of) the indentation of the preceding non-blank line.
1197
1198 ;; The first non-blank line following an indenting comment
1199 ;; line is given the same amount of indentation as the
1200 ;; indenting comment line.
1201
1202 ;; All other comment-only lines are ignored for indentation
1203 ;; purposes.
1204
1205 ;; Are we looking at a comment-only line which is *not* an
1206 ;; indenting comment line? If so, we assume that its been
1207 ;; placed at the desired indentation, so leave it alone.
1208 ;; Indenting comment lines are aligned as statements down
1209 ;; below.
1210 ((and (looking-at "[ \t]*#[^ \t\n]")
1211 ;; NOTE: this test will not be performed in older Emacsen
1212 (fboundp 'forward-comment)
1213 (<= (current-indentation)
1214 (save-excursion
1215 (forward-comment (- (point-max)))
1216 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001217 (current-indentation))
1218
1219 ;; else indentation based on that of the statement that
1220 ;; precedes us; use the first line of that statement to
1221 ;; establish the base, in case the user forced a non-std
1222 ;; indentation for the continuation lines (if any)
1223 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001224 ;; skip back over blank & non-indenting comment lines note:
1225 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001226 ;; happens to be a continuation line too. use fast Emacs 19
1227 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001228 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001229 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001230 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001231 (let (done)
1232 (while (not done)
1233 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1234 nil 'move)
1235 (setq done (or (eq py-honor-comment-indentation t)
1236 (bobp)
1237 (/= (following-char) ?#)
1238 (not (zerop (current-column)))))
1239 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001240 ;; if we landed inside a string, go to the beginning of that
1241 ;; string. this handles triple quoted, multi-line spanning
1242 ;; strings.
1243 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001244 (+ (current-indentation)
1245 (if (py-statement-opens-block-p)
1246 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001247 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001248 (- py-indent-offset)
1249 0)))
1250 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001251
1252(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001253 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001254By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001255`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001256Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001257`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001258their own buffer-local copy), both those currently existing and those
1259created later in the Emacs session.
1260
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001261Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001262There's no excuse for such foolishness, but sometimes you have to deal
1263with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001264`py-indent-offset' to what it thinks it was when they created the
1265mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001266
1267Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001268looking for a line that opens a block of code. `py-indent-offset' is
1269set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001270statement following it. If the search doesn't succeed going forward,
1271it's tried again going backward."
1272 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001273 (let (new-value
1274 (start (point))
1275 restart
1276 (found nil)
1277 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001278 (py-goto-initial-line)
1279 (while (not (or found (eobp)))
1280 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1281 (progn
1282 (setq restart (point))
1283 (py-goto-initial-line)
1284 (if (py-statement-opens-block-p)
1285 (setq found t)
1286 (goto-char restart)))))
1287 (if found
1288 ()
1289 (goto-char start)
1290 (py-goto-initial-line)
1291 (while (not (or found (bobp)))
1292 (setq found
1293 (and
1294 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1295 (or (py-goto-initial-line) t) ; always true -- side effect
1296 (py-statement-opens-block-p)))))
1297 (setq colon-indent (current-indentation)
1298 found (and found (zerop (py-next-statement 1)))
1299 new-value (- (current-indentation) colon-indent))
1300 (goto-char start)
1301 (if found
1302 (progn
1303 (funcall (if global 'kill-local-variable 'make-local-variable)
1304 'py-indent-offset)
1305 (setq py-indent-offset new-value)
1306 (message "%s value of py-indent-offset set to %d"
1307 (if global "Global" "Local")
1308 py-indent-offset))
1309 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1310
1311(defun py-shift-region (start end count)
1312 (save-excursion
1313 (goto-char end) (beginning-of-line) (setq end (point))
1314 (goto-char start) (beginning-of-line) (setq start (point))
1315 (indent-rigidly start end count)))
1316
1317(defun py-shift-region-left (start end &optional count)
1318 "Shift region of Python code to the left.
1319The lines from the line containing the start of the current region up
1320to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001321shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001322
1323If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001324many columns. With no active region, outdent only the current line.
1325You cannot outdent the region if any line is already at column zero."
1326 (interactive
1327 (let ((p (point))
1328 (m (mark))
1329 (arg current-prefix-arg))
1330 (if m
1331 (list (min p m) (max p m) arg)
1332 (list p (save-excursion (forward-line 1) (point)) arg))))
1333 ;; if any line is at column zero, don't shift the region
1334 (save-excursion
1335 (goto-char start)
1336 (while (< (point) end)
1337 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001338 (if (and (zerop (current-column))
1339 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001340 (error "Region is at left edge."))
1341 (forward-line 1)))
1342 (py-shift-region start end (- (prefix-numeric-value
1343 (or count py-indent-offset))))
1344 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001345
1346(defun py-shift-region-right (start end &optional count)
1347 "Shift region of Python code to the right.
1348The lines from the line containing the start of the current region up
1349to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001350shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001351
1352If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001353many columns. With no active region, indent only the current line."
1354 (interactive
1355 (let ((p (point))
1356 (m (mark))
1357 (arg current-prefix-arg))
1358 (if m
1359 (list (min p m) (max p m) arg)
1360 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001362 (or count py-indent-offset)))
1363 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001364
1365(defun py-indent-region (start end &optional indent-offset)
1366 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001367
Barry Warsaw7ae77681994-12-12 20:38:05 +00001368The lines from the line containing the start of the current region up
1369to (but not including) the line containing the end of the region are
1370reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371character in the first column, the first line is left alone and the
1372rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001373region is reindented with respect to the (closest code or indenting
1374comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001375
1376This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001377control structures are introduced or removed, or to reformat code
1378using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001379
1380If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001382used.
1383
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001384Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001385is called! This function does not compute proper indentation from
1386scratch (that's impossible in Python), it merely adjusts the existing
1387indentation to be correct in context.
1388
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001389Warning: This function really has no idea what to do with
1390non-indenting comment lines, and shifts them as if they were indenting
1391comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001392
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001393Special cases: whitespace is deleted from blank lines; continuation
1394lines are shifted by the same amount their initial line was shifted,
1395in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001397 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001398 (save-excursion
1399 (goto-char end) (beginning-of-line) (setq end (point-marker))
1400 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001401 (let ((py-indent-offset (prefix-numeric-value
1402 (or indent-offset py-indent-offset)))
1403 (indents '(-1)) ; stack of active indent levels
1404 (target-column 0) ; column to which to indent
1405 (base-shifted-by 0) ; amount last base line was shifted
1406 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001407 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001408 0))
1409 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001410 (while (< (point) end)
1411 (setq ci (current-indentation))
1412 ;; figure out appropriate target column
1413 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001414 ((or (eq (following-char) ?#) ; comment in column 1
1415 (looking-at "[ \t]*$")) ; entirely blank
1416 (setq target-column 0))
1417 ((py-continuation-line-p) ; shift relative to base line
1418 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001419 (t ; new base line
1420 (if (> ci (car indents)) ; going deeper; push it
1421 (setq indents (cons ci indents))
1422 ;; else we should have seen this indent before
1423 (setq indents (memq ci indents)) ; pop deeper indents
1424 (if (null indents)
1425 (error "Bad indentation in region, at line %d"
1426 (save-restriction
1427 (widen)
1428 (1+ (count-lines 1 (point)))))))
1429 (setq target-column (+ indent-base
1430 (* py-indent-offset
1431 (- (length indents) 2))))
1432 (setq base-shifted-by (- target-column ci))))
1433 ;; shift as needed
1434 (if (/= ci target-column)
1435 (progn
1436 (delete-horizontal-space)
1437 (indent-to target-column)))
1438 (forward-line 1))))
1439 (set-marker end nil))
1440
Barry Warsawa7891711996-08-01 15:53:09 +00001441(defun py-comment-region (beg end &optional arg)
1442 "Like `comment-region' but uses double hash (`#') comment starter."
1443 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001444 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001445 (comment-region beg end arg)))
1446
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001447
1448;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449(defun py-previous-statement (count)
1450 "Go to the start of previous Python statement.
1451If the statement at point is the i'th Python statement, goes to the
1452start of statement i-COUNT. If there is no such statement, goes to the
1453first statement. Returns count of statements left to move.
1454`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001455 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001456 (if (< count 0) (py-next-statement (- count))
1457 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001458 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001460 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461 (> count 0)
1462 (zerop (forward-line -1))
1463 (py-goto-statement-at-or-above))
1464 (setq count (1- count)))
1465 (if (> count 0) (goto-char start)))
1466 count))
1467
1468(defun py-next-statement (count)
1469 "Go to the start of next Python statement.
1470If the statement at point is the i'th Python statement, goes to the
1471start of statement i+COUNT. If there is no such statement, goes to the
1472last statement. Returns count of statements left to move. `Statements'
1473do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001474 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001475 (if (< count 0) (py-previous-statement (- count))
1476 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001477 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001478 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480 (> count 0)
1481 (py-goto-statement-below))
1482 (setq count (1- count)))
1483 (if (> count 0) (goto-char start)))
1484 count))
1485
1486(defun py-goto-block-up (&optional nomark)
1487 "Move up to start of current block.
1488Go to the statement that starts the smallest enclosing block; roughly
1489speaking, this will be the closest preceding statement that ends with a
1490colon and is indented less than the statement you started on. If
1491successful, also sets the mark to the starting point.
1492
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001493`\\[py-mark-block]' can be used afterward to mark the whole code
1494block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001495
1496If called from a program, the mark will not be set if optional argument
1497NOMARK is not nil."
1498 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001499 (let ((start (point))
1500 (found nil)
1501 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001502 (py-goto-initial-line)
1503 ;; if on blank or non-indenting comment line, use the preceding stmt
1504 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1505 (progn
1506 (py-goto-statement-at-or-above)
1507 (setq found (py-statement-opens-block-p))))
1508 ;; search back for colon line indented less
1509 (setq initial-indent (current-indentation))
1510 (if (zerop initial-indent)
1511 ;; force fast exit
1512 (goto-char (point-min)))
1513 (while (not (or found (bobp)))
1514 (setq found
1515 (and
1516 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1517 (or (py-goto-initial-line) t) ; always true -- side effect
1518 (< (current-indentation) initial-indent)
1519 (py-statement-opens-block-p))))
1520 (if found
1521 (progn
1522 (or nomark (push-mark start))
1523 (back-to-indentation))
1524 (goto-char start)
1525 (error "Enclosing block not found"))))
1526
1527(defun beginning-of-python-def-or-class (&optional class)
1528 "Move point to start of def (or class, with prefix arg).
1529
1530Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531arg, looks for a `class' instead. The docs assume the `def' case;
1532just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001534If point is in a def statement already, and after the `d', simply
1535moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537Else (point is not in a def statement, or at or before the `d' of a
1538def statement), searches for the closest preceding def statement, and
1539leaves point at its start. If no such statement can be found, leaves
1540point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542Returns t iff a def statement is found by these rules.
1543
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001544Note that doing this command repeatedly will take you closer to the
1545start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001546
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547If you want to mark the current def/class, see
1548`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001549 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001550 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1551 (start-of-line (progn (beginning-of-line) (point)))
1552 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001553 (if (or (/= start-of-stmt start-of-line)
1554 (not at-or-before-p))
1555 (end-of-line)) ; OK to match on this line
1556 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001557 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001558
1559(defun end-of-python-def-or-class (&optional class)
1560 "Move point beyond end of def (or class, with prefix arg) body.
1561
1562By default, looks for an appropriate `def'. If you supply a prefix arg,
1563looks for a `class' instead. The docs assume the `def' case; just
1564substitute `class' for `def' for the other case.
1565
1566If point is in a def statement already, this is the def we use.
1567
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568Else if the def found by `\\[beginning-of-python-def-or-class]'
1569contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001570
1571Else we search forward for the closest following def, and use that.
1572
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573If a def can be found by these rules, point is moved to the start of
1574the line immediately following the def block, and the position of the
1575start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001576
1577Else point is moved to the end of the buffer, and nil is returned.
1578
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579Note that doing this command repeatedly will take you closer to the
1580end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001582If you want to mark the current def/class, see
1583`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001584 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001585 (let ((start (progn (py-goto-initial-line) (point)))
1586 (which (if class "class" "def"))
1587 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588 ;; move point to start of appropriate def/class
1589 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1590 (setq state 'at-beginning)
1591 ;; else see if beginning-of-python-def-or-class hits container
1592 (if (and (beginning-of-python-def-or-class class)
1593 (progn (py-goto-beyond-block)
1594 (> (point) start)))
1595 (setq state 'at-end)
1596 ;; else search forward
1597 (goto-char start)
1598 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1599 (progn (setq state 'at-beginning)
1600 (beginning-of-line)))))
1601 (cond
1602 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1603 ((eq state 'at-end) t)
1604 ((eq state 'not-found) nil)
1605 (t (error "internal error in end-of-python-def-or-class")))))
1606
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001607
1608;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001609(defun py-mark-block (&optional extend just-move)
1610 "Mark following block of lines. With prefix arg, mark structure.
1611Easier to use than explain. It sets the region to an `interesting'
1612block of succeeding lines. If point is on a blank line, it goes down to
1613the next non-blank line. That will be the start of the region. The end
1614of the region depends on the kind of line at the start:
1615
1616 - If a comment, the region will include all succeeding comment lines up
1617 to (but not including) the next non-comment line (if any).
1618
1619 - Else if a prefix arg is given, and the line begins one of these
1620 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001621
1622 if elif else try except finally for while def class
1623
Barry Warsaw7ae77681994-12-12 20:38:05 +00001624 the region will be set to the body of the structure, including
1625 following blocks that `belong' to it, but excluding trailing blank
1626 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001627 and all (if any) of the following `except' and `finally' blocks
1628 that belong to the `try' structure will be in the region. Ditto
1629 for if/elif/else, for/else and while/else structures, and (a bit
1630 degenerate, since they're always one-block structures) def and
1631 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632
1633 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001634 block (see list above), and the block is not a `one-liner' (i.e.,
1635 the statement ends with a colon, not with code), the region will
1636 include all succeeding lines up to (but not including) the next
1637 code statement (if any) that's indented no more than the starting
1638 line, except that trailing blank and comment lines are excluded.
1639 E.g., if the starting line begins a multi-statement `def'
1640 structure, the region will be set to the full function definition,
1641 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001642
1643 - Else the region will include all succeeding lines up to (but not
1644 including) the next blank line, or code or indenting-comment line
1645 indented strictly less than the starting line. Trailing indenting
1646 comment lines are included in this case, but not trailing blank
1647 lines.
1648
1649A msg identifying the location of the mark is displayed in the echo
1650area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1651
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001652If called from a program, optional argument EXTEND plays the role of
1653the prefix arg, and if optional argument JUST-MOVE is not nil, just
1654moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001655 (interactive "P") ; raw prefix arg
1656 (py-goto-initial-line)
1657 ;; skip over blank lines
1658 (while (and
1659 (looking-at "[ \t]*$") ; while blank line
1660 (not (eobp))) ; & somewhere to go
1661 (forward-line 1))
1662 (if (eobp)
1663 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664 (let ((initial-pos (point))
1665 (initial-indent (current-indentation))
1666 last-pos ; position of last stmt in region
1667 (followers
1668 '((if elif else) (elif elif else) (else)
1669 (try except finally) (except except) (finally)
1670 (for else) (while else)
1671 (def) (class) ) )
1672 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001673
1674 (cond
1675 ;; if comment line, suck up the following comment lines
1676 ((looking-at "[ \t]*#")
1677 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1678 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1679 (setq last-pos (point)))
1680
1681 ;; else if line is a block line and EXTEND given, suck up
1682 ;; the whole structure
1683 ((and extend
1684 (setq first-symbol (py-suck-up-first-keyword) )
1685 (assq first-symbol followers))
1686 (while (and
1687 (or (py-goto-beyond-block) t) ; side effect
1688 (forward-line -1) ; side effect
1689 (setq last-pos (point)) ; side effect
1690 (py-goto-statement-below)
1691 (= (current-indentation) initial-indent)
1692 (setq next-symbol (py-suck-up-first-keyword))
1693 (memq next-symbol (cdr (assq first-symbol followers))))
1694 (setq first-symbol next-symbol)))
1695
1696 ;; else if line *opens* a block, search for next stmt indented <=
1697 ((py-statement-opens-block-p)
1698 (while (and
1699 (setq last-pos (point)) ; always true -- side effect
1700 (py-goto-statement-below)
1701 (> (current-indentation) initial-indent))
1702 nil))
1703
1704 ;; else plain code line; stop at next blank line, or stmt or
1705 ;; indenting comment line indented <
1706 (t
1707 (while (and
1708 (setq last-pos (point)) ; always true -- side effect
1709 (or (py-goto-beyond-final-line) t)
1710 (not (looking-at "[ \t]*$")) ; stop at blank line
1711 (or
1712 (>= (current-indentation) initial-indent)
1713 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1714 nil)))
1715
1716 ;; skip to end of last stmt
1717 (goto-char last-pos)
1718 (py-goto-beyond-final-line)
1719
1720 ;; set mark & display
1721 (if just-move
1722 () ; just return
1723 (push-mark (point) 'no-msg)
1724 (forward-line -1)
1725 (message "Mark set after: %s" (py-suck-up-leading-text))
1726 (goto-char initial-pos))))
1727
1728(defun mark-python-def-or-class (&optional class)
1729 "Set region to body of def (or class, with prefix arg) enclosing point.
1730Pushes the current mark, then point, on the mark ring (all language
1731modes do this, but although it's handy it's never documented ...).
1732
1733In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001734hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1735`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001736
1737And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738Turned out that was more confusing than useful: the `goto start' and
1739`goto end' commands are usually used to search through a file, and
1740people expect them to act a lot like `search backward' and `search
1741forward' string-search commands. But because Python `def' and `class'
1742can nest to arbitrary levels, finding the smallest def containing
1743point cannot be done via a simple backward search: the def containing
1744point may not be the closest preceding def, or even the closest
1745preceding def that's indented less. The fancy algorithm required is
1746appropriate for the usual uses of this `mark' command, but not for the
1747`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001748
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749So the def marked by this command may not be the one either of the
1750`goto' commands find: If point is on a blank or non-indenting comment
1751line, moves back to start of the closest preceding code statement or
1752indenting comment line. If this is a `def' statement, that's the def
1753we use. Else searches for the smallest enclosing `def' block and uses
1754that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001755
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756When an enclosing def is found: The mark is left immediately beyond
1757the last line of the def block. Point is left at the start of the
1758def, except that: if the def is preceded by a number of comment lines
1759followed by (at most) one optional blank line, point is left at the
1760start of the comments; else if the def is preceded by a blank line,
1761point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762
1763The intent is to mark the containing def/class and its associated
1764documentation, to make moving and duplicating functions and classes
1765pleasant."
1766 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001767 (let ((start (point))
1768 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001769 (push-mark start)
1770 (if (not (py-go-up-tree-to-keyword which))
1771 (progn (goto-char start)
1772 (error "Enclosing %s not found" which))
1773 ;; else enclosing def/class found
1774 (setq start (point))
1775 (py-goto-beyond-block)
1776 (push-mark (point))
1777 (goto-char start)
1778 (if (zerop (forward-line -1)) ; if there is a preceding line
1779 (progn
1780 (if (looking-at "[ \t]*$") ; it's blank
1781 (setq start (point)) ; so reset start point
1782 (goto-char start)) ; else try again
1783 (if (zerop (forward-line -1))
1784 (if (looking-at "[ \t]*#") ; a comment
1785 ;; look back for non-comment line
1786 ;; tricky: note that the regexp matches a blank
1787 ;; line, cuz \n is in the 2nd character class
1788 (and
1789 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1790 (forward-line 1))
1791 ;; no comment, so go back
1792 (goto-char start))))))))
1793
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001794;; ripped from cc-mode
1795(defun py-forward-into-nomenclature (&optional arg)
1796 "Move forward to end of a nomenclature section or word.
1797With arg, to it arg times.
1798
1799A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1800 (interactive "p")
1801 (let ((case-fold-search nil))
1802 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001803 (re-search-forward
1804 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1805 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001806 (while (and (< arg 0)
1807 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001808 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001809 (point-min) 0))
1810 (forward-char 1)
1811 (setq arg (1+ arg)))))
1812 (py-keep-region-active))
1813
1814(defun py-backward-into-nomenclature (&optional arg)
1815 "Move backward to beginning of a nomenclature section or word.
1816With optional ARG, move that many times. If ARG is negative, move
1817forward.
1818
1819A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1820 (interactive "p")
1821 (py-forward-into-nomenclature (- arg))
1822 (py-keep-region-active))
1823
1824
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825
1826;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827
1828;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001829;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1830;; out of the right places, along with the keys they're on & current
1831;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832(defun py-dump-help-string (str)
1833 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834 (let ((locals (buffer-local-variables))
1835 funckind funcname func funcdoc
1836 (start 0) mstart end
1837 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001838 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1839 (setq mstart (match-beginning 0) end (match-end 0)
1840 funckind (substring str (match-beginning 1) (match-end 1))
1841 funcname (substring str (match-beginning 2) (match-end 2))
1842 func (intern funcname))
1843 (princ (substitute-command-keys (substring str start mstart)))
1844 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001845 ((equal funckind "c") ; command
1846 (setq funcdoc (documentation func)
1847 keys (concat
1848 "Key(s): "
1849 (mapconcat 'key-description
1850 (where-is-internal func py-mode-map)
1851 ", "))))
1852 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001853 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854 keys (if (assq func locals)
1855 (concat
1856 "Local/Global values: "
1857 (prin1-to-string (symbol-value func))
1858 " / "
1859 (prin1-to-string (default-value func)))
1860 (concat
1861 "Value: "
1862 (prin1-to-string (symbol-value func))))))
1863 (t ; unexpected
1864 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001865 (princ (format "\n-> %s:\t%s\t%s\n\n"
1866 (if (equal funckind "c") "Command" "Variable")
1867 funcname keys))
1868 (princ funcdoc)
1869 (terpri)
1870 (setq start end))
1871 (princ (substitute-command-keys (substring str start))))
1872 (print-help-return-message)))
1873
1874(defun py-describe-mode ()
1875 "Dump long form of Python-mode docs."
1876 (interactive)
1877 (py-dump-help-string "Major mode for editing Python files.
1878Knows about Python indentation, tokens, comments and continuation lines.
1879Paragraphs are separated by blank lines only.
1880
1881Major sections below begin with the string `@'; specific function and
1882variable docs begin with `->'.
1883
1884@EXECUTING PYTHON CODE
1885
1886\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1887\\[py-execute-region]\tsends the current region
1888\\[py-shell]\tstarts a Python interpreter window; this will be used by
1889\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1890%c:py-execute-buffer
1891%c:py-execute-region
1892%c:py-shell
1893
1894@VARIABLES
1895
1896py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001897py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001898
1899py-python-command\tshell command to invoke Python interpreter
1900py-scroll-process-buffer\talways scroll Python process buffer
1901py-temp-directory\tdirectory used for temp files (if needed)
1902
1903py-beep-if-tab-change\tring the bell if tab-width is changed
1904%v:py-indent-offset
1905%v:py-block-comment-prefix
1906%v:py-python-command
1907%v:py-scroll-process-buffer
1908%v:py-temp-directory
1909%v:py-beep-if-tab-change
1910
1911@KINDS OF LINES
1912
1913Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914preceding line ends with a backslash that's not part of a comment, or
1915the paren/bracket/brace nesting level at the start of the line is
1916non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917
1918An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001919possibly blanks or tabs), a `comment line' (leftmost non-blank
1920character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001921
1922Comment Lines
1923
1924Although all comment lines are treated alike by Python, Python mode
1925recognizes two kinds that act differently with respect to indentation.
1926
1927An `indenting comment line' is a comment line with a blank, tab or
1928nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930indenting comment line will be indented like the comment line. All
1931other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001932following the initial `#') are `non-indenting comment lines', and
1933their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934
1935Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936whenever possible. Non-indenting comment lines are useful in cases
1937like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938
1939\ta = b # a very wordy single-line comment that ends up being
1940\t #... continued onto another line
1941
1942\tif a == b:
1943##\t\tprint 'panic!' # old code we've `commented out'
1944\t\treturn a
1945
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001946Since the `#...' and `##' comment lines have a non-whitespace
1947character following the initial `#', Python mode ignores them when
1948computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949
1950Continuation Lines and Statements
1951
1952The Python-mode commands generally work on statements instead of on
1953individual lines, where a `statement' is a comment or blank line, or a
1954code line and all of its following continuation lines (if any)
1955considered as a single logical unit. The commands in this mode
1956generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001957statement containing point, even if point happens to be in the middle
1958of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001959
1960
1961@INDENTATION
1962
1963Primarily for entering new code:
1964\t\\[indent-for-tab-command]\t indent line appropriately
1965\t\\[py-newline-and-indent]\t insert newline, then indent
1966\t\\[py-delete-char]\t reduce indentation, or delete single character
1967
1968Primarily for reindenting existing code:
1969\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1970\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1971
1972\t\\[py-indent-region]\t reindent region to match its context
1973\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1974\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1975
1976Unlike most programming languages, Python uses indentation, and only
1977indentation, to specify block structure. Hence the indentation supplied
1978automatically by Python-mode is just an educated guess: only you know
1979the block structure you intend, so only you can supply correct
1980indentation.
1981
1982The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1983the indentation of preceding statements. E.g., assuming
1984py-indent-offset is 4, after you enter
1985\tif a > 0: \\[py-newline-and-indent]
1986the cursor will be moved to the position of the `_' (_ is not a
1987character in the file, it's just used here to indicate the location of
1988the cursor):
1989\tif a > 0:
1990\t _
1991If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1992to
1993\tif a > 0:
1994\t c = d
1995\t _
1996Python-mode cannot know whether that's what you intended, or whether
1997\tif a > 0:
1998\t c = d
1999\t_
2000was your intent. In general, Python-mode either reproduces the
2001indentation of the (closest code or indenting-comment) preceding
2002statement, or adds an extra py-indent-offset blanks if the preceding
2003statement has `:' as its last significant (non-whitespace and non-
2004comment) character. If the suggested indentation is too much, use
2005\\[py-delete-char] to reduce it.
2006
2007Continuation lines are given extra indentation. If you don't like the
2008suggested indentation, change it to something you do like, and Python-
2009mode will strive to indent later lines of the statement in the same way.
2010
2011If a line is a continuation line by virtue of being in an unclosed
2012paren/bracket/brace structure (`list', for short), the suggested
2013indentation depends on whether the current line contains the first item
2014in the list. If it does, it's indented py-indent-offset columns beyond
2015the indentation of the line containing the open bracket. If you don't
2016like that, change it by hand. The remaining items in the list will mimic
2017whatever indentation you give to the first item.
2018
2019If a line is a continuation line because the line preceding it ends with
2020a backslash, the third and following lines of the statement inherit their
2021indentation from the line preceding them. The indentation of the second
2022line in the statement depends on the form of the first (base) line: if
2023the base line is an assignment statement with anything more interesting
2024than the backslash following the leftmost assigning `=', the second line
2025is indented two columns beyond that `='. Else it's indented to two
2026columns beyond the leftmost solid chunk of non-whitespace characters on
2027the base line.
2028
2029Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2030repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2031structure you intend.
2032%c:indent-for-tab-command
2033%c:py-newline-and-indent
2034%c:py-delete-char
2035
2036
2037The next function may be handy when editing code you didn't write:
2038%c:py-guess-indent-offset
2039
2040
2041The remaining `indent' functions apply to a region of Python code. They
2042assume the block structure (equals indentation, in Python) of the region
2043is correct, and alter the indentation in various ways while preserving
2044the block structure:
2045%c:py-indent-region
2046%c:py-shift-region-left
2047%c:py-shift-region-right
2048
2049@MARKING & MANIPULATING REGIONS OF CODE
2050
2051\\[py-mark-block]\t mark block of lines
2052\\[mark-python-def-or-class]\t mark smallest enclosing def
2053\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002054\\[comment-region]\t comment out region of code
2055\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002056%c:py-mark-block
2057%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002058%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059
2060@MOVING POINT
2061
2062\\[py-previous-statement]\t move to statement preceding point
2063\\[py-next-statement]\t move to statement following point
2064\\[py-goto-block-up]\t move up to start of current block
2065\\[beginning-of-python-def-or-class]\t move to start of def
2066\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2067\\[end-of-python-def-or-class]\t move to end of def
2068\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2069
2070The first two move to one statement beyond the statement that contains
2071point. A numeric prefix argument tells them to move that many
2072statements instead. Blank lines, comment lines, and continuation lines
2073do not count as `statements' for these commands. So, e.g., you can go
2074to the first code statement in a file by entering
2075\t\\[beginning-of-buffer]\t to move to the top of the file
2076\t\\[py-next-statement]\t to skip over initial comments and blank lines
2077Or do `\\[py-previous-statement]' with a huge prefix argument.
2078%c:py-previous-statement
2079%c:py-next-statement
2080%c:py-goto-block-up
2081%c:beginning-of-python-def-or-class
2082%c:end-of-python-def-or-class
2083
2084@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2085
2086`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2087
2088`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2089overall class and def structure of a module.
2090
2091`\\[back-to-indentation]' moves point to a line's first non-blank character.
2092
2093`\\[indent-relative]' is handy for creating odd indentation.
2094
2095@OTHER EMACS HINTS
2096
2097If you don't like the default value of a variable, change its value to
2098whatever you do like by putting a `setq' line in your .emacs file.
2099E.g., to set the indentation increment to 4, put this line in your
2100.emacs:
2101\t(setq py-indent-offset 4)
2102To see the value of a variable, do `\\[describe-variable]' and enter the variable
2103name at the prompt.
2104
2105When entering a key sequence like `C-c C-n', it is not necessary to
2106release the CONTROL key after doing the `C-c' part -- it suffices to
2107press the CONTROL key, press and release `c' (while still holding down
2108CONTROL), press and release `n' (while still holding down CONTROL), &
2109then release CONTROL.
2110
2111Entering Python mode calls with no arguments the value of the variable
2112`python-mode-hook', if that value exists and is not nil; for backward
2113compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2114the Elisp manual for details.
2115
2116Obscure: When python-mode is first loaded, it looks for all bindings
2117to newline-and-indent in the global keymap, and shadows them with
2118local bindings to py-newline-and-indent."))
2119
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002120
2121;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002122(defvar py-parse-state-re
2123 (concat
2124 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2125 "\\|"
2126 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002127
Barry Warsaw7ae77681994-12-12 20:38:05 +00002128;; returns the parse state at point (see parse-partial-sexp docs)
2129(defun py-parse-state ()
2130 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002131 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002132 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002133 (while (not done)
2134 ;; back up to the first preceding line (if any; else start of
2135 ;; buffer) that begins with a popular Python keyword, or a
2136 ;; non- whitespace and non-comment character. These are good
2137 ;; places to start parsing to see whether where we started is
2138 ;; at a non-zero nesting level. It may be slow for people who
2139 ;; write huge code blocks or huge lists ... tough beans.
2140 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002141 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002142 (beginning-of-line)
2143 (save-excursion
2144 (setq pps (parse-partial-sexp (point) here)))
2145 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002146 (setq done (or (zerop ci)
2147 (not (nth 3 pps))
2148 (bobp)))
2149 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002150 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151
2152;; if point is at a non-zero nesting level, returns the number of the
2153;; character that opens the smallest enclosing unclosed list; else
2154;; returns nil.
2155(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002156 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002157 (if (zerop (car status))
2158 nil ; not in a nest
2159 (car (cdr status))))) ; char# of open bracket
2160
2161;; t iff preceding line ends with backslash that's not in a comment
2162(defun py-backslash-continuation-line-p ()
2163 (save-excursion
2164 (beginning-of-line)
2165 (and
2166 ;; use a cheap test first to avoid the regexp if possible
2167 ;; use 'eq' because char-after may return nil
2168 (eq (char-after (- (point) 2)) ?\\ )
2169 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002170 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002171 (looking-at py-continued-re))))
2172
2173;; t iff current line is a continuation line
2174(defun py-continuation-line-p ()
2175 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002176 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002177 (or (py-backslash-continuation-line-p)
2178 (py-nesting-level))))
2179
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002180;; go to initial line of current statement; usually this is the line
2181;; we're on, but if we're on the 2nd or following lines of a
2182;; continuation block, we need to go up to the first line of the
2183;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002184;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002185;; Tricky: We want to avoid quadratic-time behavior for long continued
2186;; blocks, whether of the backslash or open-bracket varieties, or a
2187;; mix of the two. The following manages to do that in the usual
2188;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002189(defun py-goto-initial-line ()
2190 (let ( open-bracket-pos )
2191 (while (py-continuation-line-p)
2192 (beginning-of-line)
2193 (if (py-backslash-continuation-line-p)
2194 (while (py-backslash-continuation-line-p)
2195 (forward-line -1))
2196 ;; else zip out of nested brackets/braces/parens
2197 (while (setq open-bracket-pos (py-nesting-level))
2198 (goto-char open-bracket-pos)))))
2199 (beginning-of-line))
2200
2201;; go to point right beyond final line of current statement; usually
2202;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002203;; statement we need to skip over the continuation lines. Tricky:
2204;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002205(defun py-goto-beyond-final-line ()
2206 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002207 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002208 (while (and (py-continuation-line-p)
2209 (not (eobp)))
2210 ;; skip over the backslash flavor
2211 (while (and (py-backslash-continuation-line-p)
2212 (not (eobp)))
2213 (forward-line 1))
2214 ;; if in nest, zip to the end of the nest
2215 (setq state (py-parse-state))
2216 (if (and (not (zerop (car state)))
2217 (not (eobp)))
2218 (progn
Barry Warsawf7705781997-01-30 19:49:39 +00002219 (parse-partial-sexp (point) (point-max)
2220 (if py-parse-partial-sexp-works-p
2221 0 (- 0 (car state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002222 nil state)
2223 (forward-line 1))))))
2224
2225;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002226;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227(defun py-statement-opens-block-p ()
2228 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002229 (let ((start (point))
2230 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2231 (searching t)
2232 (answer nil)
2233 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002234 (goto-char start)
2235 (while searching
2236 ;; look for a colon with nothing after it except whitespace, and
2237 ;; maybe a comment
2238 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2239 finish t)
2240 (if (eq (point) finish) ; note: no `else' clause; just
2241 ; keep searching if we're not at
2242 ; the end yet
2243 ;; sure looks like it opens a block -- but it might
2244 ;; be in a comment
2245 (progn
2246 (setq searching nil) ; search is done either way
2247 (setq state (parse-partial-sexp start
2248 (match-beginning 0)))
2249 (setq answer (not (nth 4 state)))))
2250 ;; search failed: couldn't find another interesting colon
2251 (setq searching nil)))
2252 answer)))
2253
Barry Warsawf831d811996-07-31 20:42:59 +00002254(defun py-statement-closes-block-p ()
2255 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002256 ;; starts with `return', `raise', `break', `continue', and `pass'.
2257 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002258 (let ((here (point)))
2259 (back-to-indentation)
2260 (prog1
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002261 (looking-at "\\(return\\|raise\\|break\\|continue\\|pass\\)\\>")
Barry Warsawf831d811996-07-31 20:42:59 +00002262 (goto-char here))))
2263
Barry Warsaw7ae77681994-12-12 20:38:05 +00002264;; go to point right beyond final line of block begun by the current
2265;; line. This is the same as where py-goto-beyond-final-line goes
2266;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002267;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002268(defun py-goto-beyond-block ()
2269 (if (py-statement-opens-block-p)
2270 (py-mark-block nil 'just-move)
2271 (py-goto-beyond-final-line)))
2272
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002273;; go to start of first statement (not blank or comment or
2274;; continuation line) at or preceding point. returns t if there is
2275;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002276(defun py-goto-statement-at-or-above ()
2277 (py-goto-initial-line)
2278 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002279 ;; skip back over blank & comment lines
2280 ;; note: will skip a blank or comment line that happens to be
2281 ;; a continuation line too
2282 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2283 (progn (py-goto-initial-line) t)
2284 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002285 t))
2286
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002287;; go to start of first statement (not blank or comment or
2288;; continuation line) following the statement containing point returns
2289;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002290(defun py-goto-statement-below ()
2291 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002292 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002293 (py-goto-beyond-final-line)
2294 (while (and
2295 (looking-at py-blank-or-comment-re)
2296 (not (eobp)))
2297 (forward-line 1))
2298 (if (eobp)
2299 (progn (goto-char start) nil)
2300 t)))
2301
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002302;; go to start of statement, at or preceding point, starting with
2303;; keyword KEY. Skips blank lines and non-indenting comments upward
2304;; first. If that statement starts with KEY, done, else go back to
2305;; first enclosing block starting with KEY. If successful, leaves
2306;; point at the start of the KEY line & returns t. Else leaves point
2307;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002308(defun py-go-up-tree-to-keyword (key)
2309 ;; skip blanks and non-indenting #
2310 (py-goto-initial-line)
2311 (while (and
2312 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2313 (zerop (forward-line -1))) ; go back
2314 nil)
2315 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002316 (let* ((re (concat "[ \t]*" key "\\b"))
2317 (case-fold-search nil) ; let* so looking-at sees this
2318 (found (looking-at re))
2319 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002320 (while (not (or found dead))
2321 (condition-case nil ; in case no enclosing block
2322 (py-goto-block-up 'no-mark)
2323 (error (setq dead t)))
2324 (or dead (setq found (looking-at re))))
2325 (beginning-of-line)
2326 found))
2327
2328;; return string in buffer from start of indentation to end of line;
2329;; prefix "..." if leading whitespace was skipped
2330(defun py-suck-up-leading-text ()
2331 (save-excursion
2332 (back-to-indentation)
2333 (concat
2334 (if (bolp) "" "...")
2335 (buffer-substring (point) (progn (end-of-line) (point))))))
2336
2337;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2338;; as a Lisp symbol; return nil if none
2339(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002340 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2342 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2343 nil)))
2344
2345(defun py-make-temp-name ()
2346 (make-temp-name
2347 (concat (file-name-as-directory py-temp-directory) "python")))
2348
2349(defun py-delete-file-silently (fname)
2350 (condition-case nil
2351 (delete-file fname)
2352 (error nil)))
2353
2354(defun py-kill-emacs-hook ()
2355 ;; delete our temp files
2356 (while py-file-queue
2357 (py-delete-file-silently (car py-file-queue))
2358 (setq py-file-queue (cdr py-file-queue)))
2359 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2360 ;; run the hook we inherited, if any
2361 (and py-inherited-kill-emacs-hook
2362 (funcall py-inherited-kill-emacs-hook))))
2363
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002364;; make PROCESS's buffer visible, append STRING to it, and force
2365;; display; also make shell-mode believe the user typed this string,
2366;; so that kill-output-from-shell and show-output-from-shell work
2367;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002368(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002369 (let ((cbuf (current-buffer))
2370 (pbuf (process-buffer process))
2371 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002372 (set-buffer pbuf)
2373 (goto-char (point-max))
2374 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002375 (if (not (or py-this-is-emacs-19-p
2376 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002377 (move-marker last-input-start (point))) ; muck w/ shell-mode
2378 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002379 (if (not (or py-this-is-emacs-19-p
2380 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002381 (move-marker last-input-end (point))) ; muck w/ shell-mode
2382 (set-buffer cbuf))
2383 (sit-for 0))
2384
Barry Warsaw3622e0d1996-10-29 15:32:57 +00002385;; older Emacsen don't have this function
2386(if (not (fboundp 'match-string))
2387 (defun match-string (n)
2388 (let ((beg (match-beginning n))
2389 (end (match-end n)))
2390 (if (and beg end)
2391 (buffer-substring beg end)
2392 nil))))
2393
Barry Warsawb3e81d51996-09-04 15:12:42 +00002394(defun py-current-defun ()
2395 ;; tell add-log.el how to find the current function/method/variable
2396 (save-excursion
2397 (if (re-search-backward py-defun-start-re nil t)
2398 (or (match-string 3)
2399 (let ((method (match-string 2)))
2400 (if (and (not (zerop (length (match-string 1))))
2401 (re-search-backward py-class-start-re nil t))
2402 (concat (match-string 1) "." method)
2403 method)))
2404 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002405
2406
Barry Warsaw850437a1995-03-08 21:50:28 +00002407(defconst py-version "$Revision$"
2408 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002409(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002410 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002411
Barry Warsaw850437a1995-03-08 21:50:28 +00002412(defun py-version ()
2413 "Echo the current version of `python-mode' in the minibuffer."
2414 (interactive)
2415 (message "Using `python-mode' version %s" py-version)
2416 (py-keep-region-active))
2417
2418;; only works under Emacs 19
2419;(eval-when-compile
2420; (require 'reporter))
2421
2422(defun py-submit-bug-report (enhancement-p)
2423 "Submit via mail a bug report on `python-mode'.
2424With \\[universal-argument] just submit an enhancement request."
2425 (interactive
2426 (list (not (y-or-n-p
2427 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002428 (let ((reporter-prompt-for-summary-p (if enhancement-p
2429 "(Very) brief summary: "
2430 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002431 (require 'reporter)
2432 (reporter-submit-bug-report
2433 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002434 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002435 ;; varlist
2436 (if enhancement-p nil
2437 '(py-python-command
2438 py-indent-offset
2439 py-block-comment-prefix
2440 py-scroll-process-buffer
2441 py-temp-directory
2442 py-beep-if-tab-change))
2443 nil ;pre-hooks
2444 nil ;post-hooks
2445 "Dear Barry,") ;salutation
2446 (if enhancement-p nil
2447 (set-mark (point))
2448 (insert
2449"Please replace this text with a sufficiently large code sample\n\
2450and an exact recipe so that I can reproduce your problem. Failure\n\
2451to do so may mean a greater delay in fixing your bug.\n\n")
2452 (exchange-point-and-mark)
2453 (py-keep-region-active))))
2454
2455
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002456;; arrange to kill temp files when Emacs exists
2457(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2458 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2459 ;; have to trust that other people are as respectful of our hook
2460 ;; fiddling as we are of theirs
2461 (if (boundp 'py-inherited-kill-emacs-hook)
2462 ;; we were loaded before -- trust others not to have screwed us
2463 ;; in the meantime (no choice, really)
2464 nil
2465 ;; else arrange for our hook to run theirs
2466 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2467 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2468
2469
2470
2471(provide 'python-mode)
2472;;; python-mode.el ends here