blob: eb947593621a438d62fa1925410a501bc61d037c [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 Warsawfec75d61995-07-05 23:26:15 +00005;; Author: 1995 Barry A. Warsaw
6;; 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$
11;; Keywords: python editing language major-mode
12
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
22;; by Tim Peters <tim@ksr.com> after an original idea by Michael
23;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
Barry Warsawcfec3591995-03-10 15:58:16 +000024;; have undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
27;; line with GNU Emacs Lisp coding standards. But all in all, the
28;; mode works exceedingly well.
29
30;; The following statements, placed in your .emacs file or
31;; site-init.el, will cause this file to be autoloaded, and
32;; python-mode invoked, when visiting .py files (assuming this file is
33;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000034;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000035;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;; (setq auto-mode-alist
37;; (cons '("\\.py$" . python-mode) auto-mode-alist))
38
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000039;; Here's a brief list of recent additions/improvements:
40;;
41;; - Wrapping and indentation within triple quote strings should work
42;; properly now.
43;; - `Standard' bug reporting mechanism (use C-c C-b)
44;; - py-mark-block was moved to C-c C-m
45;; - C-c C-v shows you the python-mode version
46;; - a basic python-font-lock-keywords has been added for Emacs 19
47;; font-lock colorizations.
48;; - proper interaction with pending-del and del-sel modes.
49;; - New py-electric-colon (:) command for improved outdenting. Also
50;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +000051;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000052
Barry Warsaw7b0f5681995-03-08 21:33:04 +000053;; Here's a brief to do list:
54;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000055;; - Better integration with gud-mode for debugging.
56;; - Rewrite according to GNU Emacs Lisp standards.
57;; - py-delete-char should obey numeric arguments.
58;; - even better support for outdenting. Guido suggests outdents of
59;; at least one level after a return, raise, break, or continue
60;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000061;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000062
Barry Warsaw7b0f5681995-03-08 21:33:04 +000063;; If you can think of more things you'd like to see, drop me a line.
64;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
65;;
66;; Note that I only test things on XEmacs (currently 19.11). If you
67;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
68;; patches.
Barry Warsaw7ae77681994-12-12 20:38:05 +000069
Barry Warsaw7b0f5681995-03-08 21:33:04 +000070;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000071;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000072;; |Major mode for editing Python programs
73;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000074
Barry Warsaw7b0f5681995-03-08 21:33:04 +000075;;; Code:
76
77
78;; user definable variables
79;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
81(defvar py-python-command "python"
82 "*Shell command used to start Python interpreter.")
83
84(defvar py-indent-offset 8 ; argue with Guido <grin>
85 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000086Note that `\\[py-guess-indent-offset]' can usually guess a good value
87when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000088
89(defvar py-block-comment-prefix "##"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000090 "*String used by `py-comment-region' to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000091This should follow the convention for non-indenting comment lines so
92that the indentation commands won't get confused (i.e., the string
93should be of the form `#x...' where `x' is not a blank or a tab, and
94`...' is arbitrary).")
95
96(defvar py-scroll-process-buffer t
97 "*Scroll Python process buffer as output arrives.
98If nil, the Python process buffer acts, with respect to scrolling, like
99Shell-mode buffers normally act. This is surprisingly complicated and
100so won't be explained here; in fact, you can't get the whole story
101without studying the Emacs C code.
102
103If non-nil, the behavior is different in two respects (which are
104slightly inaccurate in the interest of brevity):
105
106 - If the buffer is in a window, and you left point at its end, the
107 window will scroll as new output arrives, and point will move to the
108 buffer's end, even if the window is not the selected window (that
109 being the one the cursor is in). The usual behavior for shell-mode
110 windows is not to scroll, and to leave point where it was, if the
111 buffer is in a window other than the selected window.
112
113 - If the buffer is not visible in any window, and you left point at
114 its end, the buffer will be popped into a window as soon as more
115 output arrives. This is handy if you have a long-running
116 computation and don't want to tie up screen area waiting for the
117 output. The usual behavior for a shell-mode buffer is to stay
118 invisible until you explicitly visit it.
119
120Note the `and if you left point at its end' clauses in both of the
121above: you can `turn off' the special behaviors while output is in
122progress, by visiting the Python buffer and moving point to anywhere
123besides the end. Then the buffer won't scroll, point will remain where
124you leave it, and if you hide the buffer it will stay hidden until you
125visit it again. You can enable and disable the special behaviors as
126often as you like, while output is in progress, by (respectively) moving
127point to, or away from, the end of the buffer.
128
129Warning: If you expect a large amount of output, you'll probably be
130happier setting this option to nil.
131
132Obscure: `End of buffer' above should really say `at or beyond the
133process mark', but if you know what that means you didn't need to be
134told <grin>.")
135
136(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000137 (let ((ok '(lambda (x)
138 (and x
139 (setq x (expand-file-name x)) ; always true
140 (file-directory-p x)
141 (file-writable-p x)
142 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000143 (or (funcall ok (getenv "TMPDIR"))
144 (funcall ok "/usr/tmp")
145 (funcall ok "/tmp")
146 (funcall ok ".")
147 (error
148 "Couldn't find a usable temp directory -- set py-temp-directory")))
149 "*Directory used for temp files created by a *Python* process.
150By default, the first directory from this list that exists and that you
151can write into: the value (if any) of the environment variable TMPDIR,
152/usr/tmp, /tmp, or the current directory.")
153
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000154(defvar py-beep-if-tab-change t
155 "*Ring the bell if tab-width is changed.
156If a comment of the form
157
158 \t# vi:set tabsize=<number>:
159
160is found before the first code line when the file is entered, and the
161current value of (the general Emacs variable) `tab-width' does not
162equal <number>, `tab-width' is set to <number>, a message saying so is
163displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
164the Emacs bell is also rung as a warning.")
165
Barry Warsaw4d82c9a1995-07-05 22:50:55 +0000166;; These were the previous font-lock keywords, but I think I now
167;; prefer the ones from XEmacs 19.12's font-lock.el. I've merged the
168;; two into the new definition below.
169;;
170;;(defvar python-font-lock-keywords
171;; (list
172;; (cons
173;; (concat
174;; "\\<\\("
175;; (mapconcat
176;; 'identity
177;; '("access" "and" "break" "continue"
178;; "del" "elif" "else" "except"
179;; "exec" "finally" "for" "from"
180;; "global" "if" "import" "in"
181;; "is" "lambda" "not" "or"
182;; "pass" "print" "raise" "return"
183;; "try" "while" "def" "class"
184;; )
185;; "\\|")
186;; "\\)\\>")
187;; 1)
188;; ;; functions
189;; '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
190;; ;; classes
191;; '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
192;; )
193;; "*Additional keywords to highlight `python-mode' buffers.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000194
Barry Warsaw4d82c9a1995-07-05 22:50:55 +0000195;; These are taken from XEmacs 19.12's font-lock.el file, but have the
196;; more complete list of keywords from the previous definition in
197;; python-mode.el. There are a few other minor stylistic changes as
198;; well.
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000199;;
Barry Warsaw4d82c9a1995-07-05 22:50:55 +0000200(defvar python-font-lock-keywords
201 (list
202 (cons (concat
203 "\\b\\("
204 (mapconcat
205 'identity
206 '("access" "and" "break" "continue"
207 "del" "elif" "else:" "except"
208 "except:" "exec" "finally:" "for"
209 "from" "global" "if" "import"
210 "in" "is" "lambda" "not"
211 "or" "pass" "print" "raise"
212 "return" "try:" "while"
213 )
214 "\\|")
215 "\\)[ \n\t(]")
216 1)
217 ;; classes
218 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
219 1 font-lock-type-face)
220 ;; functions
221 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
222 1 font-lock-function-name-face)
223 )
224 "*Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000225
226;; R Lindsay Todd <toddr@rpi.edu> suggests these changes to the
227;; original keywords, which wouldn't be necessary if we go with the
228;; XEmacs defaults, but which I agree makes sense without them.
229;;
230;; functions
231;; '("\\bdef\\s +\\(\\sw+\\)\\s *(" 1 font-lock-function-name-face)
232;; classes
233;; '("\\bclass\\s +\\(\\sw+\\)\\s *[(:]" 1 font-lock-type-face)
234
235
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000236
237;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
238;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
239
240;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
241;; seems to be the standard way of checking this.
242;; BAW - This is *not* the right solution. When at all possible,
243;; instead of testing for the version of Emacs, use feature tests.
244
245(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
246(setq py-this-is-emacs-19-p
247 (and
248 (not py-this-is-lucid-emacs-p)
249 (string-match "^19\\." emacs-version)))
250
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251;; have to bind py-file-queue before installing the kill-emacs hook
252(defvar py-file-queue nil
253 "Queue of Python temp files awaiting execution.
254Currently-active file is at the head of the list.")
255
256;; define a mode-specific abbrev table for those who use such things
257(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000258 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000259(define-abbrev-table 'python-mode-abbrev-table nil)
260
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261(defvar python-mode-hook nil
262 "*Hook called by `python-mode'.")
263
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000264;; in previous version of python-mode.el, the hook was incorrectly
265;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000266(and (fboundp 'make-obsolete-variable)
267 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
268
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000269(defvar py-mode-map ()
270 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271
Barry Warsaw7ae77681994-12-12 20:38:05 +0000272(if py-mode-map
273 ()
274 (setq py-mode-map (make-sparse-keymap))
275
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 ;; shadow global bindings for newline-and-indent w/ the py- version.
277 ;; BAW - this is extremely bad form, but I'm not going to change it
278 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000279 (mapcar (function (lambda (key)
280 (define-key
281 py-mode-map key 'py-newline-and-indent)))
282 (where-is-internal 'newline-and-indent))
283
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000284 ;; BAW - you could do it this way, but its not considered proper
285 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000286 (mapcar (function
287 (lambda (x)
288 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000289 '((":" . py-electric-colon)
290 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 ("\C-c|" . py-execute-region)
292 ("\C-c!" . py-shell)
293 ("\177" . py-delete-char)
294 ("\n" . py-newline-and-indent)
295 ("\C-c:" . py-guess-indent-offset)
296 ("\C-c\t" . py-indent-region)
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000297 ("\C-c\C-l" . py-outdent-left)
298 ("\C-c\C-r" . py-indent-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000299 ("\C-c<" . py-shift-region-left)
300 ("\C-c>" . py-shift-region-right)
301 ("\C-c\C-n" . py-next-statement)
302 ("\C-c\C-p" . py-previous-statement)
303 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000304 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000305 ("\C-c#" . py-comment-region)
306 ("\C-c?" . py-describe-mode)
307 ("\C-c\C-hm" . py-describe-mode)
308 ("\e\C-a" . beginning-of-python-def-or-class)
309 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000310 ( "\e\C-h" . mark-python-def-or-class)))
311 ;; should do all keybindings this way
312 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
313 (define-key py-mode-map "\C-c\C-v" 'py-version)
314 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000316(defvar py-mode-syntax-table nil
317 "Syntax table used in `python-mode' buffers.")
318
Barry Warsaw7ae77681994-12-12 20:38:05 +0000319(if py-mode-syntax-table
320 ()
321 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000322 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000323 (mapcar (function
324 (lambda (x) (modify-syntax-entry
325 (car x) (cdr x) py-mode-syntax-table)))
326 '(( ?\( . "()" ) ( ?\) . ")(" )
327 ( ?\[ . "(]" ) ( ?\] . ")[" )
328 ( ?\{ . "(}" ) ( ?\} . "){" )
329 ;; fix operator symbols misassigned in the std table
330 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
331 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
332 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
333 ( ?\> . "." ) ( ?\| . "." )
334 ( ?\_ . "w" ) ; underscore is legit in names
335 ( ?\' . "\"") ; single quote is string quote
336 ( ?\" . "\"" ) ; double quote is string quote too
337 ( ?\` . "$") ; backquote is open and close paren
338 ( ?\# . "<") ; hash starts comment
339 ( ?\n . ">")))) ; newline ends comment
340
341(defconst py-stringlit-re
342 (concat
343 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
344 "\\|" ; or
345 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000346 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000347
348;; this is tricky because a trailing backslash does not mean
349;; continuation if it's in a comment
350(defconst py-continued-re
351 (concat
352 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
353 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000354 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355
356(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000357 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000358
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000359(defconst py-outdent-re
360 (concat "\\(" (mapconcat 'identity
361 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000362 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000363 "finally:"
364 "elif\\s +.*:")
365 "\\|")
366 "\\)")
367 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000368
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000369(defconst py-no-outdent-re
370 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000371 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000372 "except\\(\\s +.*\\)?:"
373 "while\\s +.*:"
374 "for\\s +.*:"
375 "if\\s +.*:"
376 "elif\\s +.*:")
377 "\\|")
378 "\\)")
379 "Regexp matching lines to not outdent after.")
380
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000381
382;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000383(defun python-mode ()
384 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000385To submit a problem report, enter `\\[py-submit-bug-report]' from a
386`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
387documentation. To see what version of `python-mode' you are running,
388enter `\\[py-version]'.
389
390This mode knows about Python indentation, tokens, comments and
391continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000392
393COMMANDS
394\\{py-mode-map}
395VARIABLES
396
397py-indent-offset\tindentation increment
398py-block-comment-prefix\tcomment string used by py-comment-region
399py-python-command\tshell command to invoke Python interpreter
400py-scroll-process-buffer\talways scroll Python process buffer
401py-temp-directory\tdirectory used for temp files (if needed)
402py-beep-if-tab-change\tring the bell if tab-width is changed"
403 (interactive)
404 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000405 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000406 (setq major-mode 'python-mode
407 mode-name "Python"
408 local-abbrev-table python-mode-abbrev-table)
409 (use-local-map py-mode-map)
410 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000411 (mapcar (function (lambda (x)
412 (make-local-variable (car x))
413 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 '((paragraph-separate . "^[ \t]*$")
415 (paragraph-start . "^[ \t]*$")
416 (require-final-newline . t)
417 (comment-start . "# ")
418 (comment-start-skip . "# *")
419 (comment-column . 40)
420 (indent-region-function . py-indent-region)
421 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000422 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000423 ;;
424 ;; not sure where the magic comment has to be; to save time
425 ;; searching for a rarity, we give up if it's not found prior to the
426 ;; first executable statement.
427 ;;
428 ;; BAW - on first glance, this seems like complete hackery. Why was
429 ;; this necessary, and is it still necessary?
430 (let ((case-fold-search nil)
431 (start (point))
432 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000433 (if (re-search-forward
434 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
435 (prog2 (py-next-statement 1) (point) (goto-char 1))
436 t)
437 (progn
438 (setq new-tab-width
439 (string-to-int
440 (buffer-substring (match-beginning 1) (match-end 1))))
441 (if (= tab-width new-tab-width)
442 nil
443 (setq tab-width new-tab-width)
444 (message "Caution: tab-width changed to %d" new-tab-width)
445 (if py-beep-if-tab-change (beep)))))
446 (goto-char start))
447
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000448 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000449 (if python-mode-hook
450 (run-hooks 'python-mode-hook)
451 (run-hooks 'py-mode-hook)))
452
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453
Barry Warsawb91b7431995-03-14 15:55:20 +0000454;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000455(defun py-outdent-p ()
456 ;; returns non-nil if the current line should outdent one level
457 (save-excursion
458 (and (progn (back-to-indentation)
459 (looking-at py-outdent-re))
460 (progn (backward-to-indentation 1)
461 (while (or (looking-at py-blank-or-comment-re)
462 (bobp))
463 (backward-to-indentation 1))
464 (not (looking-at py-no-outdent-re)))
465 )))
466
467
Barry Warsawb91b7431995-03-14 15:55:20 +0000468(defun py-electric-colon (arg)
469 "Insert a colon.
470In certain cases the line is outdented appropriately. If a numeric
471argument is provided, that many colons are inserted non-electrically."
472 (interactive "P")
473 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000474 (save-excursion
475 (let ((here (point))
476 (outdent 0)
477 (indent (py-compute-indentation)))
478 (if (and (not arg)
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000479 (py-outdent-p)
Barry Warsaw3aca2a11995-03-20 18:32:14 +0000480 (= indent (save-excursion
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000481 (forward-line -1)
482 (py-compute-indentation)))
483 )
484 (setq outdent py-indent-offset))
Barry Warsawd865bc51995-03-15 18:23:16 +0000485 ;; Don't indent, only outdent. This assumes that any lines that
486 ;; are already outdented relative to py-compute-indentation were
487 ;; put there on purpose. Its highly annoying to have `:' indent
488 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
489 ;; there a better way to determine this???
Barry Warsawa6a714e1995-03-15 18:19:15 +0000490 (if (< (current-indentation) indent) nil
Barry Warsaw9b623b31995-03-14 23:59:07 +0000491 (goto-char here)
492 (beginning-of-line)
493 (delete-horizontal-space)
494 (indent-to (- indent outdent))
495 ))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000496
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000497(defun py-indent-right (arg)
498 "Indent the line by one `py-indent-offset' level.
499With numeric arg, indent by that many levels. You cannot indent
500farther right than the distance the line would be indented by
501\\[py-indent-line]."
502 (interactive "p")
503 (let ((col (current-indentation))
504 (want (* arg py-indent-offset))
505 (indent (py-compute-indentation))
506 (pos (- (point-max) (point)))
507 (bol (save-excursion (beginning-of-line) (point))))
508 (if (<= (+ col want) indent)
509 (progn
510 (beginning-of-line)
511 (delete-horizontal-space)
512 (indent-to (+ col want))
513 (if (> (- (point-max) pos) (point))
514 (goto-char (- (point-max) pos)))
515 ))))
516
517(defun py-outdent-left (arg)
518 "Outdent the line by one `py-indent-offset' level.
519With numeric arg, outdent by that many levels. You cannot outdent
520farther left than column zero."
521 (interactive "p")
522 (let ((col (current-indentation))
523 (want (* arg py-indent-offset))
524 (pos (- (point-max) (point)))
525 (bol (save-excursion (beginning-of-line) (point))))
526 (if (<= 0 (- col want))
527 (progn
528 (beginning-of-line)
529 (delete-horizontal-space)
530 (indent-to (- col want))
531 (if (> (- (point-max) pos) (point))
532 (goto-char (- (point-max) pos)))
533 ))))
534
Barry Warsawb91b7431995-03-14 15:55:20 +0000535
Barry Warsaw7ae77681994-12-12 20:38:05 +0000536;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000537(defun py-shell ()
538 "Start an interactive Python interpreter in another window.
539This is like Shell mode, except that Python is running in the window
540instead of a shell. See the `Interactive Shell' and `Shell Mode'
541sections of the Emacs manual for details, especially for the key
542bindings active in the `*Python*' buffer.
543
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000544See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000545behavior in the process window.
546
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000547Warning: Don't use an interactive Python if you change sys.ps1 or
548sys.ps2 from their default values, or if you're running code that
549prints `>>> ' or `... ' at the start of a line. `python-mode' can't
550distinguish your output from Python's output, and assumes that `>>> '
551at the start of a line is a prompt from Python. Similarly, the Emacs
552Shell mode code assumes that both `>>> ' and `... ' at the start of a
553line are Python prompts. Bad things can happen if you fool either
554mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000555
556Warning: If you do any editing *in* the process buffer *while* the
557buffer is accepting output from Python, do NOT attempt to `undo' the
558changes. Some of the output (nowhere near the parts you changed!) may
559be lost if you do. This appears to be an Emacs bug, an unfortunate
560interaction between undo and process filters; the same problem exists in
561non-Python process buffers using the default (Emacs-supplied) process
562filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000563 ;; BAW - should undo be disabled in the python process buffer, if
564 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000565 (interactive)
566 (if py-this-is-emacs-19-p
567 (progn
568 (require 'comint)
569 (switch-to-buffer-other-window
570 (make-comint "Python" py-python-command)))
571 (progn
572 (require 'shell)
573 (switch-to-buffer-other-window
Barry Warsaw6e98f331995-07-05 22:06:50 +0000574 (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
575 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576 (make-local-variable 'shell-prompt-pattern)
577 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
578 (set-process-filter (get-buffer-process (current-buffer))
579 'py-process-filter)
580 (set-syntax-table py-mode-syntax-table))
581
582(defun py-execute-region (start end)
583 "Send the region between START and END to a Python interpreter.
584If there is a *Python* process it is used.
585
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000586Hint: If you want to execute part of a Python file several times
587\(e.g., perhaps you're developing a function and want to flesh it out
588a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
589the region of interest, and send the code to a *Python* process via
590`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000591
592Following are subtleties to note when using a *Python* process:
593
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000594If a *Python* process is used, the region is copied into a temporary
595file (in directory `py-temp-directory'), and an `execfile' command is
596sent to Python naming that file. If you send regions faster than
597Python can execute them, `python-mode' will save them into distinct
598temp files, and execute the next one in the queue the next time it
599sees a `>>> ' prompt from Python. Each time this happens, the process
600buffer is popped into a window (if it's not already in some window) so
601you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000602
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000603 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000604
605is inserted at the end.
606
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000607Caution: No more than 26 regions can be pending at any given time.
608This limit is (indirectly) inherited from libc's mktemp(3).
609`python-mode' does not try to protect you from exceeding the limit.
610It's extremely unlikely that you'll get anywhere close to the limit in
611practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000612
613See the `\\[py-shell]' docs for additional warnings."
614 (interactive "r")
615 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000616 (let ((pyproc (get-process "Python"))
617 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000618 (if (null pyproc)
619 (shell-command-on-region start end py-python-command)
620 ;; else feed it thru a temp file
621 (setq fname (py-make-temp-name))
622 (write-region start end fname nil 'no-msg)
623 (setq py-file-queue (append py-file-queue (list fname)))
624 (if (cdr py-file-queue)
625 (message "File %s queued for execution" fname)
626 ;; else
627 (py-execute-file pyproc fname)))))
628
629(defun py-execute-file (pyproc fname)
630 (py-append-to-process-buffer
631 pyproc
632 (format "## working on region in file %s ...\n" fname))
633 (process-send-string pyproc (format "execfile('%s')\n" fname)))
634
635(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000636 (let ((curbuf (current-buffer))
637 (pbuf (process-buffer pyproc))
638 (pmark (process-mark pyproc))
639 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000640
641 ;; make sure we switch to a different buffer at least once. if we
642 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000643 ;; window, and point is before the end, and lots of output is
644 ;; coming at a fast pace, then (a) simple cursor-movement commands
645 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
646 ;; to have a visible effect (the window just doesn't get updated,
647 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
648 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000649 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000650 ;; #b makes no sense to me at all. #a almost makes sense: unless
651 ;; we actually change buffers, set_buffer_internal in buffer.c
652 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
653 ;; seems to make the Emacs command loop reluctant to update the
654 ;; display. Perhaps the default process filter in process.c's
655 ;; read_process_output has update_mode_lines++ for a similar
656 ;; reason? beats me ...
657
658 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000659 (if (eq curbuf pbuf) ; mysterious ugly hack
660 (set-buffer (get-buffer-create "*scratch*")))
661
662 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000663 (let* ((start (point))
664 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000665 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000666 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000667 (goto-char pmark)
668 (insert string)
669 (move-marker pmark (point))
670 (setq file-finished
671 (and py-file-queue
672 (equal ">>> "
673 (buffer-substring
674 (prog2 (beginning-of-line) (point)
675 (goto-char pmark))
676 (point)))))
677 (if goback (goto-char start)
678 ;; else
679 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000680 (let* ((pop-up-windows t)
681 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000682 (set-window-point pwin (point)))))
683 (set-buffer curbuf)
684 (if file-finished
685 (progn
686 (py-delete-file-silently (car py-file-queue))
687 (setq py-file-queue (cdr py-file-queue))
688 (if py-file-queue
689 (py-execute-file pyproc (car py-file-queue)))))
690 (and goend
691 (progn (set-buffer pbuf)
692 (goto-char (point-max))))
693 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000694
695(defun py-execute-buffer ()
696 "Send the contents of the buffer to a Python interpreter.
697If there is a *Python* process buffer it is used. If a clipping
698restriction is in effect, only the accessible portion of the buffer is
699sent. A trailing newline will be supplied if needed.
700
701See the `\\[py-execute-region]' docs for an account of some subtleties."
702 (interactive)
703 (py-execute-region (point-min) (point-max)))
704
705
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000706
707;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000708(defun py-delete-char ()
709 "Reduce indentation or delete character.
710If point is at the leftmost column, deletes the preceding newline.
711
712Else if point is at the leftmost non-blank character of a line that is
713neither a continuation line nor a non-indenting comment line, or if
714point is at the end of a blank line, reduces the indentation to match
715that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000716opened the block is displayed in the echo area to help you keep track
717of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000718
719Else the preceding character is deleted, converting a tab to spaces if
720needed so that only a single column position is deleted."
721 (interactive "*")
722 (if (or (/= (current-indentation) (current-column))
723 (bolp)
724 (py-continuation-line-p)
725 (looking-at "#[^ \t\n]")) ; non-indenting #
726 (backward-delete-char-untabify 1)
727 ;; else indent the same as the colon line that opened the block
728
729 ;; force non-blank so py-goto-block-up doesn't ignore it
730 (insert-char ?* 1)
731 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000732 (let ((base-indent 0) ; indentation of base line
733 (base-text "") ; and text of base line
734 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000735 (condition-case nil ; in case no enclosing block
736 (save-excursion
737 (py-goto-block-up 'no-mark)
738 (setq base-indent (current-indentation)
739 base-text (py-suck-up-leading-text)
740 base-found-p t))
741 (error nil))
742 (delete-char 1) ; toss the dummy character
743 (delete-horizontal-space)
744 (indent-to base-indent)
745 (if base-found-p
746 (message "Closes block: %s" base-text)))))
747
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000748;; required for pending-del and delsel modes
749(put 'py-delete-char 'delete-selection 'supersede)
750(put 'py-delete-char 'pending-delete 'supersede)
751
Barry Warsaw7ae77681994-12-12 20:38:05 +0000752(defun py-indent-line ()
753 "Fix the indentation of the current line according to Python rules."
754 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000755 (let* ((ci (current-indentation))
756 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000757 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000758 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000759 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000760 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000761 (if (/= ci need)
762 (save-excursion
763 (beginning-of-line)
764 (delete-horizontal-space)
765 (indent-to need)))
766 (if move-to-indentation-p (back-to-indentation))))
767
768(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000769 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000770This is just `strives to' because correct indentation can't be computed
771from scratch for Python code. In general, deletes the whitespace before
772point, inserts a newline, and takes an educated guess as to how you want
773the new line indented."
774 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000775 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000776 (if (< ci (current-column)) ; if point beyond indentation
777 (newline-and-indent)
778 ;; else try to act like newline-and-indent "normally" acts
779 (beginning-of-line)
780 (insert-char ?\n 1)
781 (move-to-column ci))))
782
783(defun py-compute-indentation ()
784 (save-excursion
785 (beginning-of-line)
786 (cond
Barry Warsawc01c5c81995-09-14 18:49:11 +0000787 ;; are we inside a string or comment?
788 ((save-excursion
789 (let ((pps (parse-partial-sexp (save-excursion
790 (beginning-of-python-def-or-class)
791 (point))
792 (point))))
793 (or (nth 3 pps) (nth 4 pps))))
794 (save-excursion
795 ;; skip back over blank & non-indenting comment lines note:
796 ;; will skip a blank or non-indenting comment line that
797 ;; happens to be a continuation line too
798 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
799 (back-to-indentation)
800 (current-column)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000801 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000802 ((py-continuation-line-p)
803 (let ((startpos (point))
804 (open-bracket-pos (py-nesting-level))
805 endpos searching found)
806 (if open-bracket-pos
807 (progn
808 ;; align with first item in list; else a normal
809 ;; indent beyond the line with the open bracket
810 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
811 ;; is the first list item on the same line?
812 (skip-chars-forward " \t")
813 (if (null (memq (following-char) '(?\n ?# ?\\)))
814 ; yes, so line up with it
815 (current-column)
816 ;; first list item on another line, or doesn't exist yet
817 (forward-line 1)
818 (while (and (< (point) startpos)
819 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
820 (forward-line 1))
821 (if (< (point) startpos)
822 ;; again mimic the first list item
823 (current-indentation)
824 ;; else they're about to enter the first item
825 (goto-char open-bracket-pos)
826 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000827
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000828 ;; else on backslash continuation line
829 (forward-line -1)
830 (if (py-continuation-line-p) ; on at least 3rd line in block
831 (current-indentation) ; so just continue the pattern
832 ;; else started on 2nd line in block, so indent more.
833 ;; if base line is an assignment with a start on a RHS,
834 ;; indent to 2 beyond the leftmost "="; else skip first
835 ;; chunk of non-whitespace characters on base line, + 1 more
836 ;; column
837 (end-of-line)
838 (setq endpos (point) searching t)
839 (back-to-indentation)
840 (setq startpos (point))
841 ;; look at all "=" from left to right, stopping at first
842 ;; one not nested in a list or string
843 (while searching
844 (skip-chars-forward "^=" endpos)
845 (if (= (point) endpos)
846 (setq searching nil)
847 (forward-char 1)
848 (setq state (parse-partial-sexp startpos (point)))
849 (if (and (zerop (car state)) ; not in a bracket
850 (null (nth 3 state))) ; & not in a string
851 (progn
852 (setq searching nil) ; done searching in any case
853 (setq found
854 (not (or
855 (eq (following-char) ?=)
856 (memq (char-after (- (point) 2))
857 '(?< ?> ?!)))))))))
858 (if (or (not found) ; not an assignment
859 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
860 (progn
861 (goto-char startpos)
862 (skip-chars-forward "^ \t\n")))
863 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000864
865 ;; not on a continuation line
866
867 ;; if at start of restriction, or on a non-indenting comment line,
868 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000869 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
870 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000871
872 ;; else indentation based on that of the statement that precedes
873 ;; us; use the first line of that statement to establish the base,
874 ;; in case the user forced a non-std indentation for the
875 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000876 (t
877 ;; skip back over blank & non-indenting comment lines
878 ;; note: will skip a blank or non-indenting comment line that
879 ;; happens to be a continuation line too
880 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
881 nil 'move)
882 ;; if we landed inside a string, go to the beginning of that
883 ;; string. this handles triple quoted, multi-line spanning
884 ;; strings.
885 (let ((state (parse-partial-sexp
886 (save-excursion (beginning-of-python-def-or-class)
887 (point))
888 (point))))
889 (if (nth 3 state)
890 (goto-char (nth 2 state))))
891 (py-goto-initial-line)
892 (if (py-statement-opens-block-p)
893 (+ (current-indentation) py-indent-offset)
894 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000895
896(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000899`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000900Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000901`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000902their own buffer-local copy), both those currently existing and those
903created later in the Emacs session.
904
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000905Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906There's no excuse for such foolishness, but sometimes you have to deal
907with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908`py-indent-offset' to what it thinks it was when they created the
909mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000910
911Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000912looking for a line that opens a block of code. `py-indent-offset' is
913set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000914statement following it. If the search doesn't succeed going forward,
915it's tried again going backward."
916 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917 (let (new-value
918 (start (point))
919 restart
920 (found nil)
921 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000922 (py-goto-initial-line)
923 (while (not (or found (eobp)))
924 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
925 (progn
926 (setq restart (point))
927 (py-goto-initial-line)
928 (if (py-statement-opens-block-p)
929 (setq found t)
930 (goto-char restart)))))
931 (if found
932 ()
933 (goto-char start)
934 (py-goto-initial-line)
935 (while (not (or found (bobp)))
936 (setq found
937 (and
938 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
939 (or (py-goto-initial-line) t) ; always true -- side effect
940 (py-statement-opens-block-p)))))
941 (setq colon-indent (current-indentation)
942 found (and found (zerop (py-next-statement 1)))
943 new-value (- (current-indentation) colon-indent))
944 (goto-char start)
945 (if found
946 (progn
947 (funcall (if global 'kill-local-variable 'make-local-variable)
948 'py-indent-offset)
949 (setq py-indent-offset new-value)
950 (message "%s value of py-indent-offset set to %d"
951 (if global "Global" "Local")
952 py-indent-offset))
953 (error "Sorry, couldn't guess a value for py-indent-offset"))))
954
955(defun py-shift-region (start end count)
956 (save-excursion
957 (goto-char end) (beginning-of-line) (setq end (point))
958 (goto-char start) (beginning-of-line) (setq start (point))
959 (indent-rigidly start end count)))
960
961(defun py-shift-region-left (start end &optional count)
962 "Shift region of Python code to the left.
963The lines from the line containing the start of the current region up
964to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000965shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966
967If a prefix argument is given, the region is instead shifted by that
968many columns."
969 (interactive "*r\nP") ; region; raw prefix arg
970 (py-shift-region start end
971 (- (prefix-numeric-value
972 (or count py-indent-offset)))))
973
974(defun py-shift-region-right (start end &optional count)
975 "Shift region of Python code to the right.
976The lines from the line containing the start of the current region up
977to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000978shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000979
980If a prefix argument is given, the region is instead shifted by that
981many columns."
982 (interactive "*r\nP") ; region; raw prefix arg
983 (py-shift-region start end (prefix-numeric-value
984 (or count py-indent-offset))))
985
986(defun py-indent-region (start end &optional indent-offset)
987 "Reindent a region of Python code.
988The lines from the line containing the start of the current region up
989to (but not including) the line containing the end of the region are
990reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000991character in the first column, the first line is left alone and the
992rest of the region is reindented with respect to it. Else the entire
993region is reindented with respect to the (closest code or
994indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
996This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000997control structures are introduced or removed, or to reformat code
998using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999
1000If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001001the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002used.
1003
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005is called! This function does not compute proper indentation from
1006scratch (that's impossible in Python), it merely adjusts the existing
1007indentation to be correct in context.
1008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001009Warning: This function really has no idea what to do with
1010non-indenting comment lines, and shifts them as if they were indenting
1011comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001013Special cases: whitespace is deleted from blank lines; continuation
1014lines are shifted by the same amount their initial line was shifted,
1015in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018 (save-excursion
1019 (goto-char end) (beginning-of-line) (setq end (point-marker))
1020 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001021 (let ((py-indent-offset (prefix-numeric-value
1022 (or indent-offset py-indent-offset)))
1023 (indents '(-1)) ; stack of active indent levels
1024 (target-column 0) ; column to which to indent
1025 (base-shifted-by 0) ; amount last base line was shifted
1026 (indent-base (if (looking-at "[ \t\n]")
1027 (py-compute-indentation)
1028 0))
1029 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030 (while (< (point) end)
1031 (setq ci (current-indentation))
1032 ;; figure out appropriate target column
1033 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001034 ((or (eq (following-char) ?#) ; comment in column 1
1035 (looking-at "[ \t]*$")) ; entirely blank
1036 (setq target-column 0))
1037 ((py-continuation-line-p) ; shift relative to base line
1038 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001039 (t ; new base line
1040 (if (> ci (car indents)) ; going deeper; push it
1041 (setq indents (cons ci indents))
1042 ;; else we should have seen this indent before
1043 (setq indents (memq ci indents)) ; pop deeper indents
1044 (if (null indents)
1045 (error "Bad indentation in region, at line %d"
1046 (save-restriction
1047 (widen)
1048 (1+ (count-lines 1 (point)))))))
1049 (setq target-column (+ indent-base
1050 (* py-indent-offset
1051 (- (length indents) 2))))
1052 (setq base-shifted-by (- target-column ci))))
1053 ;; shift as needed
1054 (if (/= ci target-column)
1055 (progn
1056 (delete-horizontal-space)
1057 (indent-to target-column)))
1058 (forward-line 1))))
1059 (set-marker end nil))
1060
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001061
1062;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001063(defun py-previous-statement (count)
1064 "Go to the start of previous Python statement.
1065If the statement at point is the i'th Python statement, goes to the
1066start of statement i-COUNT. If there is no such statement, goes to the
1067first statement. Returns count of statements left to move.
1068`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (if (< count 0) (py-next-statement (- count))
1071 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001073 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001074 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075 (> count 0)
1076 (zerop (forward-line -1))
1077 (py-goto-statement-at-or-above))
1078 (setq count (1- count)))
1079 (if (> count 0) (goto-char start)))
1080 count))
1081
1082(defun py-next-statement (count)
1083 "Go to the start of next Python statement.
1084If the statement at point is the i'th Python statement, goes to the
1085start of statement i+COUNT. If there is no such statement, goes to the
1086last statement. Returns count of statements left to move. `Statements'
1087do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001088 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001089 (if (< count 0) (py-previous-statement (- count))
1090 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001091 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001093 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094 (> count 0)
1095 (py-goto-statement-below))
1096 (setq count (1- count)))
1097 (if (> count 0) (goto-char start)))
1098 count))
1099
1100(defun py-goto-block-up (&optional nomark)
1101 "Move up to start of current block.
1102Go to the statement that starts the smallest enclosing block; roughly
1103speaking, this will be the closest preceding statement that ends with a
1104colon and is indented less than the statement you started on. If
1105successful, also sets the mark to the starting point.
1106
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001107`\\[py-mark-block]' can be used afterward to mark the whole code
1108block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001109
1110If called from a program, the mark will not be set if optional argument
1111NOMARK is not nil."
1112 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001113 (let ((start (point))
1114 (found nil)
1115 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116 (py-goto-initial-line)
1117 ;; if on blank or non-indenting comment line, use the preceding stmt
1118 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1119 (progn
1120 (py-goto-statement-at-or-above)
1121 (setq found (py-statement-opens-block-p))))
1122 ;; search back for colon line indented less
1123 (setq initial-indent (current-indentation))
1124 (if (zerop initial-indent)
1125 ;; force fast exit
1126 (goto-char (point-min)))
1127 (while (not (or found (bobp)))
1128 (setq found
1129 (and
1130 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1131 (or (py-goto-initial-line) t) ; always true -- side effect
1132 (< (current-indentation) initial-indent)
1133 (py-statement-opens-block-p))))
1134 (if found
1135 (progn
1136 (or nomark (push-mark start))
1137 (back-to-indentation))
1138 (goto-char start)
1139 (error "Enclosing block not found"))))
1140
1141(defun beginning-of-python-def-or-class (&optional class)
1142 "Move point to start of def (or class, with prefix arg).
1143
1144Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001145arg, looks for a `class' instead. The docs assume the `def' case;
1146just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001147
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148If point is in a def statement already, and after the `d', simply
1149moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001151Else (point is not in a def statement, or at or before the `d' of a
1152def statement), searches for the closest preceding def statement, and
1153leaves point at its start. If no such statement can be found, leaves
1154point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001155
1156Returns t iff a def statement is found by these rules.
1157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001158Note that doing this command repeatedly will take you closer to the
1159start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001160
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161If you want to mark the current def/class, see
1162`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001163 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001164 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1165 (start-of-line (progn (beginning-of-line) (point)))
1166 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001167 (if (or (/= start-of-stmt start-of-line)
1168 (not at-or-before-p))
1169 (end-of-line)) ; OK to match on this line
1170 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001171 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001172
1173(defun end-of-python-def-or-class (&optional class)
1174 "Move point beyond end of def (or class, with prefix arg) body.
1175
1176By default, looks for an appropriate `def'. If you supply a prefix arg,
1177looks for a `class' instead. The docs assume the `def' case; just
1178substitute `class' for `def' for the other case.
1179
1180If point is in a def statement already, this is the def we use.
1181
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182Else if the def found by `\\[beginning-of-python-def-or-class]'
1183contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001184
1185Else we search forward for the closest following def, and use that.
1186
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001187If a def can be found by these rules, point is moved to the start of
1188the line immediately following the def block, and the position of the
1189start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
1191Else point is moved to the end of the buffer, and nil is returned.
1192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193Note that doing this command repeatedly will take you closer to the
1194end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001196If you want to mark the current def/class, see
1197`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001198 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199 (let ((start (progn (py-goto-initial-line) (point)))
1200 (which (if class "class" "def"))
1201 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001202 ;; move point to start of appropriate def/class
1203 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1204 (setq state 'at-beginning)
1205 ;; else see if beginning-of-python-def-or-class hits container
1206 (if (and (beginning-of-python-def-or-class class)
1207 (progn (py-goto-beyond-block)
1208 (> (point) start)))
1209 (setq state 'at-end)
1210 ;; else search forward
1211 (goto-char start)
1212 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1213 (progn (setq state 'at-beginning)
1214 (beginning-of-line)))))
1215 (cond
1216 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1217 ((eq state 'at-end) t)
1218 ((eq state 'not-found) nil)
1219 (t (error "internal error in end-of-python-def-or-class")))))
1220
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001221
1222;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001223(defun py-mark-block (&optional extend just-move)
1224 "Mark following block of lines. With prefix arg, mark structure.
1225Easier to use than explain. It sets the region to an `interesting'
1226block of succeeding lines. If point is on a blank line, it goes down to
1227the next non-blank line. That will be the start of the region. The end
1228of the region depends on the kind of line at the start:
1229
1230 - If a comment, the region will include all succeeding comment lines up
1231 to (but not including) the next non-comment line (if any).
1232
1233 - Else if a prefix arg is given, and the line begins one of these
1234 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001235
1236 if elif else try except finally for while def class
1237
Barry Warsaw7ae77681994-12-12 20:38:05 +00001238 the region will be set to the body of the structure, including
1239 following blocks that `belong' to it, but excluding trailing blank
1240 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001241 and all (if any) of the following `except' and `finally' blocks
1242 that belong to the `try' structure will be in the region. Ditto
1243 for if/elif/else, for/else and while/else structures, and (a bit
1244 degenerate, since they're always one-block structures) def and
1245 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001246
1247 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001248 block (see list above), and the block is not a `one-liner' (i.e.,
1249 the statement ends with a colon, not with code), the region will
1250 include all succeeding lines up to (but not including) the next
1251 code statement (if any) that's indented no more than the starting
1252 line, except that trailing blank and comment lines are excluded.
1253 E.g., if the starting line begins a multi-statement `def'
1254 structure, the region will be set to the full function definition,
1255 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001256
1257 - Else the region will include all succeeding lines up to (but not
1258 including) the next blank line, or code or indenting-comment line
1259 indented strictly less than the starting line. Trailing indenting
1260 comment lines are included in this case, but not trailing blank
1261 lines.
1262
1263A msg identifying the location of the mark is displayed in the echo
1264area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1265
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001266If called from a program, optional argument EXTEND plays the role of
1267the prefix arg, and if optional argument JUST-MOVE is not nil, just
1268moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001269 (interactive "P") ; raw prefix arg
1270 (py-goto-initial-line)
1271 ;; skip over blank lines
1272 (while (and
1273 (looking-at "[ \t]*$") ; while blank line
1274 (not (eobp))) ; & somewhere to go
1275 (forward-line 1))
1276 (if (eobp)
1277 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001278 (let ((initial-pos (point))
1279 (initial-indent (current-indentation))
1280 last-pos ; position of last stmt in region
1281 (followers
1282 '((if elif else) (elif elif else) (else)
1283 (try except finally) (except except) (finally)
1284 (for else) (while else)
1285 (def) (class) ) )
1286 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001287
1288 (cond
1289 ;; if comment line, suck up the following comment lines
1290 ((looking-at "[ \t]*#")
1291 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1292 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1293 (setq last-pos (point)))
1294
1295 ;; else if line is a block line and EXTEND given, suck up
1296 ;; the whole structure
1297 ((and extend
1298 (setq first-symbol (py-suck-up-first-keyword) )
1299 (assq first-symbol followers))
1300 (while (and
1301 (or (py-goto-beyond-block) t) ; side effect
1302 (forward-line -1) ; side effect
1303 (setq last-pos (point)) ; side effect
1304 (py-goto-statement-below)
1305 (= (current-indentation) initial-indent)
1306 (setq next-symbol (py-suck-up-first-keyword))
1307 (memq next-symbol (cdr (assq first-symbol followers))))
1308 (setq first-symbol next-symbol)))
1309
1310 ;; else if line *opens* a block, search for next stmt indented <=
1311 ((py-statement-opens-block-p)
1312 (while (and
1313 (setq last-pos (point)) ; always true -- side effect
1314 (py-goto-statement-below)
1315 (> (current-indentation) initial-indent))
1316 nil))
1317
1318 ;; else plain code line; stop at next blank line, or stmt or
1319 ;; indenting comment line indented <
1320 (t
1321 (while (and
1322 (setq last-pos (point)) ; always true -- side effect
1323 (or (py-goto-beyond-final-line) t)
1324 (not (looking-at "[ \t]*$")) ; stop at blank line
1325 (or
1326 (>= (current-indentation) initial-indent)
1327 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1328 nil)))
1329
1330 ;; skip to end of last stmt
1331 (goto-char last-pos)
1332 (py-goto-beyond-final-line)
1333
1334 ;; set mark & display
1335 (if just-move
1336 () ; just return
1337 (push-mark (point) 'no-msg)
1338 (forward-line -1)
1339 (message "Mark set after: %s" (py-suck-up-leading-text))
1340 (goto-char initial-pos))))
1341
1342(defun mark-python-def-or-class (&optional class)
1343 "Set region to body of def (or class, with prefix arg) enclosing point.
1344Pushes the current mark, then point, on the mark ring (all language
1345modes do this, but although it's handy it's never documented ...).
1346
1347In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1349`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001350
1351And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001352Turned out that was more confusing than useful: the `goto start' and
1353`goto end' commands are usually used to search through a file, and
1354people expect them to act a lot like `search backward' and `search
1355forward' string-search commands. But because Python `def' and `class'
1356can nest to arbitrary levels, finding the smallest def containing
1357point cannot be done via a simple backward search: the def containing
1358point may not be the closest preceding def, or even the closest
1359preceding def that's indented less. The fancy algorithm required is
1360appropriate for the usual uses of this `mark' command, but not for the
1361`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001362
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363So the def marked by this command may not be the one either of the
1364`goto' commands find: If point is on a blank or non-indenting comment
1365line, moves back to start of the closest preceding code statement or
1366indenting comment line. If this is a `def' statement, that's the def
1367we use. Else searches for the smallest enclosing `def' block and uses
1368that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001370When an enclosing def is found: The mark is left immediately beyond
1371the last line of the def block. Point is left at the start of the
1372def, except that: if the def is preceded by a number of comment lines
1373followed by (at most) one optional blank line, point is left at the
1374start of the comments; else if the def is preceded by a blank line,
1375point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376
1377The intent is to mark the containing def/class and its associated
1378documentation, to make moving and duplicating functions and classes
1379pleasant."
1380 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381 (let ((start (point))
1382 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001383 (push-mark start)
1384 (if (not (py-go-up-tree-to-keyword which))
1385 (progn (goto-char start)
1386 (error "Enclosing %s not found" which))
1387 ;; else enclosing def/class found
1388 (setq start (point))
1389 (py-goto-beyond-block)
1390 (push-mark (point))
1391 (goto-char start)
1392 (if (zerop (forward-line -1)) ; if there is a preceding line
1393 (progn
1394 (if (looking-at "[ \t]*$") ; it's blank
1395 (setq start (point)) ; so reset start point
1396 (goto-char start)) ; else try again
1397 (if (zerop (forward-line -1))
1398 (if (looking-at "[ \t]*#") ; a comment
1399 ;; look back for non-comment line
1400 ;; tricky: note that the regexp matches a blank
1401 ;; line, cuz \n is in the 2nd character class
1402 (and
1403 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1404 (forward-line 1))
1405 ;; no comment, so go back
1406 (goto-char start))))))))
1407
1408(defun py-comment-region (start end &optional uncomment-p)
1409 "Comment out region of code; with prefix arg, uncomment region.
1410The lines from the line containing the start of the current region up
1411to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001412commented out, by inserting the string `py-block-comment-prefix' at
1413the start of each line. With a prefix arg, removes
1414`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001415 (interactive "*r\nP") ; region; raw prefix arg
1416 (goto-char end) (beginning-of-line) (setq end (point))
1417 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001418 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001419 (save-excursion
1420 (save-restriction
1421 (narrow-to-region start end)
1422 (while (not (eobp))
1423 (if uncomment-p
1424 (and (string= py-block-comment-prefix
1425 (buffer-substring
1426 (point) (+ (point) prefix-len)))
1427 (delete-char prefix-len))
1428 (insert py-block-comment-prefix))
1429 (forward-line 1))))))
1430
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001431
1432;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001433
1434;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001435;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1436;; out of the right places, along with the keys they're on & current
1437;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001438(defun py-dump-help-string (str)
1439 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001440 (let ((locals (buffer-local-variables))
1441 funckind funcname func funcdoc
1442 (start 0) mstart end
1443 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001444 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1445 (setq mstart (match-beginning 0) end (match-end 0)
1446 funckind (substring str (match-beginning 1) (match-end 1))
1447 funcname (substring str (match-beginning 2) (match-end 2))
1448 func (intern funcname))
1449 (princ (substitute-command-keys (substring str start mstart)))
1450 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001451 ((equal funckind "c") ; command
1452 (setq funcdoc (documentation func)
1453 keys (concat
1454 "Key(s): "
1455 (mapconcat 'key-description
1456 (where-is-internal func py-mode-map)
1457 ", "))))
1458 ((equal funckind "v") ; variable
1459 (setq funcdoc (substitute-command-keys
1460 (get func 'variable-documentation))
1461 keys (if (assq func locals)
1462 (concat
1463 "Local/Global values: "
1464 (prin1-to-string (symbol-value func))
1465 " / "
1466 (prin1-to-string (default-value func)))
1467 (concat
1468 "Value: "
1469 (prin1-to-string (symbol-value func))))))
1470 (t ; unexpected
1471 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001472 (princ (format "\n-> %s:\t%s\t%s\n\n"
1473 (if (equal funckind "c") "Command" "Variable")
1474 funcname keys))
1475 (princ funcdoc)
1476 (terpri)
1477 (setq start end))
1478 (princ (substitute-command-keys (substring str start))))
1479 (print-help-return-message)))
1480
1481(defun py-describe-mode ()
1482 "Dump long form of Python-mode docs."
1483 (interactive)
1484 (py-dump-help-string "Major mode for editing Python files.
1485Knows about Python indentation, tokens, comments and continuation lines.
1486Paragraphs are separated by blank lines only.
1487
1488Major sections below begin with the string `@'; specific function and
1489variable docs begin with `->'.
1490
1491@EXECUTING PYTHON CODE
1492
1493\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1494\\[py-execute-region]\tsends the current region
1495\\[py-shell]\tstarts a Python interpreter window; this will be used by
1496\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1497%c:py-execute-buffer
1498%c:py-execute-region
1499%c:py-shell
1500
1501@VARIABLES
1502
1503py-indent-offset\tindentation increment
1504py-block-comment-prefix\tcomment string used by py-comment-region
1505
1506py-python-command\tshell command to invoke Python interpreter
1507py-scroll-process-buffer\talways scroll Python process buffer
1508py-temp-directory\tdirectory used for temp files (if needed)
1509
1510py-beep-if-tab-change\tring the bell if tab-width is changed
1511%v:py-indent-offset
1512%v:py-block-comment-prefix
1513%v:py-python-command
1514%v:py-scroll-process-buffer
1515%v:py-temp-directory
1516%v:py-beep-if-tab-change
1517
1518@KINDS OF LINES
1519
1520Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521preceding line ends with a backslash that's not part of a comment, or
1522the paren/bracket/brace nesting level at the start of the line is
1523non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001524
1525An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001526possibly blanks or tabs), a `comment line' (leftmost non-blank
1527character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001528
1529Comment Lines
1530
1531Although all comment lines are treated alike by Python, Python mode
1532recognizes two kinds that act differently with respect to indentation.
1533
1534An `indenting comment line' is a comment line with a blank, tab or
1535nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001536treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001537indenting comment line will be indented like the comment line. All
1538other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539following the initial `#') are `non-indenting comment lines', and
1540their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001543whenever possible. Non-indenting comment lines are useful in cases
1544like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
1546\ta = b # a very wordy single-line comment that ends up being
1547\t #... continued onto another line
1548
1549\tif a == b:
1550##\t\tprint 'panic!' # old code we've `commented out'
1551\t\treturn a
1552
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553Since the `#...' and `##' comment lines have a non-whitespace
1554character following the initial `#', Python mode ignores them when
1555computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001556
1557Continuation Lines and Statements
1558
1559The Python-mode commands generally work on statements instead of on
1560individual lines, where a `statement' is a comment or blank line, or a
1561code line and all of its following continuation lines (if any)
1562considered as a single logical unit. The commands in this mode
1563generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001564statement containing point, even if point happens to be in the middle
1565of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566
1567
1568@INDENTATION
1569
1570Primarily for entering new code:
1571\t\\[indent-for-tab-command]\t indent line appropriately
1572\t\\[py-newline-and-indent]\t insert newline, then indent
1573\t\\[py-delete-char]\t reduce indentation, or delete single character
1574
1575Primarily for reindenting existing code:
1576\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1577\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1578
1579\t\\[py-indent-region]\t reindent region to match its context
1580\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1581\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1582
1583Unlike most programming languages, Python uses indentation, and only
1584indentation, to specify block structure. Hence the indentation supplied
1585automatically by Python-mode is just an educated guess: only you know
1586the block structure you intend, so only you can supply correct
1587indentation.
1588
1589The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1590the indentation of preceding statements. E.g., assuming
1591py-indent-offset is 4, after you enter
1592\tif a > 0: \\[py-newline-and-indent]
1593the cursor will be moved to the position of the `_' (_ is not a
1594character in the file, it's just used here to indicate the location of
1595the cursor):
1596\tif a > 0:
1597\t _
1598If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1599to
1600\tif a > 0:
1601\t c = d
1602\t _
1603Python-mode cannot know whether that's what you intended, or whether
1604\tif a > 0:
1605\t c = d
1606\t_
1607was your intent. In general, Python-mode either reproduces the
1608indentation of the (closest code or indenting-comment) preceding
1609statement, or adds an extra py-indent-offset blanks if the preceding
1610statement has `:' as its last significant (non-whitespace and non-
1611comment) character. If the suggested indentation is too much, use
1612\\[py-delete-char] to reduce it.
1613
1614Continuation lines are given extra indentation. If you don't like the
1615suggested indentation, change it to something you do like, and Python-
1616mode will strive to indent later lines of the statement in the same way.
1617
1618If a line is a continuation line by virtue of being in an unclosed
1619paren/bracket/brace structure (`list', for short), the suggested
1620indentation depends on whether the current line contains the first item
1621in the list. If it does, it's indented py-indent-offset columns beyond
1622the indentation of the line containing the open bracket. If you don't
1623like that, change it by hand. The remaining items in the list will mimic
1624whatever indentation you give to the first item.
1625
1626If a line is a continuation line because the line preceding it ends with
1627a backslash, the third and following lines of the statement inherit their
1628indentation from the line preceding them. The indentation of the second
1629line in the statement depends on the form of the first (base) line: if
1630the base line is an assignment statement with anything more interesting
1631than the backslash following the leftmost assigning `=', the second line
1632is indented two columns beyond that `='. Else it's indented to two
1633columns beyond the leftmost solid chunk of non-whitespace characters on
1634the base line.
1635
1636Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1637repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1638structure you intend.
1639%c:indent-for-tab-command
1640%c:py-newline-and-indent
1641%c:py-delete-char
1642
1643
1644The next function may be handy when editing code you didn't write:
1645%c:py-guess-indent-offset
1646
1647
1648The remaining `indent' functions apply to a region of Python code. They
1649assume the block structure (equals indentation, in Python) of the region
1650is correct, and alter the indentation in various ways while preserving
1651the block structure:
1652%c:py-indent-region
1653%c:py-shift-region-left
1654%c:py-shift-region-right
1655
1656@MARKING & MANIPULATING REGIONS OF CODE
1657
1658\\[py-mark-block]\t mark block of lines
1659\\[mark-python-def-or-class]\t mark smallest enclosing def
1660\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1661\\[py-comment-region]\t comment out region of code
1662\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1663%c:py-mark-block
1664%c:mark-python-def-or-class
1665%c:py-comment-region
1666
1667@MOVING POINT
1668
1669\\[py-previous-statement]\t move to statement preceding point
1670\\[py-next-statement]\t move to statement following point
1671\\[py-goto-block-up]\t move up to start of current block
1672\\[beginning-of-python-def-or-class]\t move to start of def
1673\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1674\\[end-of-python-def-or-class]\t move to end of def
1675\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1676
1677The first two move to one statement beyond the statement that contains
1678point. A numeric prefix argument tells them to move that many
1679statements instead. Blank lines, comment lines, and continuation lines
1680do not count as `statements' for these commands. So, e.g., you can go
1681to the first code statement in a file by entering
1682\t\\[beginning-of-buffer]\t to move to the top of the file
1683\t\\[py-next-statement]\t to skip over initial comments and blank lines
1684Or do `\\[py-previous-statement]' with a huge prefix argument.
1685%c:py-previous-statement
1686%c:py-next-statement
1687%c:py-goto-block-up
1688%c:beginning-of-python-def-or-class
1689%c:end-of-python-def-or-class
1690
1691@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1692
1693`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1694
1695`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1696overall class and def structure of a module.
1697
1698`\\[back-to-indentation]' moves point to a line's first non-blank character.
1699
1700`\\[indent-relative]' is handy for creating odd indentation.
1701
1702@OTHER EMACS HINTS
1703
1704If you don't like the default value of a variable, change its value to
1705whatever you do like by putting a `setq' line in your .emacs file.
1706E.g., to set the indentation increment to 4, put this line in your
1707.emacs:
1708\t(setq py-indent-offset 4)
1709To see the value of a variable, do `\\[describe-variable]' and enter the variable
1710name at the prompt.
1711
1712When entering a key sequence like `C-c C-n', it is not necessary to
1713release the CONTROL key after doing the `C-c' part -- it suffices to
1714press the CONTROL key, press and release `c' (while still holding down
1715CONTROL), press and release `n' (while still holding down CONTROL), &
1716then release CONTROL.
1717
1718Entering Python mode calls with no arguments the value of the variable
1719`python-mode-hook', if that value exists and is not nil; for backward
1720compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1721the Elisp manual for details.
1722
1723Obscure: When python-mode is first loaded, it looks for all bindings
1724to newline-and-indent in the global keymap, and shadows them with
1725local bindings to py-newline-and-indent."))
1726
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001727
1728;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729(defvar py-parse-state-re
1730 (concat
1731 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1732 "\\|"
1733 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001734
Barry Warsaw7ae77681994-12-12 20:38:05 +00001735;; returns the parse state at point (see parse-partial-sexp docs)
1736(defun py-parse-state ()
1737 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739 ;; back up to the first preceding line (if any; else start of
1740 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741 ;; whitespace and non-comment character. These are good places
1742 ;; to start parsing to see whether where we started is at a
1743 ;; non-zero nesting level. It may be slow for people who write
1744 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001745 (re-search-backward py-parse-state-re nil 'move)
1746 (beginning-of-line)
1747 (parse-partial-sexp (point) here))))
1748
1749;; if point is at a non-zero nesting level, returns the number of the
1750;; character that opens the smallest enclosing unclosed list; else
1751;; returns nil.
1752(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001753 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754 (if (zerop (car status))
1755 nil ; not in a nest
1756 (car (cdr status))))) ; char# of open bracket
1757
1758;; t iff preceding line ends with backslash that's not in a comment
1759(defun py-backslash-continuation-line-p ()
1760 (save-excursion
1761 (beginning-of-line)
1762 (and
1763 ;; use a cheap test first to avoid the regexp if possible
1764 ;; use 'eq' because char-after may return nil
1765 (eq (char-after (- (point) 2)) ?\\ )
1766 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001767 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768 (looking-at py-continued-re))))
1769
1770;; t iff current line is a continuation line
1771(defun py-continuation-line-p ()
1772 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774 (or (py-backslash-continuation-line-p)
1775 (py-nesting-level))))
1776
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777;; go to initial line of current statement; usually this is the line
1778;; we're on, but if we're on the 2nd or following lines of a
1779;; continuation block, we need to go up to the first line of the
1780;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001781;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001782;; Tricky: We want to avoid quadratic-time behavior for long continued
1783;; blocks, whether of the backslash or open-bracket varieties, or a
1784;; mix of the two. The following manages to do that in the usual
1785;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001786(defun py-goto-initial-line ()
1787 (let ( open-bracket-pos )
1788 (while (py-continuation-line-p)
1789 (beginning-of-line)
1790 (if (py-backslash-continuation-line-p)
1791 (while (py-backslash-continuation-line-p)
1792 (forward-line -1))
1793 ;; else zip out of nested brackets/braces/parens
1794 (while (setq open-bracket-pos (py-nesting-level))
1795 (goto-char open-bracket-pos)))))
1796 (beginning-of-line))
1797
1798;; go to point right beyond final line of current statement; usually
1799;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800;; statement we need to skip over the continuation lines. Tricky:
1801;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001802(defun py-goto-beyond-final-line ()
1803 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001804 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805 (while (and (py-continuation-line-p)
1806 (not (eobp)))
1807 ;; skip over the backslash flavor
1808 (while (and (py-backslash-continuation-line-p)
1809 (not (eobp)))
1810 (forward-line 1))
1811 ;; if in nest, zip to the end of the nest
1812 (setq state (py-parse-state))
1813 (if (and (not (zerop (car state)))
1814 (not (eobp)))
1815 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001816 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001817 ;; the 3rd argument should be plain 0
1818 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1819 nil state)
1820 (forward-line 1))))))
1821
1822;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001823;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001824(defun py-statement-opens-block-p ()
1825 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001826 (let ((start (point))
1827 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1828 (searching t)
1829 (answer nil)
1830 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001831 (goto-char start)
1832 (while searching
1833 ;; look for a colon with nothing after it except whitespace, and
1834 ;; maybe a comment
1835 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1836 finish t)
1837 (if (eq (point) finish) ; note: no `else' clause; just
1838 ; keep searching if we're not at
1839 ; the end yet
1840 ;; sure looks like it opens a block -- but it might
1841 ;; be in a comment
1842 (progn
1843 (setq searching nil) ; search is done either way
1844 (setq state (parse-partial-sexp start
1845 (match-beginning 0)))
1846 (setq answer (not (nth 4 state)))))
1847 ;; search failed: couldn't find another interesting colon
1848 (setq searching nil)))
1849 answer)))
1850
1851;; go to point right beyond final line of block begun by the current
1852;; line. This is the same as where py-goto-beyond-final-line goes
1853;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855(defun py-goto-beyond-block ()
1856 (if (py-statement-opens-block-p)
1857 (py-mark-block nil 'just-move)
1858 (py-goto-beyond-final-line)))
1859
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001860;; go to start of first statement (not blank or comment or
1861;; continuation line) at or preceding point. returns t if there is
1862;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863(defun py-goto-statement-at-or-above ()
1864 (py-goto-initial-line)
1865 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001866 ;; skip back over blank & comment lines
1867 ;; note: will skip a blank or comment line that happens to be
1868 ;; a continuation line too
1869 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1870 (progn (py-goto-initial-line) t)
1871 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001872 t))
1873
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001874;; go to start of first statement (not blank or comment or
1875;; continuation line) following the statement containing point returns
1876;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001877(defun py-goto-statement-below ()
1878 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001879 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880 (py-goto-beyond-final-line)
1881 (while (and
1882 (looking-at py-blank-or-comment-re)
1883 (not (eobp)))
1884 (forward-line 1))
1885 (if (eobp)
1886 (progn (goto-char start) nil)
1887 t)))
1888
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001889;; go to start of statement, at or preceding point, starting with
1890;; keyword KEY. Skips blank lines and non-indenting comments upward
1891;; first. If that statement starts with KEY, done, else go back to
1892;; first enclosing block starting with KEY. If successful, leaves
1893;; point at the start of the KEY line & returns t. Else leaves point
1894;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895(defun py-go-up-tree-to-keyword (key)
1896 ;; skip blanks and non-indenting #
1897 (py-goto-initial-line)
1898 (while (and
1899 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1900 (zerop (forward-line -1))) ; go back
1901 nil)
1902 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001903 (let* ((re (concat "[ \t]*" key "\\b"))
1904 (case-fold-search nil) ; let* so looking-at sees this
1905 (found (looking-at re))
1906 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001907 (while (not (or found dead))
1908 (condition-case nil ; in case no enclosing block
1909 (py-goto-block-up 'no-mark)
1910 (error (setq dead t)))
1911 (or dead (setq found (looking-at re))))
1912 (beginning-of-line)
1913 found))
1914
1915;; return string in buffer from start of indentation to end of line;
1916;; prefix "..." if leading whitespace was skipped
1917(defun py-suck-up-leading-text ()
1918 (save-excursion
1919 (back-to-indentation)
1920 (concat
1921 (if (bolp) "" "...")
1922 (buffer-substring (point) (progn (end-of-line) (point))))))
1923
1924;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1925;; as a Lisp symbol; return nil if none
1926(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001927 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001928 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1929 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1930 nil)))
1931
1932(defun py-make-temp-name ()
1933 (make-temp-name
1934 (concat (file-name-as-directory py-temp-directory) "python")))
1935
1936(defun py-delete-file-silently (fname)
1937 (condition-case nil
1938 (delete-file fname)
1939 (error nil)))
1940
1941(defun py-kill-emacs-hook ()
1942 ;; delete our temp files
1943 (while py-file-queue
1944 (py-delete-file-silently (car py-file-queue))
1945 (setq py-file-queue (cdr py-file-queue)))
1946 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1947 ;; run the hook we inherited, if any
1948 (and py-inherited-kill-emacs-hook
1949 (funcall py-inherited-kill-emacs-hook))))
1950
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001951;; make PROCESS's buffer visible, append STRING to it, and force
1952;; display; also make shell-mode believe the user typed this string,
1953;; so that kill-output-from-shell and show-output-from-shell work
1954;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001955(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001956 (let ((cbuf (current-buffer))
1957 (pbuf (process-buffer process))
1958 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001959 (set-buffer pbuf)
1960 (goto-char (point-max))
1961 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001962 (if (not (or py-this-is-emacs-19-p
1963 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964 (move-marker last-input-start (point))) ; muck w/ shell-mode
1965 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001966 (if (not (or py-this-is-emacs-19-p
1967 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001968 (move-marker last-input-end (point))) ; muck w/ shell-mode
1969 (set-buffer cbuf))
1970 (sit-for 0))
1971
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001972(defun py-keep-region-active ()
1973 ;; do whatever is necessary to keep the region active in XEmacs.
1974 ;; Ignore byte-compiler warnings you might see. Also note that
1975 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1976 ;; require us to take explicit action.
1977 (and (boundp 'zmacs-region-stays)
1978 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001979
1980
Barry Warsaw850437a1995-03-08 21:50:28 +00001981(defconst py-version "$Revision$"
1982 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001983(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001984 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001985
Barry Warsaw850437a1995-03-08 21:50:28 +00001986(defun py-version ()
1987 "Echo the current version of `python-mode' in the minibuffer."
1988 (interactive)
1989 (message "Using `python-mode' version %s" py-version)
1990 (py-keep-region-active))
1991
1992;; only works under Emacs 19
1993;(eval-when-compile
1994; (require 'reporter))
1995
1996(defun py-submit-bug-report (enhancement-p)
1997 "Submit via mail a bug report on `python-mode'.
1998With \\[universal-argument] just submit an enhancement request."
1999 (interactive
2000 (list (not (y-or-n-p
2001 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002002 (let ((reporter-prompt-for-summary-p (if enhancement-p
2003 "(Very) brief summary: "
2004 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002005 (require 'reporter)
2006 (reporter-submit-bug-report
2007 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002008 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002009 ;; varlist
2010 (if enhancement-p nil
2011 '(py-python-command
2012 py-indent-offset
2013 py-block-comment-prefix
2014 py-scroll-process-buffer
2015 py-temp-directory
2016 py-beep-if-tab-change))
2017 nil ;pre-hooks
2018 nil ;post-hooks
2019 "Dear Barry,") ;salutation
2020 (if enhancement-p nil
2021 (set-mark (point))
2022 (insert
2023"Please replace this text with a sufficiently large code sample\n\
2024and an exact recipe so that I can reproduce your problem. Failure\n\
2025to do so may mean a greater delay in fixing your bug.\n\n")
2026 (exchange-point-and-mark)
2027 (py-keep-region-active))))
2028
2029
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030;; arrange to kill temp files when Emacs exists
2031(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2032 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2033 ;; have to trust that other people are as respectful of our hook
2034 ;; fiddling as we are of theirs
2035 (if (boundp 'py-inherited-kill-emacs-hook)
2036 ;; we were loaded before -- trust others not to have screwed us
2037 ;; in the meantime (no choice, really)
2038 nil
2039 ;; else arrange for our hook to run theirs
2040 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2041 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2042
2043
2044
2045(provide 'python-mode)
2046;;; python-mode.el ends here