blob: d5fb9566fb209f2fe22893d4d02680537a7d4d97 [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)
Barry Warsaw57697af1995-09-14 20:01:14 +0000410 ;; Emacs 19 requires this
411 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
412 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000413 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000414 (mapcar (function (lambda (x)
415 (make-local-variable (car x))
416 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000417 '((paragraph-separate . "^[ \t]*$")
418 (paragraph-start . "^[ \t]*$")
419 (require-final-newline . t)
420 (comment-start . "# ")
421 (comment-start-skip . "# *")
422 (comment-column . 40)
423 (indent-region-function . py-indent-region)
424 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000425 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000426 ;;
427 ;; not sure where the magic comment has to be; to save time
428 ;; searching for a rarity, we give up if it's not found prior to the
429 ;; first executable statement.
430 ;;
431 ;; BAW - on first glance, this seems like complete hackery. Why was
432 ;; this necessary, and is it still necessary?
433 (let ((case-fold-search nil)
434 (start (point))
435 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000436 (if (re-search-forward
437 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
438 (prog2 (py-next-statement 1) (point) (goto-char 1))
439 t)
440 (progn
441 (setq new-tab-width
442 (string-to-int
443 (buffer-substring (match-beginning 1) (match-end 1))))
444 (if (= tab-width new-tab-width)
445 nil
446 (setq tab-width new-tab-width)
447 (message "Caution: tab-width changed to %d" new-tab-width)
448 (if py-beep-if-tab-change (beep)))))
449 (goto-char start))
450
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000451 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000452 (if python-mode-hook
453 (run-hooks 'python-mode-hook)
454 (run-hooks 'py-mode-hook)))
455
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000456
Barry Warsawb91b7431995-03-14 15:55:20 +0000457;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000458(defun py-outdent-p ()
459 ;; returns non-nil if the current line should outdent one level
460 (save-excursion
461 (and (progn (back-to-indentation)
462 (looking-at py-outdent-re))
463 (progn (backward-to-indentation 1)
464 (while (or (looking-at py-blank-or-comment-re)
465 (bobp))
466 (backward-to-indentation 1))
467 (not (looking-at py-no-outdent-re)))
468 )))
469
470
Barry Warsawb91b7431995-03-14 15:55:20 +0000471(defun py-electric-colon (arg)
472 "Insert a colon.
473In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000474argument is provided, that many colons are inserted non-electrically.
475Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000476 (interactive "P")
477 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000478 ;; are we in a string or comment?
479 (if (save-excursion
480 (let ((pps (parse-partial-sexp (save-excursion
481 (beginning-of-python-def-or-class)
482 (point))
483 (point))))
484 (not (or (nth 3 pps) (nth 4 pps)))))
485 (save-excursion
486 (let ((here (point))
487 (outdent 0)
488 (indent (py-compute-indentation)))
489 (if (and (not arg)
490 (py-outdent-p)
491 (= indent (save-excursion
492 (forward-line -1)
493 (py-compute-indentation)))
494 )
495 (setq outdent py-indent-offset))
496 ;; Don't indent, only outdent. This assumes that any lines that
497 ;; are already outdented relative to py-compute-indentation were
498 ;; put there on purpose. Its highly annoying to have `:' indent
499 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
500 ;; there a better way to determine this???
501 (if (< (current-indentation) indent) nil
502 (goto-char here)
503 (beginning-of-line)
504 (delete-horizontal-space)
505 (indent-to (- indent outdent))
506 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000507
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000508(defun py-indent-right (arg)
509 "Indent the line by one `py-indent-offset' level.
510With numeric arg, indent by that many levels. You cannot indent
511farther right than the distance the line would be indented by
512\\[py-indent-line]."
513 (interactive "p")
514 (let ((col (current-indentation))
515 (want (* arg py-indent-offset))
516 (indent (py-compute-indentation))
517 (pos (- (point-max) (point)))
518 (bol (save-excursion (beginning-of-line) (point))))
519 (if (<= (+ col want) indent)
520 (progn
521 (beginning-of-line)
522 (delete-horizontal-space)
523 (indent-to (+ col want))
524 (if (> (- (point-max) pos) (point))
525 (goto-char (- (point-max) pos)))
526 ))))
527
528(defun py-outdent-left (arg)
529 "Outdent the line by one `py-indent-offset' level.
530With numeric arg, outdent by that many levels. You cannot outdent
531farther left than column zero."
532 (interactive "p")
533 (let ((col (current-indentation))
534 (want (* arg py-indent-offset))
535 (pos (- (point-max) (point)))
536 (bol (save-excursion (beginning-of-line) (point))))
537 (if (<= 0 (- col want))
538 (progn
539 (beginning-of-line)
540 (delete-horizontal-space)
541 (indent-to (- col want))
542 (if (> (- (point-max) pos) (point))
543 (goto-char (- (point-max) pos)))
544 ))))
545
Barry Warsawb91b7431995-03-14 15:55:20 +0000546
Barry Warsaw7ae77681994-12-12 20:38:05 +0000547;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000548(defun py-shell ()
549 "Start an interactive Python interpreter in another window.
550This is like Shell mode, except that Python is running in the window
551instead of a shell. See the `Interactive Shell' and `Shell Mode'
552sections of the Emacs manual for details, especially for the key
553bindings active in the `*Python*' buffer.
554
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000555See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556behavior in the process window.
557
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000558Warning: Don't use an interactive Python if you change sys.ps1 or
559sys.ps2 from their default values, or if you're running code that
560prints `>>> ' or `... ' at the start of a line. `python-mode' can't
561distinguish your output from Python's output, and assumes that `>>> '
562at the start of a line is a prompt from Python. Similarly, the Emacs
563Shell mode code assumes that both `>>> ' and `... ' at the start of a
564line are Python prompts. Bad things can happen if you fool either
565mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000566
567Warning: If you do any editing *in* the process buffer *while* the
568buffer is accepting output from Python, do NOT attempt to `undo' the
569changes. Some of the output (nowhere near the parts you changed!) may
570be lost if you do. This appears to be an Emacs bug, an unfortunate
571interaction between undo and process filters; the same problem exists in
572non-Python process buffers using the default (Emacs-supplied) process
573filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000574 ;; BAW - should undo be disabled in the python process buffer, if
575 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576 (interactive)
577 (if py-this-is-emacs-19-p
578 (progn
579 (require 'comint)
580 (switch-to-buffer-other-window
581 (make-comint "Python" py-python-command)))
582 (progn
583 (require 'shell)
584 (switch-to-buffer-other-window
Barry Warsaw6e98f331995-07-05 22:06:50 +0000585 (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
586 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000587 (make-local-variable 'shell-prompt-pattern)
588 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
589 (set-process-filter (get-buffer-process (current-buffer))
590 'py-process-filter)
591 (set-syntax-table py-mode-syntax-table))
592
593(defun py-execute-region (start end)
594 "Send the region between START and END to a Python interpreter.
595If there is a *Python* process it is used.
596
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000597Hint: If you want to execute part of a Python file several times
598\(e.g., perhaps you're developing a function and want to flesh it out
599a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
600the region of interest, and send the code to a *Python* process via
601`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000602
603Following are subtleties to note when using a *Python* process:
604
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000605If a *Python* process is used, the region is copied into a temporary
606file (in directory `py-temp-directory'), and an `execfile' command is
607sent to Python naming that file. If you send regions faster than
608Python can execute them, `python-mode' will save them into distinct
609temp files, and execute the next one in the queue the next time it
610sees a `>>> ' prompt from Python. Each time this happens, the process
611buffer is popped into a window (if it's not already in some window) so
612you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000613
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000614 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000615
616is inserted at the end.
617
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000618Caution: No more than 26 regions can be pending at any given time.
619This limit is (indirectly) inherited from libc's mktemp(3).
620`python-mode' does not try to protect you from exceeding the limit.
621It's extremely unlikely that you'll get anywhere close to the limit in
622practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000623
624See the `\\[py-shell]' docs for additional warnings."
625 (interactive "r")
626 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000627 (let ((pyproc (get-process "Python"))
628 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000629 (if (null pyproc)
630 (shell-command-on-region start end py-python-command)
631 ;; else feed it thru a temp file
632 (setq fname (py-make-temp-name))
633 (write-region start end fname nil 'no-msg)
634 (setq py-file-queue (append py-file-queue (list fname)))
635 (if (cdr py-file-queue)
636 (message "File %s queued for execution" fname)
637 ;; else
638 (py-execute-file pyproc fname)))))
639
640(defun py-execute-file (pyproc fname)
641 (py-append-to-process-buffer
642 pyproc
643 (format "## working on region in file %s ...\n" fname))
644 (process-send-string pyproc (format "execfile('%s')\n" fname)))
645
646(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000647 (let ((curbuf (current-buffer))
648 (pbuf (process-buffer pyproc))
649 (pmark (process-mark pyproc))
650 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000651
652 ;; make sure we switch to a different buffer at least once. if we
653 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000654 ;; window, and point is before the end, and lots of output is
655 ;; coming at a fast pace, then (a) simple cursor-movement commands
656 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
657 ;; to have a visible effect (the window just doesn't get updated,
658 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
659 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000660 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000661 ;; #b makes no sense to me at all. #a almost makes sense: unless
662 ;; we actually change buffers, set_buffer_internal in buffer.c
663 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
664 ;; seems to make the Emacs command loop reluctant to update the
665 ;; display. Perhaps the default process filter in process.c's
666 ;; read_process_output has update_mode_lines++ for a similar
667 ;; reason? beats me ...
668
669 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000670 (if (eq curbuf pbuf) ; mysterious ugly hack
671 (set-buffer (get-buffer-create "*scratch*")))
672
673 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000674 (let* ((start (point))
675 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000676 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000677 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000678 (goto-char pmark)
679 (insert string)
680 (move-marker pmark (point))
681 (setq file-finished
682 (and py-file-queue
683 (equal ">>> "
684 (buffer-substring
685 (prog2 (beginning-of-line) (point)
686 (goto-char pmark))
687 (point)))))
688 (if goback (goto-char start)
689 ;; else
690 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000691 (let* ((pop-up-windows t)
692 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000693 (set-window-point pwin (point)))))
694 (set-buffer curbuf)
695 (if file-finished
696 (progn
697 (py-delete-file-silently (car py-file-queue))
698 (setq py-file-queue (cdr py-file-queue))
699 (if py-file-queue
700 (py-execute-file pyproc (car py-file-queue)))))
701 (and goend
702 (progn (set-buffer pbuf)
703 (goto-char (point-max))))
704 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000705
706(defun py-execute-buffer ()
707 "Send the contents of the buffer to a Python interpreter.
708If there is a *Python* process buffer it is used. If a clipping
709restriction is in effect, only the accessible portion of the buffer is
710sent. A trailing newline will be supplied if needed.
711
712See the `\\[py-execute-region]' docs for an account of some subtleties."
713 (interactive)
714 (py-execute-region (point-min) (point-max)))
715
716
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000717
718;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000719(defun py-delete-char ()
720 "Reduce indentation or delete character.
721If point is at the leftmost column, deletes the preceding newline.
722
723Else if point is at the leftmost non-blank character of a line that is
724neither a continuation line nor a non-indenting comment line, or if
725point is at the end of a blank line, reduces the indentation to match
726that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000727opened the block is displayed in the echo area to help you keep track
728of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000729
730Else the preceding character is deleted, converting a tab to spaces if
731needed so that only a single column position is deleted."
732 (interactive "*")
733 (if (or (/= (current-indentation) (current-column))
734 (bolp)
735 (py-continuation-line-p)
736 (looking-at "#[^ \t\n]")) ; non-indenting #
737 (backward-delete-char-untabify 1)
738 ;; else indent the same as the colon line that opened the block
739
740 ;; force non-blank so py-goto-block-up doesn't ignore it
741 (insert-char ?* 1)
742 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000743 (let ((base-indent 0) ; indentation of base line
744 (base-text "") ; and text of base line
745 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746 (condition-case nil ; in case no enclosing block
747 (save-excursion
748 (py-goto-block-up 'no-mark)
749 (setq base-indent (current-indentation)
750 base-text (py-suck-up-leading-text)
751 base-found-p t))
752 (error nil))
753 (delete-char 1) ; toss the dummy character
754 (delete-horizontal-space)
755 (indent-to base-indent)
756 (if base-found-p
757 (message "Closes block: %s" base-text)))))
758
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000759;; required for pending-del and delsel modes
760(put 'py-delete-char 'delete-selection 'supersede)
761(put 'py-delete-char 'pending-delete 'supersede)
762
Barry Warsaw7ae77681994-12-12 20:38:05 +0000763(defun py-indent-line ()
764 "Fix the indentation of the current line according to Python rules."
765 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000766 (let* ((ci (current-indentation))
767 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000768 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000769 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000770 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000771 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000772 (if (/= ci need)
773 (save-excursion
774 (beginning-of-line)
775 (delete-horizontal-space)
776 (indent-to need)))
777 (if move-to-indentation-p (back-to-indentation))))
778
779(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000780 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000781This is just `strives to' because correct indentation can't be computed
782from scratch for Python code. In general, deletes the whitespace before
783point, inserts a newline, and takes an educated guess as to how you want
784the new line indented."
785 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000786 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000787 (if (< ci (current-column)) ; if point beyond indentation
788 (newline-and-indent)
789 ;; else try to act like newline-and-indent "normally" acts
790 (beginning-of-line)
791 (insert-char ?\n 1)
792 (move-to-column ci))))
793
794(defun py-compute-indentation ()
795 (save-excursion
796 (beginning-of-line)
797 (cond
Barry Warsawc01c5c81995-09-14 18:49:11 +0000798 ;; are we inside a string or comment?
799 ((save-excursion
800 (let ((pps (parse-partial-sexp (save-excursion
801 (beginning-of-python-def-or-class)
802 (point))
803 (point))))
804 (or (nth 3 pps) (nth 4 pps))))
805 (save-excursion
806 ;; skip back over blank & non-indenting comment lines note:
807 ;; will skip a blank or non-indenting comment line that
808 ;; happens to be a continuation line too
809 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
810 (back-to-indentation)
811 (current-column)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000813 ((py-continuation-line-p)
814 (let ((startpos (point))
815 (open-bracket-pos (py-nesting-level))
816 endpos searching found)
817 (if open-bracket-pos
818 (progn
819 ;; align with first item in list; else a normal
820 ;; indent beyond the line with the open bracket
821 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
822 ;; is the first list item on the same line?
823 (skip-chars-forward " \t")
824 (if (null (memq (following-char) '(?\n ?# ?\\)))
825 ; yes, so line up with it
826 (current-column)
827 ;; first list item on another line, or doesn't exist yet
828 (forward-line 1)
829 (while (and (< (point) startpos)
830 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
831 (forward-line 1))
832 (if (< (point) startpos)
833 ;; again mimic the first list item
834 (current-indentation)
835 ;; else they're about to enter the first item
836 (goto-char open-bracket-pos)
837 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000838
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000839 ;; else on backslash continuation line
840 (forward-line -1)
841 (if (py-continuation-line-p) ; on at least 3rd line in block
842 (current-indentation) ; so just continue the pattern
843 ;; else started on 2nd line in block, so indent more.
844 ;; if base line is an assignment with a start on a RHS,
845 ;; indent to 2 beyond the leftmost "="; else skip first
846 ;; chunk of non-whitespace characters on base line, + 1 more
847 ;; column
848 (end-of-line)
849 (setq endpos (point) searching t)
850 (back-to-indentation)
851 (setq startpos (point))
852 ;; look at all "=" from left to right, stopping at first
853 ;; one not nested in a list or string
854 (while searching
855 (skip-chars-forward "^=" endpos)
856 (if (= (point) endpos)
857 (setq searching nil)
858 (forward-char 1)
859 (setq state (parse-partial-sexp startpos (point)))
860 (if (and (zerop (car state)) ; not in a bracket
861 (null (nth 3 state))) ; & not in a string
862 (progn
863 (setq searching nil) ; done searching in any case
864 (setq found
865 (not (or
866 (eq (following-char) ?=)
867 (memq (char-after (- (point) 2))
868 '(?< ?> ?!)))))))))
869 (if (or (not found) ; not an assignment
870 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
871 (progn
872 (goto-char startpos)
873 (skip-chars-forward "^ \t\n")))
874 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000875
876 ;; not on a continuation line
877
878 ;; if at start of restriction, or on a non-indenting comment line,
879 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000880 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
881 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882
883 ;; else indentation based on that of the statement that precedes
884 ;; us; use the first line of that statement to establish the base,
885 ;; in case the user forced a non-std indentation for the
886 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000887 (t
888 ;; skip back over blank & non-indenting comment lines
889 ;; note: will skip a blank or non-indenting comment line that
890 ;; happens to be a continuation line too
891 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
892 nil 'move)
893 ;; if we landed inside a string, go to the beginning of that
894 ;; string. this handles triple quoted, multi-line spanning
895 ;; strings.
896 (let ((state (parse-partial-sexp
897 (save-excursion (beginning-of-python-def-or-class)
898 (point))
899 (point))))
900 (if (nth 3 state)
901 (goto-char (nth 2 state))))
902 (py-goto-initial-line)
903 (if (py-statement-opens-block-p)
904 (+ (current-indentation) py-indent-offset)
905 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906
907(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000910`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000911Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000912`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000913their own buffer-local copy), both those currently existing and those
914created later in the Emacs session.
915
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000916Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000917There's no excuse for such foolishness, but sometimes you have to deal
918with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000919`py-indent-offset' to what it thinks it was when they created the
920mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000921
922Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000923looking for a line that opens a block of code. `py-indent-offset' is
924set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925statement following it. If the search doesn't succeed going forward,
926it's tried again going backward."
927 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000928 (let (new-value
929 (start (point))
930 restart
931 (found nil)
932 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000933 (py-goto-initial-line)
934 (while (not (or found (eobp)))
935 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
936 (progn
937 (setq restart (point))
938 (py-goto-initial-line)
939 (if (py-statement-opens-block-p)
940 (setq found t)
941 (goto-char restart)))))
942 (if found
943 ()
944 (goto-char start)
945 (py-goto-initial-line)
946 (while (not (or found (bobp)))
947 (setq found
948 (and
949 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
950 (or (py-goto-initial-line) t) ; always true -- side effect
951 (py-statement-opens-block-p)))))
952 (setq colon-indent (current-indentation)
953 found (and found (zerop (py-next-statement 1)))
954 new-value (- (current-indentation) colon-indent))
955 (goto-char start)
956 (if found
957 (progn
958 (funcall (if global 'kill-local-variable 'make-local-variable)
959 'py-indent-offset)
960 (setq py-indent-offset new-value)
961 (message "%s value of py-indent-offset set to %d"
962 (if global "Global" "Local")
963 py-indent-offset))
964 (error "Sorry, couldn't guess a value for py-indent-offset"))))
965
966(defun py-shift-region (start end count)
967 (save-excursion
968 (goto-char end) (beginning-of-line) (setq end (point))
969 (goto-char start) (beginning-of-line) (setq start (point))
970 (indent-rigidly start end count)))
971
972(defun py-shift-region-left (start end &optional count)
973 "Shift region of Python code to the left.
974The lines from the line containing the start of the current region up
975to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000976shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977
978If a prefix argument is given, the region is instead shifted by that
979many columns."
980 (interactive "*r\nP") ; region; raw prefix arg
981 (py-shift-region start end
982 (- (prefix-numeric-value
983 (or count py-indent-offset)))))
984
985(defun py-shift-region-right (start end &optional count)
986 "Shift region of Python code to the right.
987The lines from the line containing the start of the current region up
988to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000989shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000990
991If a prefix argument is given, the region is instead shifted by that
992many columns."
993 (interactive "*r\nP") ; region; raw prefix arg
994 (py-shift-region start end (prefix-numeric-value
995 (or count py-indent-offset))))
996
997(defun py-indent-region (start end &optional indent-offset)
998 "Reindent a region of Python code.
999The lines from the line containing the start of the current region up
1000to (but not including) the line containing the end of the region are
1001reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001002character in the first column, the first line is left alone and the
1003rest of the region is reindented with respect to it. Else the entire
1004region is reindented with respect to the (closest code or
1005indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006
1007This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001008control structures are introduced or removed, or to reformat code
1009using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001010
1011If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013used.
1014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001015Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016is called! This function does not compute proper indentation from
1017scratch (that's impossible in Python), it merely adjusts the existing
1018indentation to be correct in context.
1019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020Warning: This function really has no idea what to do with
1021non-indenting comment lines, and shifts them as if they were indenting
1022comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024Special cases: whitespace is deleted from blank lines; continuation
1025lines are shifted by the same amount their initial line was shifted,
1026in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029 (save-excursion
1030 (goto-char end) (beginning-of-line) (setq end (point-marker))
1031 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001032 (let ((py-indent-offset (prefix-numeric-value
1033 (or indent-offset py-indent-offset)))
1034 (indents '(-1)) ; stack of active indent levels
1035 (target-column 0) ; column to which to indent
1036 (base-shifted-by 0) ; amount last base line was shifted
1037 (indent-base (if (looking-at "[ \t\n]")
1038 (py-compute-indentation)
1039 0))
1040 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041 (while (< (point) end)
1042 (setq ci (current-indentation))
1043 ;; figure out appropriate target column
1044 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001045 ((or (eq (following-char) ?#) ; comment in column 1
1046 (looking-at "[ \t]*$")) ; entirely blank
1047 (setq target-column 0))
1048 ((py-continuation-line-p) ; shift relative to base line
1049 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001050 (t ; new base line
1051 (if (> ci (car indents)) ; going deeper; push it
1052 (setq indents (cons ci indents))
1053 ;; else we should have seen this indent before
1054 (setq indents (memq ci indents)) ; pop deeper indents
1055 (if (null indents)
1056 (error "Bad indentation in region, at line %d"
1057 (save-restriction
1058 (widen)
1059 (1+ (count-lines 1 (point)))))))
1060 (setq target-column (+ indent-base
1061 (* py-indent-offset
1062 (- (length indents) 2))))
1063 (setq base-shifted-by (- target-column ci))))
1064 ;; shift as needed
1065 (if (/= ci target-column)
1066 (progn
1067 (delete-horizontal-space)
1068 (indent-to target-column)))
1069 (forward-line 1))))
1070 (set-marker end nil))
1071
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072
1073;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001074(defun py-previous-statement (count)
1075 "Go to the start of previous Python statement.
1076If the statement at point is the i'th Python statement, goes to the
1077start of statement i-COUNT. If there is no such statement, goes to the
1078first statement. Returns count of statements left to move.
1079`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001081 (if (< count 0) (py-next-statement (- count))
1082 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001086 (> count 0)
1087 (zerop (forward-line -1))
1088 (py-goto-statement-at-or-above))
1089 (setq count (1- count)))
1090 (if (> count 0) (goto-char start)))
1091 count))
1092
1093(defun py-next-statement (count)
1094 "Go to the start of next Python statement.
1095If the statement at point is the i'th Python statement, goes to the
1096start of statement i+COUNT. If there is no such statement, goes to the
1097last statement. Returns count of statements left to move. `Statements'
1098do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001099 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 (if (< count 0) (py-previous-statement (- count))
1101 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001102 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001103 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001104 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001105 (> count 0)
1106 (py-goto-statement-below))
1107 (setq count (1- count)))
1108 (if (> count 0) (goto-char start)))
1109 count))
1110
1111(defun py-goto-block-up (&optional nomark)
1112 "Move up to start of current block.
1113Go to the statement that starts the smallest enclosing block; roughly
1114speaking, this will be the closest preceding statement that ends with a
1115colon and is indented less than the statement you started on. If
1116successful, also sets the mark to the starting point.
1117
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001118`\\[py-mark-block]' can be used afterward to mark the whole code
1119block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001120
1121If called from a program, the mark will not be set if optional argument
1122NOMARK is not nil."
1123 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001124 (let ((start (point))
1125 (found nil)
1126 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001127 (py-goto-initial-line)
1128 ;; if on blank or non-indenting comment line, use the preceding stmt
1129 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1130 (progn
1131 (py-goto-statement-at-or-above)
1132 (setq found (py-statement-opens-block-p))))
1133 ;; search back for colon line indented less
1134 (setq initial-indent (current-indentation))
1135 (if (zerop initial-indent)
1136 ;; force fast exit
1137 (goto-char (point-min)))
1138 (while (not (or found (bobp)))
1139 (setq found
1140 (and
1141 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1142 (or (py-goto-initial-line) t) ; always true -- side effect
1143 (< (current-indentation) initial-indent)
1144 (py-statement-opens-block-p))))
1145 (if found
1146 (progn
1147 (or nomark (push-mark start))
1148 (back-to-indentation))
1149 (goto-char start)
1150 (error "Enclosing block not found"))))
1151
1152(defun beginning-of-python-def-or-class (&optional class)
1153 "Move point to start of def (or class, with prefix arg).
1154
1155Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001156arg, looks for a `class' instead. The docs assume the `def' case;
1157just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001158
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001159If point is in a def statement already, and after the `d', simply
1160moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001161
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001162Else (point is not in a def statement, or at or before the `d' of a
1163def statement), searches for the closest preceding def statement, and
1164leaves point at its start. If no such statement can be found, leaves
1165point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001166
1167Returns t iff a def statement is found by these rules.
1168
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001169Note that doing this command repeatedly will take you closer to the
1170start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001171
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001172If you want to mark the current def/class, see
1173`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001175 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1176 (start-of-line (progn (beginning-of-line) (point)))
1177 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001178 (if (or (/= start-of-stmt start-of-line)
1179 (not at-or-before-p))
1180 (end-of-line)) ; OK to match on this line
1181 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183
1184(defun end-of-python-def-or-class (&optional class)
1185 "Move point beyond end of def (or class, with prefix arg) body.
1186
1187By default, looks for an appropriate `def'. If you supply a prefix arg,
1188looks for a `class' instead. The docs assume the `def' case; just
1189substitute `class' for `def' for the other case.
1190
1191If point is in a def statement already, this is the def we use.
1192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193Else if the def found by `\\[beginning-of-python-def-or-class]'
1194contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195
1196Else we search forward for the closest following def, and use that.
1197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198If a def can be found by these rules, point is moved to the start of
1199the line immediately following the def block, and the position of the
1200start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
1202Else point is moved to the end of the buffer, and nil is returned.
1203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001204Note that doing this command repeatedly will take you closer to the
1205end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001206
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207If you want to mark the current def/class, see
1208`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001209 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001210 (let ((start (progn (py-goto-initial-line) (point)))
1211 (which (if class "class" "def"))
1212 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001213 ;; move point to start of appropriate def/class
1214 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1215 (setq state 'at-beginning)
1216 ;; else see if beginning-of-python-def-or-class hits container
1217 (if (and (beginning-of-python-def-or-class class)
1218 (progn (py-goto-beyond-block)
1219 (> (point) start)))
1220 (setq state 'at-end)
1221 ;; else search forward
1222 (goto-char start)
1223 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1224 (progn (setq state 'at-beginning)
1225 (beginning-of-line)))))
1226 (cond
1227 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1228 ((eq state 'at-end) t)
1229 ((eq state 'not-found) nil)
1230 (t (error "internal error in end-of-python-def-or-class")))))
1231
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001232
1233;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001234(defun py-mark-block (&optional extend just-move)
1235 "Mark following block of lines. With prefix arg, mark structure.
1236Easier to use than explain. It sets the region to an `interesting'
1237block of succeeding lines. If point is on a blank line, it goes down to
1238the next non-blank line. That will be the start of the region. The end
1239of the region depends on the kind of line at the start:
1240
1241 - If a comment, the region will include all succeeding comment lines up
1242 to (but not including) the next non-comment line (if any).
1243
1244 - Else if a prefix arg is given, and the line begins one of these
1245 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001246
1247 if elif else try except finally for while def class
1248
Barry Warsaw7ae77681994-12-12 20:38:05 +00001249 the region will be set to the body of the structure, including
1250 following blocks that `belong' to it, but excluding trailing blank
1251 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001252 and all (if any) of the following `except' and `finally' blocks
1253 that belong to the `try' structure will be in the region. Ditto
1254 for if/elif/else, for/else and while/else structures, and (a bit
1255 degenerate, since they're always one-block structures) def and
1256 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257
1258 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001259 block (see list above), and the block is not a `one-liner' (i.e.,
1260 the statement ends with a colon, not with code), the region will
1261 include all succeeding lines up to (but not including) the next
1262 code statement (if any) that's indented no more than the starting
1263 line, except that trailing blank and comment lines are excluded.
1264 E.g., if the starting line begins a multi-statement `def'
1265 structure, the region will be set to the full function definition,
1266 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001267
1268 - Else the region will include all succeeding lines up to (but not
1269 including) the next blank line, or code or indenting-comment line
1270 indented strictly less than the starting line. Trailing indenting
1271 comment lines are included in this case, but not trailing blank
1272 lines.
1273
1274A msg identifying the location of the mark is displayed in the echo
1275area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1276
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001277If called from a program, optional argument EXTEND plays the role of
1278the prefix arg, and if optional argument JUST-MOVE is not nil, just
1279moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280 (interactive "P") ; raw prefix arg
1281 (py-goto-initial-line)
1282 ;; skip over blank lines
1283 (while (and
1284 (looking-at "[ \t]*$") ; while blank line
1285 (not (eobp))) ; & somewhere to go
1286 (forward-line 1))
1287 (if (eobp)
1288 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001289 (let ((initial-pos (point))
1290 (initial-indent (current-indentation))
1291 last-pos ; position of last stmt in region
1292 (followers
1293 '((if elif else) (elif elif else) (else)
1294 (try except finally) (except except) (finally)
1295 (for else) (while else)
1296 (def) (class) ) )
1297 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001298
1299 (cond
1300 ;; if comment line, suck up the following comment lines
1301 ((looking-at "[ \t]*#")
1302 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1303 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1304 (setq last-pos (point)))
1305
1306 ;; else if line is a block line and EXTEND given, suck up
1307 ;; the whole structure
1308 ((and extend
1309 (setq first-symbol (py-suck-up-first-keyword) )
1310 (assq first-symbol followers))
1311 (while (and
1312 (or (py-goto-beyond-block) t) ; side effect
1313 (forward-line -1) ; side effect
1314 (setq last-pos (point)) ; side effect
1315 (py-goto-statement-below)
1316 (= (current-indentation) initial-indent)
1317 (setq next-symbol (py-suck-up-first-keyword))
1318 (memq next-symbol (cdr (assq first-symbol followers))))
1319 (setq first-symbol next-symbol)))
1320
1321 ;; else if line *opens* a block, search for next stmt indented <=
1322 ((py-statement-opens-block-p)
1323 (while (and
1324 (setq last-pos (point)) ; always true -- side effect
1325 (py-goto-statement-below)
1326 (> (current-indentation) initial-indent))
1327 nil))
1328
1329 ;; else plain code line; stop at next blank line, or stmt or
1330 ;; indenting comment line indented <
1331 (t
1332 (while (and
1333 (setq last-pos (point)) ; always true -- side effect
1334 (or (py-goto-beyond-final-line) t)
1335 (not (looking-at "[ \t]*$")) ; stop at blank line
1336 (or
1337 (>= (current-indentation) initial-indent)
1338 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1339 nil)))
1340
1341 ;; skip to end of last stmt
1342 (goto-char last-pos)
1343 (py-goto-beyond-final-line)
1344
1345 ;; set mark & display
1346 (if just-move
1347 () ; just return
1348 (push-mark (point) 'no-msg)
1349 (forward-line -1)
1350 (message "Mark set after: %s" (py-suck-up-leading-text))
1351 (goto-char initial-pos))))
1352
1353(defun mark-python-def-or-class (&optional class)
1354 "Set region to body of def (or class, with prefix arg) enclosing point.
1355Pushes the current mark, then point, on the mark ring (all language
1356modes do this, but although it's handy it's never documented ...).
1357
1358In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1360`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361
1362And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363Turned out that was more confusing than useful: the `goto start' and
1364`goto end' commands are usually used to search through a file, and
1365people expect them to act a lot like `search backward' and `search
1366forward' string-search commands. But because Python `def' and `class'
1367can nest to arbitrary levels, finding the smallest def containing
1368point cannot be done via a simple backward search: the def containing
1369point may not be the closest preceding def, or even the closest
1370preceding def that's indented less. The fancy algorithm required is
1371appropriate for the usual uses of this `mark' command, but not for the
1372`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001374So the def marked by this command may not be the one either of the
1375`goto' commands find: If point is on a blank or non-indenting comment
1376line, moves back to start of the closest preceding code statement or
1377indenting comment line. If this is a `def' statement, that's the def
1378we use. Else searches for the smallest enclosing `def' block and uses
1379that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381When an enclosing def is found: The mark is left immediately beyond
1382the last line of the def block. Point is left at the start of the
1383def, except that: if the def is preceded by a number of comment lines
1384followed by (at most) one optional blank line, point is left at the
1385start of the comments; else if the def is preceded by a blank line,
1386point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001387
1388The intent is to mark the containing def/class and its associated
1389documentation, to make moving and duplicating functions and classes
1390pleasant."
1391 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392 (let ((start (point))
1393 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001394 (push-mark start)
1395 (if (not (py-go-up-tree-to-keyword which))
1396 (progn (goto-char start)
1397 (error "Enclosing %s not found" which))
1398 ;; else enclosing def/class found
1399 (setq start (point))
1400 (py-goto-beyond-block)
1401 (push-mark (point))
1402 (goto-char start)
1403 (if (zerop (forward-line -1)) ; if there is a preceding line
1404 (progn
1405 (if (looking-at "[ \t]*$") ; it's blank
1406 (setq start (point)) ; so reset start point
1407 (goto-char start)) ; else try again
1408 (if (zerop (forward-line -1))
1409 (if (looking-at "[ \t]*#") ; a comment
1410 ;; look back for non-comment line
1411 ;; tricky: note that the regexp matches a blank
1412 ;; line, cuz \n is in the 2nd character class
1413 (and
1414 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1415 (forward-line 1))
1416 ;; no comment, so go back
1417 (goto-char start))))))))
1418
1419(defun py-comment-region (start end &optional uncomment-p)
1420 "Comment out region of code; with prefix arg, uncomment region.
1421The lines from the line containing the start of the current region up
1422to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001423commented out, by inserting the string `py-block-comment-prefix' at
1424the start of each line. With a prefix arg, removes
1425`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001426 (interactive "*r\nP") ; region; raw prefix arg
1427 (goto-char end) (beginning-of-line) (setq end (point))
1428 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001429 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001430 (save-excursion
1431 (save-restriction
1432 (narrow-to-region start end)
1433 (while (not (eobp))
1434 (if uncomment-p
1435 (and (string= py-block-comment-prefix
1436 (buffer-substring
1437 (point) (+ (point) prefix-len)))
1438 (delete-char prefix-len))
1439 (insert py-block-comment-prefix))
1440 (forward-line 1))))))
1441
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001442
1443;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001444
1445;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001446;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1447;; out of the right places, along with the keys they're on & current
1448;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449(defun py-dump-help-string (str)
1450 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001451 (let ((locals (buffer-local-variables))
1452 funckind funcname func funcdoc
1453 (start 0) mstart end
1454 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1456 (setq mstart (match-beginning 0) end (match-end 0)
1457 funckind (substring str (match-beginning 1) (match-end 1))
1458 funcname (substring str (match-beginning 2) (match-end 2))
1459 func (intern funcname))
1460 (princ (substitute-command-keys (substring str start mstart)))
1461 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001462 ((equal funckind "c") ; command
1463 (setq funcdoc (documentation func)
1464 keys (concat
1465 "Key(s): "
1466 (mapconcat 'key-description
1467 (where-is-internal func py-mode-map)
1468 ", "))))
1469 ((equal funckind "v") ; variable
1470 (setq funcdoc (substitute-command-keys
1471 (get func 'variable-documentation))
1472 keys (if (assq func locals)
1473 (concat
1474 "Local/Global values: "
1475 (prin1-to-string (symbol-value func))
1476 " / "
1477 (prin1-to-string (default-value func)))
1478 (concat
1479 "Value: "
1480 (prin1-to-string (symbol-value func))))))
1481 (t ; unexpected
1482 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001483 (princ (format "\n-> %s:\t%s\t%s\n\n"
1484 (if (equal funckind "c") "Command" "Variable")
1485 funcname keys))
1486 (princ funcdoc)
1487 (terpri)
1488 (setq start end))
1489 (princ (substitute-command-keys (substring str start))))
1490 (print-help-return-message)))
1491
1492(defun py-describe-mode ()
1493 "Dump long form of Python-mode docs."
1494 (interactive)
1495 (py-dump-help-string "Major mode for editing Python files.
1496Knows about Python indentation, tokens, comments and continuation lines.
1497Paragraphs are separated by blank lines only.
1498
1499Major sections below begin with the string `@'; specific function and
1500variable docs begin with `->'.
1501
1502@EXECUTING PYTHON CODE
1503
1504\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1505\\[py-execute-region]\tsends the current region
1506\\[py-shell]\tstarts a Python interpreter window; this will be used by
1507\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1508%c:py-execute-buffer
1509%c:py-execute-region
1510%c:py-shell
1511
1512@VARIABLES
1513
1514py-indent-offset\tindentation increment
1515py-block-comment-prefix\tcomment string used by py-comment-region
1516
1517py-python-command\tshell command to invoke Python interpreter
1518py-scroll-process-buffer\talways scroll Python process buffer
1519py-temp-directory\tdirectory used for temp files (if needed)
1520
1521py-beep-if-tab-change\tring the bell if tab-width is changed
1522%v:py-indent-offset
1523%v:py-block-comment-prefix
1524%v:py-python-command
1525%v:py-scroll-process-buffer
1526%v:py-temp-directory
1527%v:py-beep-if-tab-change
1528
1529@KINDS OF LINES
1530
1531Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001532preceding line ends with a backslash that's not part of a comment, or
1533the paren/bracket/brace nesting level at the start of the line is
1534non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001535
1536An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537possibly blanks or tabs), a `comment line' (leftmost non-blank
1538character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001539
1540Comment Lines
1541
1542Although all comment lines are treated alike by Python, Python mode
1543recognizes two kinds that act differently with respect to indentation.
1544
1545An `indenting comment line' is a comment line with a blank, tab or
1546nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548indenting comment line will be indented like the comment line. All
1549other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001550following the initial `#') are `non-indenting comment lines', and
1551their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552
1553Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001554whenever possible. Non-indenting comment lines are useful in cases
1555like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001556
1557\ta = b # a very wordy single-line comment that ends up being
1558\t #... continued onto another line
1559
1560\tif a == b:
1561##\t\tprint 'panic!' # old code we've `commented out'
1562\t\treturn a
1563
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001564Since the `#...' and `##' comment lines have a non-whitespace
1565character following the initial `#', Python mode ignores them when
1566computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567
1568Continuation Lines and Statements
1569
1570The Python-mode commands generally work on statements instead of on
1571individual lines, where a `statement' is a comment or blank line, or a
1572code line and all of its following continuation lines (if any)
1573considered as a single logical unit. The commands in this mode
1574generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001575statement containing point, even if point happens to be in the middle
1576of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577
1578
1579@INDENTATION
1580
1581Primarily for entering new code:
1582\t\\[indent-for-tab-command]\t indent line appropriately
1583\t\\[py-newline-and-indent]\t insert newline, then indent
1584\t\\[py-delete-char]\t reduce indentation, or delete single character
1585
1586Primarily for reindenting existing code:
1587\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1588\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1589
1590\t\\[py-indent-region]\t reindent region to match its context
1591\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1592\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1593
1594Unlike most programming languages, Python uses indentation, and only
1595indentation, to specify block structure. Hence the indentation supplied
1596automatically by Python-mode is just an educated guess: only you know
1597the block structure you intend, so only you can supply correct
1598indentation.
1599
1600The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1601the indentation of preceding statements. E.g., assuming
1602py-indent-offset is 4, after you enter
1603\tif a > 0: \\[py-newline-and-indent]
1604the cursor will be moved to the position of the `_' (_ is not a
1605character in the file, it's just used here to indicate the location of
1606the cursor):
1607\tif a > 0:
1608\t _
1609If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1610to
1611\tif a > 0:
1612\t c = d
1613\t _
1614Python-mode cannot know whether that's what you intended, or whether
1615\tif a > 0:
1616\t c = d
1617\t_
1618was your intent. In general, Python-mode either reproduces the
1619indentation of the (closest code or indenting-comment) preceding
1620statement, or adds an extra py-indent-offset blanks if the preceding
1621statement has `:' as its last significant (non-whitespace and non-
1622comment) character. If the suggested indentation is too much, use
1623\\[py-delete-char] to reduce it.
1624
1625Continuation lines are given extra indentation. If you don't like the
1626suggested indentation, change it to something you do like, and Python-
1627mode will strive to indent later lines of the statement in the same way.
1628
1629If a line is a continuation line by virtue of being in an unclosed
1630paren/bracket/brace structure (`list', for short), the suggested
1631indentation depends on whether the current line contains the first item
1632in the list. If it does, it's indented py-indent-offset columns beyond
1633the indentation of the line containing the open bracket. If you don't
1634like that, change it by hand. The remaining items in the list will mimic
1635whatever indentation you give to the first item.
1636
1637If a line is a continuation line because the line preceding it ends with
1638a backslash, the third and following lines of the statement inherit their
1639indentation from the line preceding them. The indentation of the second
1640line in the statement depends on the form of the first (base) line: if
1641the base line is an assignment statement with anything more interesting
1642than the backslash following the leftmost assigning `=', the second line
1643is indented two columns beyond that `='. Else it's indented to two
1644columns beyond the leftmost solid chunk of non-whitespace characters on
1645the base line.
1646
1647Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1648repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1649structure you intend.
1650%c:indent-for-tab-command
1651%c:py-newline-and-indent
1652%c:py-delete-char
1653
1654
1655The next function may be handy when editing code you didn't write:
1656%c:py-guess-indent-offset
1657
1658
1659The remaining `indent' functions apply to a region of Python code. They
1660assume the block structure (equals indentation, in Python) of the region
1661is correct, and alter the indentation in various ways while preserving
1662the block structure:
1663%c:py-indent-region
1664%c:py-shift-region-left
1665%c:py-shift-region-right
1666
1667@MARKING & MANIPULATING REGIONS OF CODE
1668
1669\\[py-mark-block]\t mark block of lines
1670\\[mark-python-def-or-class]\t mark smallest enclosing def
1671\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1672\\[py-comment-region]\t comment out region of code
1673\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1674%c:py-mark-block
1675%c:mark-python-def-or-class
1676%c:py-comment-region
1677
1678@MOVING POINT
1679
1680\\[py-previous-statement]\t move to statement preceding point
1681\\[py-next-statement]\t move to statement following point
1682\\[py-goto-block-up]\t move up to start of current block
1683\\[beginning-of-python-def-or-class]\t move to start of def
1684\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1685\\[end-of-python-def-or-class]\t move to end of def
1686\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1687
1688The first two move to one statement beyond the statement that contains
1689point. A numeric prefix argument tells them to move that many
1690statements instead. Blank lines, comment lines, and continuation lines
1691do not count as `statements' for these commands. So, e.g., you can go
1692to the first code statement in a file by entering
1693\t\\[beginning-of-buffer]\t to move to the top of the file
1694\t\\[py-next-statement]\t to skip over initial comments and blank lines
1695Or do `\\[py-previous-statement]' with a huge prefix argument.
1696%c:py-previous-statement
1697%c:py-next-statement
1698%c:py-goto-block-up
1699%c:beginning-of-python-def-or-class
1700%c:end-of-python-def-or-class
1701
1702@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1703
1704`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1705
1706`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1707overall class and def structure of a module.
1708
1709`\\[back-to-indentation]' moves point to a line's first non-blank character.
1710
1711`\\[indent-relative]' is handy for creating odd indentation.
1712
1713@OTHER EMACS HINTS
1714
1715If you don't like the default value of a variable, change its value to
1716whatever you do like by putting a `setq' line in your .emacs file.
1717E.g., to set the indentation increment to 4, put this line in your
1718.emacs:
1719\t(setq py-indent-offset 4)
1720To see the value of a variable, do `\\[describe-variable]' and enter the variable
1721name at the prompt.
1722
1723When entering a key sequence like `C-c C-n', it is not necessary to
1724release the CONTROL key after doing the `C-c' part -- it suffices to
1725press the CONTROL key, press and release `c' (while still holding down
1726CONTROL), press and release `n' (while still holding down CONTROL), &
1727then release CONTROL.
1728
1729Entering Python mode calls with no arguments the value of the variable
1730`python-mode-hook', if that value exists and is not nil; for backward
1731compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1732the Elisp manual for details.
1733
1734Obscure: When python-mode is first loaded, it looks for all bindings
1735to newline-and-indent in the global keymap, and shadows them with
1736local bindings to py-newline-and-indent."))
1737
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738
1739;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001740(defvar py-parse-state-re
1741 (concat
1742 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1743 "\\|"
1744 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001745
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746;; returns the parse state at point (see parse-partial-sexp docs)
1747(defun py-parse-state ()
1748 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001750 ;; back up to the first preceding line (if any; else start of
1751 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752 ;; whitespace and non-comment character. These are good places
1753 ;; to start parsing to see whether where we started is at a
1754 ;; non-zero nesting level. It may be slow for people who write
1755 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (re-search-backward py-parse-state-re nil 'move)
1757 (beginning-of-line)
1758 (parse-partial-sexp (point) here))))
1759
1760;; if point is at a non-zero nesting level, returns the number of the
1761;; character that opens the smallest enclosing unclosed list; else
1762;; returns nil.
1763(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001765 (if (zerop (car status))
1766 nil ; not in a nest
1767 (car (cdr status))))) ; char# of open bracket
1768
1769;; t iff preceding line ends with backslash that's not in a comment
1770(defun py-backslash-continuation-line-p ()
1771 (save-excursion
1772 (beginning-of-line)
1773 (and
1774 ;; use a cheap test first to avoid the regexp if possible
1775 ;; use 'eq' because char-after may return nil
1776 (eq (char-after (- (point) 2)) ?\\ )
1777 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779 (looking-at py-continued-re))))
1780
1781;; t iff current line is a continuation line
1782(defun py-continuation-line-p ()
1783 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785 (or (py-backslash-continuation-line-p)
1786 (py-nesting-level))))
1787
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788;; go to initial line of current statement; usually this is the line
1789;; we're on, but if we're on the 2nd or following lines of a
1790;; continuation block, we need to go up to the first line of the
1791;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001793;; Tricky: We want to avoid quadratic-time behavior for long continued
1794;; blocks, whether of the backslash or open-bracket varieties, or a
1795;; mix of the two. The following manages to do that in the usual
1796;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797(defun py-goto-initial-line ()
1798 (let ( open-bracket-pos )
1799 (while (py-continuation-line-p)
1800 (beginning-of-line)
1801 (if (py-backslash-continuation-line-p)
1802 (while (py-backslash-continuation-line-p)
1803 (forward-line -1))
1804 ;; else zip out of nested brackets/braces/parens
1805 (while (setq open-bracket-pos (py-nesting-level))
1806 (goto-char open-bracket-pos)))))
1807 (beginning-of-line))
1808
1809;; go to point right beyond final line of current statement; usually
1810;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811;; statement we need to skip over the continuation lines. Tricky:
1812;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813(defun py-goto-beyond-final-line ()
1814 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001816 (while (and (py-continuation-line-p)
1817 (not (eobp)))
1818 ;; skip over the backslash flavor
1819 (while (and (py-backslash-continuation-line-p)
1820 (not (eobp)))
1821 (forward-line 1))
1822 ;; if in nest, zip to the end of the nest
1823 (setq state (py-parse-state))
1824 (if (and (not (zerop (car state)))
1825 (not (eobp)))
1826 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828 ;; the 3rd argument should be plain 0
1829 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1830 nil state)
1831 (forward-line 1))))))
1832
1833;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001835(defun py-statement-opens-block-p ()
1836 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837 (let ((start (point))
1838 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1839 (searching t)
1840 (answer nil)
1841 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842 (goto-char start)
1843 (while searching
1844 ;; look for a colon with nothing after it except whitespace, and
1845 ;; maybe a comment
1846 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1847 finish t)
1848 (if (eq (point) finish) ; note: no `else' clause; just
1849 ; keep searching if we're not at
1850 ; the end yet
1851 ;; sure looks like it opens a block -- but it might
1852 ;; be in a comment
1853 (progn
1854 (setq searching nil) ; search is done either way
1855 (setq state (parse-partial-sexp start
1856 (match-beginning 0)))
1857 (setq answer (not (nth 4 state)))))
1858 ;; search failed: couldn't find another interesting colon
1859 (setq searching nil)))
1860 answer)))
1861
1862;; go to point right beyond final line of block begun by the current
1863;; line. This is the same as where py-goto-beyond-final-line goes
1864;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866(defun py-goto-beyond-block ()
1867 (if (py-statement-opens-block-p)
1868 (py-mark-block nil 'just-move)
1869 (py-goto-beyond-final-line)))
1870
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871;; go to start of first statement (not blank or comment or
1872;; continuation line) at or preceding point. returns t if there is
1873;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874(defun py-goto-statement-at-or-above ()
1875 (py-goto-initial-line)
1876 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 ;; skip back over blank & comment lines
1878 ;; note: will skip a blank or comment line that happens to be
1879 ;; a continuation line too
1880 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1881 (progn (py-goto-initial-line) t)
1882 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883 t))
1884
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885;; go to start of first statement (not blank or comment or
1886;; continuation line) following the statement containing point returns
1887;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888(defun py-goto-statement-below ()
1889 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001890 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001891 (py-goto-beyond-final-line)
1892 (while (and
1893 (looking-at py-blank-or-comment-re)
1894 (not (eobp)))
1895 (forward-line 1))
1896 (if (eobp)
1897 (progn (goto-char start) nil)
1898 t)))
1899
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900;; go to start of statement, at or preceding point, starting with
1901;; keyword KEY. Skips blank lines and non-indenting comments upward
1902;; first. If that statement starts with KEY, done, else go back to
1903;; first enclosing block starting with KEY. If successful, leaves
1904;; point at the start of the KEY line & returns t. Else leaves point
1905;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001906(defun py-go-up-tree-to-keyword (key)
1907 ;; skip blanks and non-indenting #
1908 (py-goto-initial-line)
1909 (while (and
1910 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1911 (zerop (forward-line -1))) ; go back
1912 nil)
1913 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914 (let* ((re (concat "[ \t]*" key "\\b"))
1915 (case-fold-search nil) ; let* so looking-at sees this
1916 (found (looking-at re))
1917 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918 (while (not (or found dead))
1919 (condition-case nil ; in case no enclosing block
1920 (py-goto-block-up 'no-mark)
1921 (error (setq dead t)))
1922 (or dead (setq found (looking-at re))))
1923 (beginning-of-line)
1924 found))
1925
1926;; return string in buffer from start of indentation to end of line;
1927;; prefix "..." if leading whitespace was skipped
1928(defun py-suck-up-leading-text ()
1929 (save-excursion
1930 (back-to-indentation)
1931 (concat
1932 (if (bolp) "" "...")
1933 (buffer-substring (point) (progn (end-of-line) (point))))))
1934
1935;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1936;; as a Lisp symbol; return nil if none
1937(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1940 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1941 nil)))
1942
1943(defun py-make-temp-name ()
1944 (make-temp-name
1945 (concat (file-name-as-directory py-temp-directory) "python")))
1946
1947(defun py-delete-file-silently (fname)
1948 (condition-case nil
1949 (delete-file fname)
1950 (error nil)))
1951
1952(defun py-kill-emacs-hook ()
1953 ;; delete our temp files
1954 (while py-file-queue
1955 (py-delete-file-silently (car py-file-queue))
1956 (setq py-file-queue (cdr py-file-queue)))
1957 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1958 ;; run the hook we inherited, if any
1959 (and py-inherited-kill-emacs-hook
1960 (funcall py-inherited-kill-emacs-hook))))
1961
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001962;; make PROCESS's buffer visible, append STRING to it, and force
1963;; display; also make shell-mode believe the user typed this string,
1964;; so that kill-output-from-shell and show-output-from-shell work
1965;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001966(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967 (let ((cbuf (current-buffer))
1968 (pbuf (process-buffer process))
1969 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001970 (set-buffer pbuf)
1971 (goto-char (point-max))
1972 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001973 (if (not (or py-this-is-emacs-19-p
1974 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001975 (move-marker last-input-start (point))) ; muck w/ shell-mode
1976 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001977 (if (not (or py-this-is-emacs-19-p
1978 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001979 (move-marker last-input-end (point))) ; muck w/ shell-mode
1980 (set-buffer cbuf))
1981 (sit-for 0))
1982
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001983(defun py-keep-region-active ()
1984 ;; do whatever is necessary to keep the region active in XEmacs.
1985 ;; Ignore byte-compiler warnings you might see. Also note that
1986 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1987 ;; require us to take explicit action.
1988 (and (boundp 'zmacs-region-stays)
1989 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001990
1991
Barry Warsaw850437a1995-03-08 21:50:28 +00001992(defconst py-version "$Revision$"
1993 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001994(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001995 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996
Barry Warsaw850437a1995-03-08 21:50:28 +00001997(defun py-version ()
1998 "Echo the current version of `python-mode' in the minibuffer."
1999 (interactive)
2000 (message "Using `python-mode' version %s" py-version)
2001 (py-keep-region-active))
2002
2003;; only works under Emacs 19
2004;(eval-when-compile
2005; (require 'reporter))
2006
2007(defun py-submit-bug-report (enhancement-p)
2008 "Submit via mail a bug report on `python-mode'.
2009With \\[universal-argument] just submit an enhancement request."
2010 (interactive
2011 (list (not (y-or-n-p
2012 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002013 (let ((reporter-prompt-for-summary-p (if enhancement-p
2014 "(Very) brief summary: "
2015 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002016 (require 'reporter)
2017 (reporter-submit-bug-report
2018 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002019 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002020 ;; varlist
2021 (if enhancement-p nil
2022 '(py-python-command
2023 py-indent-offset
2024 py-block-comment-prefix
2025 py-scroll-process-buffer
2026 py-temp-directory
2027 py-beep-if-tab-change))
2028 nil ;pre-hooks
2029 nil ;post-hooks
2030 "Dear Barry,") ;salutation
2031 (if enhancement-p nil
2032 (set-mark (point))
2033 (insert
2034"Please replace this text with a sufficiently large code sample\n\
2035and an exact recipe so that I can reproduce your problem. Failure\n\
2036to do so may mean a greater delay in fixing your bug.\n\n")
2037 (exchange-point-and-mark)
2038 (py-keep-region-active))))
2039
2040
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002041;; arrange to kill temp files when Emacs exists
2042(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2043 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2044 ;; have to trust that other people are as respectful of our hook
2045 ;; fiddling as we are of theirs
2046 (if (boundp 'py-inherited-kill-emacs-hook)
2047 ;; we were loaded before -- trust others not to have screwed us
2048 ;; in the meantime (no choice, really)
2049 nil
2050 ;; else arrange for our hook to run theirs
2051 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2052 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2053
2054
2055
2056(provide 'python-mode)
2057;;; python-mode.el ends here