blob: c84ede4e15f90adc22f893811eea4781e24c18d4 [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
474argument is provided, that many colons are inserted non-electrically."
475 (interactive "P")
476 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000477 (save-excursion
478 (let ((here (point))
479 (outdent 0)
480 (indent (py-compute-indentation)))
481 (if (and (not arg)
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000482 (py-outdent-p)
Barry Warsaw3aca2a11995-03-20 18:32:14 +0000483 (= indent (save-excursion
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000484 (forward-line -1)
485 (py-compute-indentation)))
486 )
487 (setq outdent py-indent-offset))
Barry Warsawd865bc51995-03-15 18:23:16 +0000488 ;; Don't indent, only outdent. This assumes that any lines that
489 ;; are already outdented relative to py-compute-indentation were
490 ;; put there on purpose. Its highly annoying to have `:' indent
491 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
492 ;; there a better way to determine this???
Barry Warsawa6a714e1995-03-15 18:19:15 +0000493 (if (< (current-indentation) indent) nil
Barry Warsaw9b623b31995-03-14 23:59:07 +0000494 (goto-char here)
495 (beginning-of-line)
496 (delete-horizontal-space)
497 (indent-to (- indent outdent))
498 ))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000499
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000500(defun py-indent-right (arg)
501 "Indent the line by one `py-indent-offset' level.
502With numeric arg, indent by that many levels. You cannot indent
503farther right than the distance the line would be indented by
504\\[py-indent-line]."
505 (interactive "p")
506 (let ((col (current-indentation))
507 (want (* arg py-indent-offset))
508 (indent (py-compute-indentation))
509 (pos (- (point-max) (point)))
510 (bol (save-excursion (beginning-of-line) (point))))
511 (if (<= (+ col want) indent)
512 (progn
513 (beginning-of-line)
514 (delete-horizontal-space)
515 (indent-to (+ col want))
516 (if (> (- (point-max) pos) (point))
517 (goto-char (- (point-max) pos)))
518 ))))
519
520(defun py-outdent-left (arg)
521 "Outdent the line by one `py-indent-offset' level.
522With numeric arg, outdent by that many levels. You cannot outdent
523farther left than column zero."
524 (interactive "p")
525 (let ((col (current-indentation))
526 (want (* arg py-indent-offset))
527 (pos (- (point-max) (point)))
528 (bol (save-excursion (beginning-of-line) (point))))
529 (if (<= 0 (- col want))
530 (progn
531 (beginning-of-line)
532 (delete-horizontal-space)
533 (indent-to (- col want))
534 (if (> (- (point-max) pos) (point))
535 (goto-char (- (point-max) pos)))
536 ))))
537
Barry Warsawb91b7431995-03-14 15:55:20 +0000538
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000540(defun py-shell ()
541 "Start an interactive Python interpreter in another window.
542This is like Shell mode, except that Python is running in the window
543instead of a shell. See the `Interactive Shell' and `Shell Mode'
544sections of the Emacs manual for details, especially for the key
545bindings active in the `*Python*' buffer.
546
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000547See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000548behavior in the process window.
549
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000550Warning: Don't use an interactive Python if you change sys.ps1 or
551sys.ps2 from their default values, or if you're running code that
552prints `>>> ' or `... ' at the start of a line. `python-mode' can't
553distinguish your output from Python's output, and assumes that `>>> '
554at the start of a line is a prompt from Python. Similarly, the Emacs
555Shell mode code assumes that both `>>> ' and `... ' at the start of a
556line are Python prompts. Bad things can happen if you fool either
557mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000558
559Warning: If you do any editing *in* the process buffer *while* the
560buffer is accepting output from Python, do NOT attempt to `undo' the
561changes. Some of the output (nowhere near the parts you changed!) may
562be lost if you do. This appears to be an Emacs bug, an unfortunate
563interaction between undo and process filters; the same problem exists in
564non-Python process buffers using the default (Emacs-supplied) process
565filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000566 ;; BAW - should undo be disabled in the python process buffer, if
567 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000568 (interactive)
569 (if py-this-is-emacs-19-p
570 (progn
571 (require 'comint)
572 (switch-to-buffer-other-window
573 (make-comint "Python" py-python-command)))
574 (progn
575 (require 'shell)
576 (switch-to-buffer-other-window
Barry Warsaw6e98f331995-07-05 22:06:50 +0000577 (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
578 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000579 (make-local-variable 'shell-prompt-pattern)
580 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
581 (set-process-filter (get-buffer-process (current-buffer))
582 'py-process-filter)
583 (set-syntax-table py-mode-syntax-table))
584
585(defun py-execute-region (start end)
586 "Send the region between START and END to a Python interpreter.
587If there is a *Python* process it is used.
588
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000589Hint: If you want to execute part of a Python file several times
590\(e.g., perhaps you're developing a function and want to flesh it out
591a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
592the region of interest, and send the code to a *Python* process via
593`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000594
595Following are subtleties to note when using a *Python* process:
596
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000597If a *Python* process is used, the region is copied into a temporary
598file (in directory `py-temp-directory'), and an `execfile' command is
599sent to Python naming that file. If you send regions faster than
600Python can execute them, `python-mode' will save them into distinct
601temp files, and execute the next one in the queue the next time it
602sees a `>>> ' prompt from Python. Each time this happens, the process
603buffer is popped into a window (if it's not already in some window) so
604you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000605
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000606 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000607
608is inserted at the end.
609
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000610Caution: No more than 26 regions can be pending at any given time.
611This limit is (indirectly) inherited from libc's mktemp(3).
612`python-mode' does not try to protect you from exceeding the limit.
613It's extremely unlikely that you'll get anywhere close to the limit in
614practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000615
616See the `\\[py-shell]' docs for additional warnings."
617 (interactive "r")
618 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000619 (let ((pyproc (get-process "Python"))
620 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000621 (if (null pyproc)
622 (shell-command-on-region start end py-python-command)
623 ;; else feed it thru a temp file
624 (setq fname (py-make-temp-name))
625 (write-region start end fname nil 'no-msg)
626 (setq py-file-queue (append py-file-queue (list fname)))
627 (if (cdr py-file-queue)
628 (message "File %s queued for execution" fname)
629 ;; else
630 (py-execute-file pyproc fname)))))
631
632(defun py-execute-file (pyproc fname)
633 (py-append-to-process-buffer
634 pyproc
635 (format "## working on region in file %s ...\n" fname))
636 (process-send-string pyproc (format "execfile('%s')\n" fname)))
637
638(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000639 (let ((curbuf (current-buffer))
640 (pbuf (process-buffer pyproc))
641 (pmark (process-mark pyproc))
642 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000643
644 ;; make sure we switch to a different buffer at least once. if we
645 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000646 ;; window, and point is before the end, and lots of output is
647 ;; coming at a fast pace, then (a) simple cursor-movement commands
648 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
649 ;; to have a visible effect (the window just doesn't get updated,
650 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
651 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000652 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000653 ;; #b makes no sense to me at all. #a almost makes sense: unless
654 ;; we actually change buffers, set_buffer_internal in buffer.c
655 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
656 ;; seems to make the Emacs command loop reluctant to update the
657 ;; display. Perhaps the default process filter in process.c's
658 ;; read_process_output has update_mode_lines++ for a similar
659 ;; reason? beats me ...
660
661 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000662 (if (eq curbuf pbuf) ; mysterious ugly hack
663 (set-buffer (get-buffer-create "*scratch*")))
664
665 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000666 (let* ((start (point))
667 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000668 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000669 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000670 (goto-char pmark)
671 (insert string)
672 (move-marker pmark (point))
673 (setq file-finished
674 (and py-file-queue
675 (equal ">>> "
676 (buffer-substring
677 (prog2 (beginning-of-line) (point)
678 (goto-char pmark))
679 (point)))))
680 (if goback (goto-char start)
681 ;; else
682 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683 (let* ((pop-up-windows t)
684 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000685 (set-window-point pwin (point)))))
686 (set-buffer curbuf)
687 (if file-finished
688 (progn
689 (py-delete-file-silently (car py-file-queue))
690 (setq py-file-queue (cdr py-file-queue))
691 (if py-file-queue
692 (py-execute-file pyproc (car py-file-queue)))))
693 (and goend
694 (progn (set-buffer pbuf)
695 (goto-char (point-max))))
696 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000697
698(defun py-execute-buffer ()
699 "Send the contents of the buffer to a Python interpreter.
700If there is a *Python* process buffer it is used. If a clipping
701restriction is in effect, only the accessible portion of the buffer is
702sent. A trailing newline will be supplied if needed.
703
704See the `\\[py-execute-region]' docs for an account of some subtleties."
705 (interactive)
706 (py-execute-region (point-min) (point-max)))
707
708
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000709
710;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000711(defun py-delete-char ()
712 "Reduce indentation or delete character.
713If point is at the leftmost column, deletes the preceding newline.
714
715Else if point is at the leftmost non-blank character of a line that is
716neither a continuation line nor a non-indenting comment line, or if
717point is at the end of a blank line, reduces the indentation to match
718that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000719opened the block is displayed in the echo area to help you keep track
720of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000721
722Else the preceding character is deleted, converting a tab to spaces if
723needed so that only a single column position is deleted."
724 (interactive "*")
725 (if (or (/= (current-indentation) (current-column))
726 (bolp)
727 (py-continuation-line-p)
728 (looking-at "#[^ \t\n]")) ; non-indenting #
729 (backward-delete-char-untabify 1)
730 ;; else indent the same as the colon line that opened the block
731
732 ;; force non-blank so py-goto-block-up doesn't ignore it
733 (insert-char ?* 1)
734 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000735 (let ((base-indent 0) ; indentation of base line
736 (base-text "") ; and text of base line
737 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738 (condition-case nil ; in case no enclosing block
739 (save-excursion
740 (py-goto-block-up 'no-mark)
741 (setq base-indent (current-indentation)
742 base-text (py-suck-up-leading-text)
743 base-found-p t))
744 (error nil))
745 (delete-char 1) ; toss the dummy character
746 (delete-horizontal-space)
747 (indent-to base-indent)
748 (if base-found-p
749 (message "Closes block: %s" base-text)))))
750
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000751;; required for pending-del and delsel modes
752(put 'py-delete-char 'delete-selection 'supersede)
753(put 'py-delete-char 'pending-delete 'supersede)
754
Barry Warsaw7ae77681994-12-12 20:38:05 +0000755(defun py-indent-line ()
756 "Fix the indentation of the current line according to Python rules."
757 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000758 (let* ((ci (current-indentation))
759 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000760 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000761 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000762 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000763 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000764 (if (/= ci need)
765 (save-excursion
766 (beginning-of-line)
767 (delete-horizontal-space)
768 (indent-to need)))
769 (if move-to-indentation-p (back-to-indentation))))
770
771(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000772 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000773This is just `strives to' because correct indentation can't be computed
774from scratch for Python code. In general, deletes the whitespace before
775point, inserts a newline, and takes an educated guess as to how you want
776the new line indented."
777 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000778 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000779 (if (< ci (current-column)) ; if point beyond indentation
780 (newline-and-indent)
781 ;; else try to act like newline-and-indent "normally" acts
782 (beginning-of-line)
783 (insert-char ?\n 1)
784 (move-to-column ci))))
785
786(defun py-compute-indentation ()
787 (save-excursion
788 (beginning-of-line)
789 (cond
Barry Warsawc01c5c81995-09-14 18:49:11 +0000790 ;; are we inside a string or comment?
791 ((save-excursion
792 (let ((pps (parse-partial-sexp (save-excursion
793 (beginning-of-python-def-or-class)
794 (point))
795 (point))))
796 (or (nth 3 pps) (nth 4 pps))))
797 (save-excursion
798 ;; skip back over blank & non-indenting comment lines note:
799 ;; will skip a blank or non-indenting comment line that
800 ;; happens to be a continuation line too
801 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
802 (back-to-indentation)
803 (current-column)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000804 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000805 ((py-continuation-line-p)
806 (let ((startpos (point))
807 (open-bracket-pos (py-nesting-level))
808 endpos searching found)
809 (if open-bracket-pos
810 (progn
811 ;; align with first item in list; else a normal
812 ;; indent beyond the line with the open bracket
813 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
814 ;; is the first list item on the same line?
815 (skip-chars-forward " \t")
816 (if (null (memq (following-char) '(?\n ?# ?\\)))
817 ; yes, so line up with it
818 (current-column)
819 ;; first list item on another line, or doesn't exist yet
820 (forward-line 1)
821 (while (and (< (point) startpos)
822 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
823 (forward-line 1))
824 (if (< (point) startpos)
825 ;; again mimic the first list item
826 (current-indentation)
827 ;; else they're about to enter the first item
828 (goto-char open-bracket-pos)
829 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000830
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000831 ;; else on backslash continuation line
832 (forward-line -1)
833 (if (py-continuation-line-p) ; on at least 3rd line in block
834 (current-indentation) ; so just continue the pattern
835 ;; else started on 2nd line in block, so indent more.
836 ;; if base line is an assignment with a start on a RHS,
837 ;; indent to 2 beyond the leftmost "="; else skip first
838 ;; chunk of non-whitespace characters on base line, + 1 more
839 ;; column
840 (end-of-line)
841 (setq endpos (point) searching t)
842 (back-to-indentation)
843 (setq startpos (point))
844 ;; look at all "=" from left to right, stopping at first
845 ;; one not nested in a list or string
846 (while searching
847 (skip-chars-forward "^=" endpos)
848 (if (= (point) endpos)
849 (setq searching nil)
850 (forward-char 1)
851 (setq state (parse-partial-sexp startpos (point)))
852 (if (and (zerop (car state)) ; not in a bracket
853 (null (nth 3 state))) ; & not in a string
854 (progn
855 (setq searching nil) ; done searching in any case
856 (setq found
857 (not (or
858 (eq (following-char) ?=)
859 (memq (char-after (- (point) 2))
860 '(?< ?> ?!)))))))))
861 (if (or (not found) ; not an assignment
862 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
863 (progn
864 (goto-char startpos)
865 (skip-chars-forward "^ \t\n")))
866 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000867
868 ;; not on a continuation line
869
870 ;; if at start of restriction, or on a non-indenting comment line,
871 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000872 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
873 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000874
875 ;; else indentation based on that of the statement that precedes
876 ;; us; use the first line of that statement to establish the base,
877 ;; in case the user forced a non-std indentation for the
878 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000879 (t
880 ;; skip back over blank & non-indenting comment lines
881 ;; note: will skip a blank or non-indenting comment line that
882 ;; happens to be a continuation line too
883 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
884 nil 'move)
885 ;; if we landed inside a string, go to the beginning of that
886 ;; string. this handles triple quoted, multi-line spanning
887 ;; strings.
888 (let ((state (parse-partial-sexp
889 (save-excursion (beginning-of-python-def-or-class)
890 (point))
891 (point))))
892 (if (nth 3 state)
893 (goto-char (nth 2 state))))
894 (py-goto-initial-line)
895 (if (py-statement-opens-block-p)
896 (+ (current-indentation) py-indent-offset)
897 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898
899(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000900 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000902`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000903Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000905their own buffer-local copy), both those currently existing and those
906created later in the Emacs session.
907
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909There's no excuse for such foolishness, but sometimes you have to deal
910with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000911`py-indent-offset' to what it thinks it was when they created the
912mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000913
914Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000915looking for a line that opens a block of code. `py-indent-offset' is
916set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000917statement following it. If the search doesn't succeed going forward,
918it's tried again going backward."
919 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920 (let (new-value
921 (start (point))
922 restart
923 (found nil)
924 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925 (py-goto-initial-line)
926 (while (not (or found (eobp)))
927 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
928 (progn
929 (setq restart (point))
930 (py-goto-initial-line)
931 (if (py-statement-opens-block-p)
932 (setq found t)
933 (goto-char restart)))))
934 (if found
935 ()
936 (goto-char start)
937 (py-goto-initial-line)
938 (while (not (or found (bobp)))
939 (setq found
940 (and
941 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
942 (or (py-goto-initial-line) t) ; always true -- side effect
943 (py-statement-opens-block-p)))))
944 (setq colon-indent (current-indentation)
945 found (and found (zerop (py-next-statement 1)))
946 new-value (- (current-indentation) colon-indent))
947 (goto-char start)
948 (if found
949 (progn
950 (funcall (if global 'kill-local-variable 'make-local-variable)
951 'py-indent-offset)
952 (setq py-indent-offset new-value)
953 (message "%s value of py-indent-offset set to %d"
954 (if global "Global" "Local")
955 py-indent-offset))
956 (error "Sorry, couldn't guess a value for py-indent-offset"))))
957
958(defun py-shift-region (start end count)
959 (save-excursion
960 (goto-char end) (beginning-of-line) (setq end (point))
961 (goto-char start) (beginning-of-line) (setq start (point))
962 (indent-rigidly start end count)))
963
964(defun py-shift-region-left (start end &optional count)
965 "Shift region of Python code to the left.
966The lines from the line containing the start of the current region up
967to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000968shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000969
970If a prefix argument is given, the region is instead shifted by that
971many columns."
972 (interactive "*r\nP") ; region; raw prefix arg
973 (py-shift-region start end
974 (- (prefix-numeric-value
975 (or count py-indent-offset)))))
976
977(defun py-shift-region-right (start end &optional count)
978 "Shift region of Python code to the right.
979The lines from the line containing the start of the current region up
980to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000982
983If a prefix argument is given, the region is instead shifted by that
984many columns."
985 (interactive "*r\nP") ; region; raw prefix arg
986 (py-shift-region start end (prefix-numeric-value
987 (or count py-indent-offset))))
988
989(defun py-indent-region (start end &optional indent-offset)
990 "Reindent a region of Python code.
991The lines from the line containing the start of the current region up
992to (but not including) the line containing the end of the region are
993reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994character in the first column, the first line is left alone and the
995rest of the region is reindented with respect to it. Else the entire
996region is reindented with respect to the (closest code or
997indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000998
999This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001000control structures are introduced or removed, or to reformat code
1001using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002
1003If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005used.
1006
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008is called! This function does not compute proper indentation from
1009scratch (that's impossible in Python), it merely adjusts the existing
1010indentation to be correct in context.
1011
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012Warning: This function really has no idea what to do with
1013non-indenting comment lines, and shifts them as if they were indenting
1014comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001015
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001016Special cases: whitespace is deleted from blank lines; continuation
1017lines are shifted by the same amount their initial line was shifted,
1018in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001019initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001021 (save-excursion
1022 (goto-char end) (beginning-of-line) (setq end (point-marker))
1023 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024 (let ((py-indent-offset (prefix-numeric-value
1025 (or indent-offset py-indent-offset)))
1026 (indents '(-1)) ; stack of active indent levels
1027 (target-column 0) ; column to which to indent
1028 (base-shifted-by 0) ; amount last base line was shifted
1029 (indent-base (if (looking-at "[ \t\n]")
1030 (py-compute-indentation)
1031 0))
1032 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001033 (while (< (point) end)
1034 (setq ci (current-indentation))
1035 ;; figure out appropriate target column
1036 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001037 ((or (eq (following-char) ?#) ; comment in column 1
1038 (looking-at "[ \t]*$")) ; entirely blank
1039 (setq target-column 0))
1040 ((py-continuation-line-p) ; shift relative to base line
1041 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001042 (t ; new base line
1043 (if (> ci (car indents)) ; going deeper; push it
1044 (setq indents (cons ci indents))
1045 ;; else we should have seen this indent before
1046 (setq indents (memq ci indents)) ; pop deeper indents
1047 (if (null indents)
1048 (error "Bad indentation in region, at line %d"
1049 (save-restriction
1050 (widen)
1051 (1+ (count-lines 1 (point)))))))
1052 (setq target-column (+ indent-base
1053 (* py-indent-offset
1054 (- (length indents) 2))))
1055 (setq base-shifted-by (- target-column ci))))
1056 ;; shift as needed
1057 (if (/= ci target-column)
1058 (progn
1059 (delete-horizontal-space)
1060 (indent-to target-column)))
1061 (forward-line 1))))
1062 (set-marker end nil))
1063
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001064
1065;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001066(defun py-previous-statement (count)
1067 "Go to the start of previous Python statement.
1068If the statement at point is the i'th Python statement, goes to the
1069start of statement i-COUNT. If there is no such statement, goes to the
1070first statement. Returns count of statements left to move.
1071`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001073 (if (< count 0) (py-next-statement (- count))
1074 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001075 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001077 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001078 (> count 0)
1079 (zerop (forward-line -1))
1080 (py-goto-statement-at-or-above))
1081 (setq count (1- count)))
1082 (if (> count 0) (goto-char start)))
1083 count))
1084
1085(defun py-next-statement (count)
1086 "Go to the start of next Python statement.
1087If the statement at point is the i'th Python statement, goes to the
1088start of statement i+COUNT. If there is no such statement, goes to the
1089last statement. Returns count of statements left to move. `Statements'
1090do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001091 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 (if (< count 0) (py-previous-statement (- count))
1093 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001095 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001096 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097 (> count 0)
1098 (py-goto-statement-below))
1099 (setq count (1- count)))
1100 (if (> count 0) (goto-char start)))
1101 count))
1102
1103(defun py-goto-block-up (&optional nomark)
1104 "Move up to start of current block.
1105Go to the statement that starts the smallest enclosing block; roughly
1106speaking, this will be the closest preceding statement that ends with a
1107colon and is indented less than the statement you started on. If
1108successful, also sets the mark to the starting point.
1109
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001110`\\[py-mark-block]' can be used afterward to mark the whole code
1111block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001112
1113If called from a program, the mark will not be set if optional argument
1114NOMARK is not nil."
1115 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001116 (let ((start (point))
1117 (found nil)
1118 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001119 (py-goto-initial-line)
1120 ;; if on blank or non-indenting comment line, use the preceding stmt
1121 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1122 (progn
1123 (py-goto-statement-at-or-above)
1124 (setq found (py-statement-opens-block-p))))
1125 ;; search back for colon line indented less
1126 (setq initial-indent (current-indentation))
1127 (if (zerop initial-indent)
1128 ;; force fast exit
1129 (goto-char (point-min)))
1130 (while (not (or found (bobp)))
1131 (setq found
1132 (and
1133 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1134 (or (py-goto-initial-line) t) ; always true -- side effect
1135 (< (current-indentation) initial-indent)
1136 (py-statement-opens-block-p))))
1137 (if found
1138 (progn
1139 (or nomark (push-mark start))
1140 (back-to-indentation))
1141 (goto-char start)
1142 (error "Enclosing block not found"))))
1143
1144(defun beginning-of-python-def-or-class (&optional class)
1145 "Move point to start of def (or class, with prefix arg).
1146
1147Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148arg, looks for a `class' instead. The docs assume the `def' case;
1149just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001151If point is in a def statement already, and after the `d', simply
1152moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001153
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001154Else (point is not in a def statement, or at or before the `d' of a
1155def statement), searches for the closest preceding def statement, and
1156leaves point at its start. If no such statement can be found, leaves
1157point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001158
1159Returns t iff a def statement is found by these rules.
1160
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161Note that doing this command repeatedly will take you closer to the
1162start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001163
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001164If you want to mark the current def/class, see
1165`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001166 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001167 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1168 (start-of-line (progn (beginning-of-line) (point)))
1169 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001170 (if (or (/= start-of-stmt start-of-line)
1171 (not at-or-before-p))
1172 (end-of-line)) ; OK to match on this line
1173 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001174 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001175
1176(defun end-of-python-def-or-class (&optional class)
1177 "Move point beyond end of def (or class, with prefix arg) body.
1178
1179By default, looks for an appropriate `def'. If you supply a prefix arg,
1180looks for a `class' instead. The docs assume the `def' case; just
1181substitute `class' for `def' for the other case.
1182
1183If point is in a def statement already, this is the def we use.
1184
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001185Else if the def found by `\\[beginning-of-python-def-or-class]'
1186contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001187
1188Else we search forward for the closest following def, and use that.
1189
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001190If a def can be found by these rules, point is moved to the start of
1191the line immediately following the def block, and the position of the
1192start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001193
1194Else point is moved to the end of the buffer, and nil is returned.
1195
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001196Note that doing this command repeatedly will take you closer to the
1197end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001198
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199If you want to mark the current def/class, see
1200`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001202 (let ((start (progn (py-goto-initial-line) (point)))
1203 (which (if class "class" "def"))
1204 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001205 ;; move point to start of appropriate def/class
1206 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1207 (setq state 'at-beginning)
1208 ;; else see if beginning-of-python-def-or-class hits container
1209 (if (and (beginning-of-python-def-or-class class)
1210 (progn (py-goto-beyond-block)
1211 (> (point) start)))
1212 (setq state 'at-end)
1213 ;; else search forward
1214 (goto-char start)
1215 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1216 (progn (setq state 'at-beginning)
1217 (beginning-of-line)))))
1218 (cond
1219 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1220 ((eq state 'at-end) t)
1221 ((eq state 'not-found) nil)
1222 (t (error "internal error in end-of-python-def-or-class")))))
1223
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001224
1225;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001226(defun py-mark-block (&optional extend just-move)
1227 "Mark following block of lines. With prefix arg, mark structure.
1228Easier to use than explain. It sets the region to an `interesting'
1229block of succeeding lines. If point is on a blank line, it goes down to
1230the next non-blank line. That will be the start of the region. The end
1231of the region depends on the kind of line at the start:
1232
1233 - If a comment, the region will include all succeeding comment lines up
1234 to (but not including) the next non-comment line (if any).
1235
1236 - Else if a prefix arg is given, and the line begins one of these
1237 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001238
1239 if elif else try except finally for while def class
1240
Barry Warsaw7ae77681994-12-12 20:38:05 +00001241 the region will be set to the body of the structure, including
1242 following blocks that `belong' to it, but excluding trailing blank
1243 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001244 and all (if any) of the following `except' and `finally' blocks
1245 that belong to the `try' structure will be in the region. Ditto
1246 for if/elif/else, for/else and while/else structures, and (a bit
1247 degenerate, since they're always one-block structures) def and
1248 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001249
1250 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001251 block (see list above), and the block is not a `one-liner' (i.e.,
1252 the statement ends with a colon, not with code), the region will
1253 include all succeeding lines up to (but not including) the next
1254 code statement (if any) that's indented no more than the starting
1255 line, except that trailing blank and comment lines are excluded.
1256 E.g., if the starting line begins a multi-statement `def'
1257 structure, the region will be set to the full function definition,
1258 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001259
1260 - Else the region will include all succeeding lines up to (but not
1261 including) the next blank line, or code or indenting-comment line
1262 indented strictly less than the starting line. Trailing indenting
1263 comment lines are included in this case, but not trailing blank
1264 lines.
1265
1266A msg identifying the location of the mark is displayed in the echo
1267area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1268
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001269If called from a program, optional argument EXTEND plays the role of
1270the prefix arg, and if optional argument JUST-MOVE is not nil, just
1271moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001272 (interactive "P") ; raw prefix arg
1273 (py-goto-initial-line)
1274 ;; skip over blank lines
1275 (while (and
1276 (looking-at "[ \t]*$") ; while blank line
1277 (not (eobp))) ; & somewhere to go
1278 (forward-line 1))
1279 (if (eobp)
1280 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281 (let ((initial-pos (point))
1282 (initial-indent (current-indentation))
1283 last-pos ; position of last stmt in region
1284 (followers
1285 '((if elif else) (elif elif else) (else)
1286 (try except finally) (except except) (finally)
1287 (for else) (while else)
1288 (def) (class) ) )
1289 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290
1291 (cond
1292 ;; if comment line, suck up the following comment lines
1293 ((looking-at "[ \t]*#")
1294 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1295 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1296 (setq last-pos (point)))
1297
1298 ;; else if line is a block line and EXTEND given, suck up
1299 ;; the whole structure
1300 ((and extend
1301 (setq first-symbol (py-suck-up-first-keyword) )
1302 (assq first-symbol followers))
1303 (while (and
1304 (or (py-goto-beyond-block) t) ; side effect
1305 (forward-line -1) ; side effect
1306 (setq last-pos (point)) ; side effect
1307 (py-goto-statement-below)
1308 (= (current-indentation) initial-indent)
1309 (setq next-symbol (py-suck-up-first-keyword))
1310 (memq next-symbol (cdr (assq first-symbol followers))))
1311 (setq first-symbol next-symbol)))
1312
1313 ;; else if line *opens* a block, search for next stmt indented <=
1314 ((py-statement-opens-block-p)
1315 (while (and
1316 (setq last-pos (point)) ; always true -- side effect
1317 (py-goto-statement-below)
1318 (> (current-indentation) initial-indent))
1319 nil))
1320
1321 ;; else plain code line; stop at next blank line, or stmt or
1322 ;; indenting comment line indented <
1323 (t
1324 (while (and
1325 (setq last-pos (point)) ; always true -- side effect
1326 (or (py-goto-beyond-final-line) t)
1327 (not (looking-at "[ \t]*$")) ; stop at blank line
1328 (or
1329 (>= (current-indentation) initial-indent)
1330 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1331 nil)))
1332
1333 ;; skip to end of last stmt
1334 (goto-char last-pos)
1335 (py-goto-beyond-final-line)
1336
1337 ;; set mark & display
1338 (if just-move
1339 () ; just return
1340 (push-mark (point) 'no-msg)
1341 (forward-line -1)
1342 (message "Mark set after: %s" (py-suck-up-leading-text))
1343 (goto-char initial-pos))))
1344
1345(defun mark-python-def-or-class (&optional class)
1346 "Set region to body of def (or class, with prefix arg) enclosing point.
1347Pushes the current mark, then point, on the mark ring (all language
1348modes do this, but although it's handy it's never documented ...).
1349
1350In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001351hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1352`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001353
1354And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001355Turned out that was more confusing than useful: the `goto start' and
1356`goto end' commands are usually used to search through a file, and
1357people expect them to act a lot like `search backward' and `search
1358forward' string-search commands. But because Python `def' and `class'
1359can nest to arbitrary levels, finding the smallest def containing
1360point cannot be done via a simple backward search: the def containing
1361point may not be the closest preceding def, or even the closest
1362preceding def that's indented less. The fancy algorithm required is
1363appropriate for the usual uses of this `mark' command, but not for the
1364`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001366So the def marked by this command may not be the one either of the
1367`goto' commands find: If point is on a blank or non-indenting comment
1368line, moves back to start of the closest preceding code statement or
1369indenting comment line. If this is a `def' statement, that's the def
1370we use. Else searches for the smallest enclosing `def' block and uses
1371that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001372
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001373When an enclosing def is found: The mark is left immediately beyond
1374the last line of the def block. Point is left at the start of the
1375def, except that: if the def is preceded by a number of comment lines
1376followed by (at most) one optional blank line, point is left at the
1377start of the comments; else if the def is preceded by a blank line,
1378point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001379
1380The intent is to mark the containing def/class and its associated
1381documentation, to make moving and duplicating functions and classes
1382pleasant."
1383 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001384 (let ((start (point))
1385 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001386 (push-mark start)
1387 (if (not (py-go-up-tree-to-keyword which))
1388 (progn (goto-char start)
1389 (error "Enclosing %s not found" which))
1390 ;; else enclosing def/class found
1391 (setq start (point))
1392 (py-goto-beyond-block)
1393 (push-mark (point))
1394 (goto-char start)
1395 (if (zerop (forward-line -1)) ; if there is a preceding line
1396 (progn
1397 (if (looking-at "[ \t]*$") ; it's blank
1398 (setq start (point)) ; so reset start point
1399 (goto-char start)) ; else try again
1400 (if (zerop (forward-line -1))
1401 (if (looking-at "[ \t]*#") ; a comment
1402 ;; look back for non-comment line
1403 ;; tricky: note that the regexp matches a blank
1404 ;; line, cuz \n is in the 2nd character class
1405 (and
1406 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1407 (forward-line 1))
1408 ;; no comment, so go back
1409 (goto-char start))))))))
1410
1411(defun py-comment-region (start end &optional uncomment-p)
1412 "Comment out region of code; with prefix arg, uncomment region.
1413The lines from the line containing the start of the current region up
1414to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001415commented out, by inserting the string `py-block-comment-prefix' at
1416the start of each line. With a prefix arg, removes
1417`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418 (interactive "*r\nP") ; region; raw prefix arg
1419 (goto-char end) (beginning-of-line) (setq end (point))
1420 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001421 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422 (save-excursion
1423 (save-restriction
1424 (narrow-to-region start end)
1425 (while (not (eobp))
1426 (if uncomment-p
1427 (and (string= py-block-comment-prefix
1428 (buffer-substring
1429 (point) (+ (point) prefix-len)))
1430 (delete-char prefix-len))
1431 (insert py-block-comment-prefix))
1432 (forward-line 1))))))
1433
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001434
1435;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001436
1437;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001438;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1439;; out of the right places, along with the keys they're on & current
1440;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001441(defun py-dump-help-string (str)
1442 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001443 (let ((locals (buffer-local-variables))
1444 funckind funcname func funcdoc
1445 (start 0) mstart end
1446 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001447 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1448 (setq mstart (match-beginning 0) end (match-end 0)
1449 funckind (substring str (match-beginning 1) (match-end 1))
1450 funcname (substring str (match-beginning 2) (match-end 2))
1451 func (intern funcname))
1452 (princ (substitute-command-keys (substring str start mstart)))
1453 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001454 ((equal funckind "c") ; command
1455 (setq funcdoc (documentation func)
1456 keys (concat
1457 "Key(s): "
1458 (mapconcat 'key-description
1459 (where-is-internal func py-mode-map)
1460 ", "))))
1461 ((equal funckind "v") ; variable
1462 (setq funcdoc (substitute-command-keys
1463 (get func 'variable-documentation))
1464 keys (if (assq func locals)
1465 (concat
1466 "Local/Global values: "
1467 (prin1-to-string (symbol-value func))
1468 " / "
1469 (prin1-to-string (default-value func)))
1470 (concat
1471 "Value: "
1472 (prin1-to-string (symbol-value func))))))
1473 (t ; unexpected
1474 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001475 (princ (format "\n-> %s:\t%s\t%s\n\n"
1476 (if (equal funckind "c") "Command" "Variable")
1477 funcname keys))
1478 (princ funcdoc)
1479 (terpri)
1480 (setq start end))
1481 (princ (substitute-command-keys (substring str start))))
1482 (print-help-return-message)))
1483
1484(defun py-describe-mode ()
1485 "Dump long form of Python-mode docs."
1486 (interactive)
1487 (py-dump-help-string "Major mode for editing Python files.
1488Knows about Python indentation, tokens, comments and continuation lines.
1489Paragraphs are separated by blank lines only.
1490
1491Major sections below begin with the string `@'; specific function and
1492variable docs begin with `->'.
1493
1494@EXECUTING PYTHON CODE
1495
1496\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1497\\[py-execute-region]\tsends the current region
1498\\[py-shell]\tstarts a Python interpreter window; this will be used by
1499\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1500%c:py-execute-buffer
1501%c:py-execute-region
1502%c:py-shell
1503
1504@VARIABLES
1505
1506py-indent-offset\tindentation increment
1507py-block-comment-prefix\tcomment string used by py-comment-region
1508
1509py-python-command\tshell command to invoke Python interpreter
1510py-scroll-process-buffer\talways scroll Python process buffer
1511py-temp-directory\tdirectory used for temp files (if needed)
1512
1513py-beep-if-tab-change\tring the bell if tab-width is changed
1514%v:py-indent-offset
1515%v:py-block-comment-prefix
1516%v:py-python-command
1517%v:py-scroll-process-buffer
1518%v:py-temp-directory
1519%v:py-beep-if-tab-change
1520
1521@KINDS OF LINES
1522
1523Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001524preceding line ends with a backslash that's not part of a comment, or
1525the paren/bracket/brace nesting level at the start of the line is
1526non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001527
1528An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001529possibly blanks or tabs), a `comment line' (leftmost non-blank
1530character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001531
1532Comment Lines
1533
1534Although all comment lines are treated alike by Python, Python mode
1535recognizes two kinds that act differently with respect to indentation.
1536
1537An `indenting comment line' is a comment line with a blank, tab or
1538nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540indenting comment line will be indented like the comment line. All
1541other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542following the initial `#') are `non-indenting comment lines', and
1543their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544
1545Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546whenever possible. Non-indenting comment lines are useful in cases
1547like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548
1549\ta = b # a very wordy single-line comment that ends up being
1550\t #... continued onto another line
1551
1552\tif a == b:
1553##\t\tprint 'panic!' # old code we've `commented out'
1554\t\treturn a
1555
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556Since the `#...' and `##' comment lines have a non-whitespace
1557character following the initial `#', Python mode ignores them when
1558computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559
1560Continuation Lines and Statements
1561
1562The Python-mode commands generally work on statements instead of on
1563individual lines, where a `statement' is a comment or blank line, or a
1564code line and all of its following continuation lines (if any)
1565considered as a single logical unit. The commands in this mode
1566generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001567statement containing point, even if point happens to be in the middle
1568of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569
1570
1571@INDENTATION
1572
1573Primarily for entering new code:
1574\t\\[indent-for-tab-command]\t indent line appropriately
1575\t\\[py-newline-and-indent]\t insert newline, then indent
1576\t\\[py-delete-char]\t reduce indentation, or delete single character
1577
1578Primarily for reindenting existing code:
1579\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1580\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1581
1582\t\\[py-indent-region]\t reindent region to match its context
1583\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1584\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1585
1586Unlike most programming languages, Python uses indentation, and only
1587indentation, to specify block structure. Hence the indentation supplied
1588automatically by Python-mode is just an educated guess: only you know
1589the block structure you intend, so only you can supply correct
1590indentation.
1591
1592The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1593the indentation of preceding statements. E.g., assuming
1594py-indent-offset is 4, after you enter
1595\tif a > 0: \\[py-newline-and-indent]
1596the cursor will be moved to the position of the `_' (_ is not a
1597character in the file, it's just used here to indicate the location of
1598the cursor):
1599\tif a > 0:
1600\t _
1601If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1602to
1603\tif a > 0:
1604\t c = d
1605\t _
1606Python-mode cannot know whether that's what you intended, or whether
1607\tif a > 0:
1608\t c = d
1609\t_
1610was your intent. In general, Python-mode either reproduces the
1611indentation of the (closest code or indenting-comment) preceding
1612statement, or adds an extra py-indent-offset blanks if the preceding
1613statement has `:' as its last significant (non-whitespace and non-
1614comment) character. If the suggested indentation is too much, use
1615\\[py-delete-char] to reduce it.
1616
1617Continuation lines are given extra indentation. If you don't like the
1618suggested indentation, change it to something you do like, and Python-
1619mode will strive to indent later lines of the statement in the same way.
1620
1621If a line is a continuation line by virtue of being in an unclosed
1622paren/bracket/brace structure (`list', for short), the suggested
1623indentation depends on whether the current line contains the first item
1624in the list. If it does, it's indented py-indent-offset columns beyond
1625the indentation of the line containing the open bracket. If you don't
1626like that, change it by hand. The remaining items in the list will mimic
1627whatever indentation you give to the first item.
1628
1629If a line is a continuation line because the line preceding it ends with
1630a backslash, the third and following lines of the statement inherit their
1631indentation from the line preceding them. The indentation of the second
1632line in the statement depends on the form of the first (base) line: if
1633the base line is an assignment statement with anything more interesting
1634than the backslash following the leftmost assigning `=', the second line
1635is indented two columns beyond that `='. Else it's indented to two
1636columns beyond the leftmost solid chunk of non-whitespace characters on
1637the base line.
1638
1639Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1640repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1641structure you intend.
1642%c:indent-for-tab-command
1643%c:py-newline-and-indent
1644%c:py-delete-char
1645
1646
1647The next function may be handy when editing code you didn't write:
1648%c:py-guess-indent-offset
1649
1650
1651The remaining `indent' functions apply to a region of Python code. They
1652assume the block structure (equals indentation, in Python) of the region
1653is correct, and alter the indentation in various ways while preserving
1654the block structure:
1655%c:py-indent-region
1656%c:py-shift-region-left
1657%c:py-shift-region-right
1658
1659@MARKING & MANIPULATING REGIONS OF CODE
1660
1661\\[py-mark-block]\t mark block of lines
1662\\[mark-python-def-or-class]\t mark smallest enclosing def
1663\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1664\\[py-comment-region]\t comment out region of code
1665\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1666%c:py-mark-block
1667%c:mark-python-def-or-class
1668%c:py-comment-region
1669
1670@MOVING POINT
1671
1672\\[py-previous-statement]\t move to statement preceding point
1673\\[py-next-statement]\t move to statement following point
1674\\[py-goto-block-up]\t move up to start of current block
1675\\[beginning-of-python-def-or-class]\t move to start of def
1676\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1677\\[end-of-python-def-or-class]\t move to end of def
1678\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1679
1680The first two move to one statement beyond the statement that contains
1681point. A numeric prefix argument tells them to move that many
1682statements instead. Blank lines, comment lines, and continuation lines
1683do not count as `statements' for these commands. So, e.g., you can go
1684to the first code statement in a file by entering
1685\t\\[beginning-of-buffer]\t to move to the top of the file
1686\t\\[py-next-statement]\t to skip over initial comments and blank lines
1687Or do `\\[py-previous-statement]' with a huge prefix argument.
1688%c:py-previous-statement
1689%c:py-next-statement
1690%c:py-goto-block-up
1691%c:beginning-of-python-def-or-class
1692%c:end-of-python-def-or-class
1693
1694@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1695
1696`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1697
1698`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1699overall class and def structure of a module.
1700
1701`\\[back-to-indentation]' moves point to a line's first non-blank character.
1702
1703`\\[indent-relative]' is handy for creating odd indentation.
1704
1705@OTHER EMACS HINTS
1706
1707If you don't like the default value of a variable, change its value to
1708whatever you do like by putting a `setq' line in your .emacs file.
1709E.g., to set the indentation increment to 4, put this line in your
1710.emacs:
1711\t(setq py-indent-offset 4)
1712To see the value of a variable, do `\\[describe-variable]' and enter the variable
1713name at the prompt.
1714
1715When entering a key sequence like `C-c C-n', it is not necessary to
1716release the CONTROL key after doing the `C-c' part -- it suffices to
1717press the CONTROL key, press and release `c' (while still holding down
1718CONTROL), press and release `n' (while still holding down CONTROL), &
1719then release CONTROL.
1720
1721Entering Python mode calls with no arguments the value of the variable
1722`python-mode-hook', if that value exists and is not nil; for backward
1723compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1724the Elisp manual for details.
1725
1726Obscure: When python-mode is first loaded, it looks for all bindings
1727to newline-and-indent in the global keymap, and shadows them with
1728local bindings to py-newline-and-indent."))
1729
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001730
1731;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001732(defvar py-parse-state-re
1733 (concat
1734 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1735 "\\|"
1736 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001737
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738;; returns the parse state at point (see parse-partial-sexp docs)
1739(defun py-parse-state ()
1740 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001742 ;; back up to the first preceding line (if any; else start of
1743 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001744 ;; whitespace and non-comment character. These are good places
1745 ;; to start parsing to see whether where we started is at a
1746 ;; non-zero nesting level. It may be slow for people who write
1747 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001748 (re-search-backward py-parse-state-re nil 'move)
1749 (beginning-of-line)
1750 (parse-partial-sexp (point) here))))
1751
1752;; if point is at a non-zero nesting level, returns the number of the
1753;; character that opens the smallest enclosing unclosed list; else
1754;; returns nil.
1755(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757 (if (zerop (car status))
1758 nil ; not in a nest
1759 (car (cdr status))))) ; char# of open bracket
1760
1761;; t iff preceding line ends with backslash that's not in a comment
1762(defun py-backslash-continuation-line-p ()
1763 (save-excursion
1764 (beginning-of-line)
1765 (and
1766 ;; use a cheap test first to avoid the regexp if possible
1767 ;; use 'eq' because char-after may return nil
1768 (eq (char-after (- (point) 2)) ?\\ )
1769 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771 (looking-at py-continued-re))))
1772
1773;; t iff current line is a continuation line
1774(defun py-continuation-line-p ()
1775 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001776 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001777 (or (py-backslash-continuation-line-p)
1778 (py-nesting-level))))
1779
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780;; go to initial line of current statement; usually this is the line
1781;; we're on, but if we're on the 2nd or following lines of a
1782;; continuation block, we need to go up to the first line of the
1783;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001784;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001785;; Tricky: We want to avoid quadratic-time behavior for long continued
1786;; blocks, whether of the backslash or open-bracket varieties, or a
1787;; mix of the two. The following manages to do that in the usual
1788;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001789(defun py-goto-initial-line ()
1790 (let ( open-bracket-pos )
1791 (while (py-continuation-line-p)
1792 (beginning-of-line)
1793 (if (py-backslash-continuation-line-p)
1794 (while (py-backslash-continuation-line-p)
1795 (forward-line -1))
1796 ;; else zip out of nested brackets/braces/parens
1797 (while (setq open-bracket-pos (py-nesting-level))
1798 (goto-char open-bracket-pos)))))
1799 (beginning-of-line))
1800
1801;; go to point right beyond final line of current statement; usually
1802;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001803;; statement we need to skip over the continuation lines. Tricky:
1804;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805(defun py-goto-beyond-final-line ()
1806 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001808 (while (and (py-continuation-line-p)
1809 (not (eobp)))
1810 ;; skip over the backslash flavor
1811 (while (and (py-backslash-continuation-line-p)
1812 (not (eobp)))
1813 (forward-line 1))
1814 ;; if in nest, zip to the end of the nest
1815 (setq state (py-parse-state))
1816 (if (and (not (zerop (car state)))
1817 (not (eobp)))
1818 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001819 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820 ;; the 3rd argument should be plain 0
1821 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1822 nil state)
1823 (forward-line 1))))))
1824
1825;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001826;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827(defun py-statement-opens-block-p ()
1828 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001829 (let ((start (point))
1830 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1831 (searching t)
1832 (answer nil)
1833 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834 (goto-char start)
1835 (while searching
1836 ;; look for a colon with nothing after it except whitespace, and
1837 ;; maybe a comment
1838 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1839 finish t)
1840 (if (eq (point) finish) ; note: no `else' clause; just
1841 ; keep searching if we're not at
1842 ; the end yet
1843 ;; sure looks like it opens a block -- but it might
1844 ;; be in a comment
1845 (progn
1846 (setq searching nil) ; search is done either way
1847 (setq state (parse-partial-sexp start
1848 (match-beginning 0)))
1849 (setq answer (not (nth 4 state)))))
1850 ;; search failed: couldn't find another interesting colon
1851 (setq searching nil)))
1852 answer)))
1853
1854;; go to point right beyond final line of block begun by the current
1855;; line. This is the same as where py-goto-beyond-final-line goes
1856;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858(defun py-goto-beyond-block ()
1859 (if (py-statement-opens-block-p)
1860 (py-mark-block nil 'just-move)
1861 (py-goto-beyond-final-line)))
1862
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863;; go to start of first statement (not blank or comment or
1864;; continuation line) at or preceding point. returns t if there is
1865;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866(defun py-goto-statement-at-or-above ()
1867 (py-goto-initial-line)
1868 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869 ;; skip back over blank & comment lines
1870 ;; note: will skip a blank or comment line that happens to be
1871 ;; a continuation line too
1872 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1873 (progn (py-goto-initial-line) t)
1874 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001875 t))
1876
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877;; go to start of first statement (not blank or comment or
1878;; continuation line) following the statement containing point returns
1879;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880(defun py-goto-statement-below ()
1881 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001882 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883 (py-goto-beyond-final-line)
1884 (while (and
1885 (looking-at py-blank-or-comment-re)
1886 (not (eobp)))
1887 (forward-line 1))
1888 (if (eobp)
1889 (progn (goto-char start) nil)
1890 t)))
1891
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892;; go to start of statement, at or preceding point, starting with
1893;; keyword KEY. Skips blank lines and non-indenting comments upward
1894;; first. If that statement starts with KEY, done, else go back to
1895;; first enclosing block starting with KEY. If successful, leaves
1896;; point at the start of the KEY line & returns t. Else leaves point
1897;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001898(defun py-go-up-tree-to-keyword (key)
1899 ;; skip blanks and non-indenting #
1900 (py-goto-initial-line)
1901 (while (and
1902 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1903 (zerop (forward-line -1))) ; go back
1904 nil)
1905 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001906 (let* ((re (concat "[ \t]*" key "\\b"))
1907 (case-fold-search nil) ; let* so looking-at sees this
1908 (found (looking-at re))
1909 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001910 (while (not (or found dead))
1911 (condition-case nil ; in case no enclosing block
1912 (py-goto-block-up 'no-mark)
1913 (error (setq dead t)))
1914 (or dead (setq found (looking-at re))))
1915 (beginning-of-line)
1916 found))
1917
1918;; return string in buffer from start of indentation to end of line;
1919;; prefix "..." if leading whitespace was skipped
1920(defun py-suck-up-leading-text ()
1921 (save-excursion
1922 (back-to-indentation)
1923 (concat
1924 (if (bolp) "" "...")
1925 (buffer-substring (point) (progn (end-of-line) (point))))))
1926
1927;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1928;; as a Lisp symbol; return nil if none
1929(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001931 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1932 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1933 nil)))
1934
1935(defun py-make-temp-name ()
1936 (make-temp-name
1937 (concat (file-name-as-directory py-temp-directory) "python")))
1938
1939(defun py-delete-file-silently (fname)
1940 (condition-case nil
1941 (delete-file fname)
1942 (error nil)))
1943
1944(defun py-kill-emacs-hook ()
1945 ;; delete our temp files
1946 (while py-file-queue
1947 (py-delete-file-silently (car py-file-queue))
1948 (setq py-file-queue (cdr py-file-queue)))
1949 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1950 ;; run the hook we inherited, if any
1951 (and py-inherited-kill-emacs-hook
1952 (funcall py-inherited-kill-emacs-hook))))
1953
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001954;; make PROCESS's buffer visible, append STRING to it, and force
1955;; display; also make shell-mode believe the user typed this string,
1956;; so that kill-output-from-shell and show-output-from-shell work
1957;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001959 (let ((cbuf (current-buffer))
1960 (pbuf (process-buffer process))
1961 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001962 (set-buffer pbuf)
1963 (goto-char (point-max))
1964 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001965 (if (not (or py-this-is-emacs-19-p
1966 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001967 (move-marker last-input-start (point))) ; muck w/ shell-mode
1968 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001969 (if (not (or py-this-is-emacs-19-p
1970 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971 (move-marker last-input-end (point))) ; muck w/ shell-mode
1972 (set-buffer cbuf))
1973 (sit-for 0))
1974
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001975(defun py-keep-region-active ()
1976 ;; do whatever is necessary to keep the region active in XEmacs.
1977 ;; Ignore byte-compiler warnings you might see. Also note that
1978 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1979 ;; require us to take explicit action.
1980 (and (boundp 'zmacs-region-stays)
1981 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001982
1983
Barry Warsaw850437a1995-03-08 21:50:28 +00001984(defconst py-version "$Revision$"
1985 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001986(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001987 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001988
Barry Warsaw850437a1995-03-08 21:50:28 +00001989(defun py-version ()
1990 "Echo the current version of `python-mode' in the minibuffer."
1991 (interactive)
1992 (message "Using `python-mode' version %s" py-version)
1993 (py-keep-region-active))
1994
1995;; only works under Emacs 19
1996;(eval-when-compile
1997; (require 'reporter))
1998
1999(defun py-submit-bug-report (enhancement-p)
2000 "Submit via mail a bug report on `python-mode'.
2001With \\[universal-argument] just submit an enhancement request."
2002 (interactive
2003 (list (not (y-or-n-p
2004 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002005 (let ((reporter-prompt-for-summary-p (if enhancement-p
2006 "(Very) brief summary: "
2007 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002008 (require 'reporter)
2009 (reporter-submit-bug-report
2010 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002011 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002012 ;; varlist
2013 (if enhancement-p nil
2014 '(py-python-command
2015 py-indent-offset
2016 py-block-comment-prefix
2017 py-scroll-process-buffer
2018 py-temp-directory
2019 py-beep-if-tab-change))
2020 nil ;pre-hooks
2021 nil ;post-hooks
2022 "Dear Barry,") ;salutation
2023 (if enhancement-p nil
2024 (set-mark (point))
2025 (insert
2026"Please replace this text with a sufficiently large code sample\n\
2027and an exact recipe so that I can reproduce your problem. Failure\n\
2028to do so may mean a greater delay in fixing your bug.\n\n")
2029 (exchange-point-and-mark)
2030 (py-keep-region-active))))
2031
2032
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002033;; arrange to kill temp files when Emacs exists
2034(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2035 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2036 ;; have to trust that other people are as respectful of our hook
2037 ;; fiddling as we are of theirs
2038 (if (boundp 'py-inherited-kill-emacs-hook)
2039 ;; we were loaded before -- trust others not to have screwed us
2040 ;; in the meantime (no choice, really)
2041 nil
2042 ;; else arrange for our hook to run theirs
2043 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2044 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2045
2046
2047
2048(provide 'python-mode)
2049;;; python-mode.el ends here