blob: e2659c013e9345df727f83dd08af0be5ef82f050 [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
Barry Warsaw17914f41995-11-03 18:25:15 +000084(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000085 "*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
Barry Warsaw095e9c61995-09-19 20:01:42 +000089(defvar py-align-multiline-strings-p t
90 "*Flag describing how multiline triple quoted strings are aligned.
91When this flag is non-nil, continuation lines are lined up under the
92preceding line's indentation. When this flag is nil, continuation
93lines are aligned to column zero.")
94
Barry Warsaw7ae77681994-12-12 20:38:05 +000095(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +000096 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000097This should follow the convention for non-indenting comment lines so
98that the indentation commands won't get confused (i.e., the string
99should be of the form `#x...' where `x' is not a blank or a tab, and
100`...' is arbitrary).")
101
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000102(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000103 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000104
Barry Warsaw6d627751996-03-06 18:41:38 +0000105When nil, all comment lines are skipped for indentation purposes, and
106in Emacs 19, a faster algorithm is used.
107
108When t, lines that begin with a single `#' are a hint to subsequent
109line indentation. If the previous line is such a comment line (as
110opposed to one that starts with `py-block-comment-prefix'), then it's
111indentation is used as a hint for this line's indentation. Lines that
112begin with `py-block-comment-prefix' are ignored for indentation
113purposes.
114
115When not nil or t, comment lines that begin with a `#' are used as
116indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000117
Barry Warsaw7ae77681994-12-12 20:38:05 +0000118(defvar py-scroll-process-buffer t
119 "*Scroll Python process buffer as output arrives.
120If nil, the Python process buffer acts, with respect to scrolling, like
121Shell-mode buffers normally act. This is surprisingly complicated and
122so won't be explained here; in fact, you can't get the whole story
123without studying the Emacs C code.
124
125If non-nil, the behavior is different in two respects (which are
126slightly inaccurate in the interest of brevity):
127
128 - If the buffer is in a window, and you left point at its end, the
129 window will scroll as new output arrives, and point will move to the
130 buffer's end, even if the window is not the selected window (that
131 being the one the cursor is in). The usual behavior for shell-mode
132 windows is not to scroll, and to leave point where it was, if the
133 buffer is in a window other than the selected window.
134
135 - If the buffer is not visible in any window, and you left point at
136 its end, the buffer will be popped into a window as soon as more
137 output arrives. This is handy if you have a long-running
138 computation and don't want to tie up screen area waiting for the
139 output. The usual behavior for a shell-mode buffer is to stay
140 invisible until you explicitly visit it.
141
142Note the `and if you left point at its end' clauses in both of the
143above: you can `turn off' the special behaviors while output is in
144progress, by visiting the Python buffer and moving point to anywhere
145besides the end. Then the buffer won't scroll, point will remain where
146you leave it, and if you hide the buffer it will stay hidden until you
147visit it again. You can enable and disable the special behaviors as
148often as you like, while output is in progress, by (respectively) moving
149point to, or away from, the end of the buffer.
150
151Warning: If you expect a large amount of output, you'll probably be
152happier setting this option to nil.
153
154Obscure: `End of buffer' above should really say `at or beyond the
155process mark', but if you know what that means you didn't need to be
156told <grin>.")
157
158(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000159 (let ((ok '(lambda (x)
160 (and x
161 (setq x (expand-file-name x)) ; always true
162 (file-directory-p x)
163 (file-writable-p x)
164 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000165 (or (funcall ok (getenv "TMPDIR"))
166 (funcall ok "/usr/tmp")
167 (funcall ok "/tmp")
168 (funcall ok ".")
169 (error
170 "Couldn't find a usable temp directory -- set py-temp-directory")))
171 "*Directory used for temp files created by a *Python* process.
172By default, the first directory from this list that exists and that you
173can write into: the value (if any) of the environment variable TMPDIR,
174/usr/tmp, /tmp, or the current directory.")
175
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000176(defvar py-beep-if-tab-change t
177 "*Ring the bell if tab-width is changed.
178If a comment of the form
179
180 \t# vi:set tabsize=<number>:
181
182is found before the first code line when the file is entered, and the
183current value of (the general Emacs variable) `tab-width' does not
184equal <number>, `tab-width' is set to <number>, a message saying so is
185displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
186the Emacs bell is also rung as a warning.")
187
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000188(defconst python-font-lock-keywords
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000189 (let* ((keywords '("access" "and" "break" "continue"
190 "del" "elif" "else:" "except"
191 "except:" "exec" "finally:" "for"
192 "from" "global" "if" "import"
193 "in" "is" "lambda" "not"
194 "or" "pass" "print" "raise"
195 "return" "try:" "while"
196 ))
197 (kwregex (mapconcat 'identity keywords "\\|")))
198 (list
199 ;; keywords not at beginning of line
200 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
201 ;; keywords at beginning of line. i don't think regexps are
202 ;; powerful enough to handle these two cases in one regexp.
203 ;; prove me wrong!
204 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
205 ;; classes
206 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
207 1 font-lock-type-face)
208 ;; functions
209 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
210 1 font-lock-function-name-face)
211 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000212 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000213
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000214
215;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
216;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
217
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000218(make-variable-buffer-local 'py-indent-offset)
219
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000220;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
221;; seems to be the standard way of checking this.
222;; BAW - This is *not* the right solution. When at all possible,
223;; instead of testing for the version of Emacs, use feature tests.
224
225(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
226(setq py-this-is-emacs-19-p
227 (and
228 (not py-this-is-lucid-emacs-p)
229 (string-match "^19\\." emacs-version)))
230
Barry Warsaw7ae77681994-12-12 20:38:05 +0000231;; have to bind py-file-queue before installing the kill-emacs hook
232(defvar py-file-queue nil
233 "Queue of Python temp files awaiting execution.
234Currently-active file is at the head of the list.")
235
236;; define a mode-specific abbrev table for those who use such things
237(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000238 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000239(define-abbrev-table 'python-mode-abbrev-table nil)
240
Barry Warsaw7ae77681994-12-12 20:38:05 +0000241(defvar python-mode-hook nil
242 "*Hook called by `python-mode'.")
243
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000244;; in previous version of python-mode.el, the hook was incorrectly
245;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000246(and (fboundp 'make-obsolete-variable)
247 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
248
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000249(defvar py-mode-map ()
250 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251
Barry Warsaw7ae77681994-12-12 20:38:05 +0000252(if py-mode-map
253 ()
254 (setq py-mode-map (make-sparse-keymap))
255
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256 ;; shadow global bindings for newline-and-indent w/ the py- version.
257 ;; BAW - this is extremely bad form, but I'm not going to change it
258 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000259 (mapcar (function (lambda (key)
260 (define-key
261 py-mode-map key 'py-newline-and-indent)))
262 (where-is-internal 'newline-and-indent))
263
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000264 ;; BAW - you could do it this way, but its not considered proper
265 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000266 (mapcar (function
267 (lambda (x)
268 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000269 '((":" . py-electric-colon)
270 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000271 ("\C-c|" . py-execute-region)
272 ("\C-c!" . py-shell)
273 ("\177" . py-delete-char)
274 ("\n" . py-newline-and-indent)
275 ("\C-c:" . py-guess-indent-offset)
276 ("\C-c\t" . py-indent-region)
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000277 ("\C-c\C-l" . py-outdent-left)
278 ("\C-c\C-r" . py-indent-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000279 ("\C-c<" . py-shift-region-left)
280 ("\C-c>" . py-shift-region-right)
281 ("\C-c\C-n" . py-next-statement)
282 ("\C-c\C-p" . py-previous-statement)
283 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000284 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000285 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000286 ("\C-c?" . py-describe-mode)
287 ("\C-c\C-hm" . py-describe-mode)
288 ("\e\C-a" . beginning-of-python-def-or-class)
289 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000290 ( "\e\C-h" . mark-python-def-or-class)))
291 ;; should do all keybindings this way
292 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
293 (define-key py-mode-map "\C-c\C-v" 'py-version)
294 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000295
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000296(defvar py-mode-syntax-table nil
297 "Syntax table used in `python-mode' buffers.")
298
Barry Warsaw7ae77681994-12-12 20:38:05 +0000299(if py-mode-syntax-table
300 ()
301 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000302 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000303 (mapcar (function
304 (lambda (x) (modify-syntax-entry
305 (car x) (cdr x) py-mode-syntax-table)))
306 '(( ?\( . "()" ) ( ?\) . ")(" )
307 ( ?\[ . "(]" ) ( ?\] . ")[" )
308 ( ?\{ . "(}" ) ( ?\} . "){" )
309 ;; fix operator symbols misassigned in the std table
310 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
311 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
312 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
313 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw2bbe49b1995-10-18 14:41:12 +0000314 ( ?\_ . "_" ) ; underscore is legit in symbols, but not words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315 ( ?\' . "\"") ; single quote is string quote
316 ( ?\" . "\"" ) ; double quote is string quote too
317 ( ?\` . "$") ; backquote is open and close paren
318 ( ?\# . "<") ; hash starts comment
319 ( ?\n . ">")))) ; newline ends comment
320
321(defconst py-stringlit-re
322 (concat
323 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
324 "\\|" ; or
325 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000326 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000327
328;; this is tricky because a trailing backslash does not mean
329;; continuation if it's in a comment
330(defconst py-continued-re
331 (concat
332 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
333 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000334 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000335
336(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000337 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000338
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000339(defconst py-outdent-re
340 (concat "\\(" (mapconcat 'identity
341 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000342 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000343 "finally:"
344 "elif\\s +.*:")
345 "\\|")
346 "\\)")
347 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000348
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000349(defconst py-no-outdent-re
350 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000351 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000352 "except\\(\\s +.*\\)?:"
353 "while\\s +.*:"
354 "for\\s +.*:"
355 "if\\s +.*:"
356 "elif\\s +.*:")
357 "\\|")
358 "\\)")
359 "Regexp matching lines to not outdent after.")
360
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000361
362;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000363(defun python-mode ()
364 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000365To submit a problem report, enter `\\[py-submit-bug-report]' from a
366`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
367documentation. To see what version of `python-mode' you are running,
368enter `\\[py-version]'.
369
370This mode knows about Python indentation, tokens, comments and
371continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000372
373COMMANDS
374\\{py-mode-map}
375VARIABLES
376
377py-indent-offset\tindentation increment
378py-block-comment-prefix\tcomment string used by py-comment-region
379py-python-command\tshell command to invoke Python interpreter
380py-scroll-process-buffer\talways scroll Python process buffer
381py-temp-directory\tdirectory used for temp files (if needed)
382py-beep-if-tab-change\tring the bell if tab-width is changed"
383 (interactive)
384 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000385 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000386 (setq major-mode 'python-mode
387 mode-name "Python"
388 local-abbrev-table python-mode-abbrev-table)
389 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000390 ;; Emacs 19 requires this
391 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
392 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000394 (mapcar (function (lambda (x)
395 (make-local-variable (car x))
396 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000397 '((paragraph-separate . "^[ \t]*$")
398 (paragraph-start . "^[ \t]*$")
399 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000400 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000401 (comment-start-skip . "# *")
402 (comment-column . 40)
403 (indent-region-function . py-indent-region)
404 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000405 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000406 ;;
407 ;; not sure where the magic comment has to be; to save time
408 ;; searching for a rarity, we give up if it's not found prior to the
409 ;; first executable statement.
410 ;;
411 ;; BAW - on first glance, this seems like complete hackery. Why was
412 ;; this necessary, and is it still necessary?
413 (let ((case-fold-search nil)
414 (start (point))
415 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000416 (if (re-search-forward
417 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
418 (prog2 (py-next-statement 1) (point) (goto-char 1))
419 t)
420 (progn
421 (setq new-tab-width
422 (string-to-int
423 (buffer-substring (match-beginning 1) (match-end 1))))
424 (if (= tab-width new-tab-width)
425 nil
426 (setq tab-width new-tab-width)
427 (message "Caution: tab-width changed to %d" new-tab-width)
428 (if py-beep-if-tab-change (beep)))))
429 (goto-char start))
430
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000431 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000432 (if python-mode-hook
433 (run-hooks 'python-mode-hook)
434 (run-hooks 'py-mode-hook)))
435
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000436
Barry Warsawb91b7431995-03-14 15:55:20 +0000437;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000438(defun py-outdent-p ()
439 ;; returns non-nil if the current line should outdent one level
440 (save-excursion
441 (and (progn (back-to-indentation)
442 (looking-at py-outdent-re))
443 (progn (backward-to-indentation 1)
444 (while (or (looking-at py-blank-or-comment-re)
445 (bobp))
446 (backward-to-indentation 1))
447 (not (looking-at py-no-outdent-re)))
448 )))
449
450
Barry Warsawb91b7431995-03-14 15:55:20 +0000451(defun py-electric-colon (arg)
452 "Insert a colon.
453In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000454argument is provided, that many colons are inserted non-electrically.
455Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000456 (interactive "P")
457 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000458 ;; are we in a string or comment?
459 (if (save-excursion
460 (let ((pps (parse-partial-sexp (save-excursion
461 (beginning-of-python-def-or-class)
462 (point))
463 (point))))
464 (not (or (nth 3 pps) (nth 4 pps)))))
465 (save-excursion
466 (let ((here (point))
467 (outdent 0)
468 (indent (py-compute-indentation)))
469 (if (and (not arg)
470 (py-outdent-p)
471 (= indent (save-excursion
472 (forward-line -1)
473 (py-compute-indentation)))
474 )
475 (setq outdent py-indent-offset))
476 ;; Don't indent, only outdent. This assumes that any lines that
477 ;; are already outdented relative to py-compute-indentation were
478 ;; put there on purpose. Its highly annoying to have `:' indent
479 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
480 ;; there a better way to determine this???
481 (if (< (current-indentation) indent) nil
482 (goto-char here)
483 (beginning-of-line)
484 (delete-horizontal-space)
485 (indent-to (- indent outdent))
486 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000487
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000488(defun py-indent-right (arg)
489 "Indent the line by one `py-indent-offset' level.
490With numeric arg, indent by that many levels. You cannot indent
491farther right than the distance the line would be indented by
492\\[py-indent-line]."
493 (interactive "p")
494 (let ((col (current-indentation))
495 (want (* arg py-indent-offset))
496 (indent (py-compute-indentation))
497 (pos (- (point-max) (point)))
498 (bol (save-excursion (beginning-of-line) (point))))
499 (if (<= (+ col want) indent)
500 (progn
501 (beginning-of-line)
502 (delete-horizontal-space)
503 (indent-to (+ col want))
504 (if (> (- (point-max) pos) (point))
505 (goto-char (- (point-max) pos)))
506 ))))
507
508(defun py-outdent-left (arg)
509 "Outdent the line by one `py-indent-offset' level.
510With numeric arg, outdent by that many levels. You cannot outdent
511farther left than column zero."
512 (interactive "p")
513 (let ((col (current-indentation))
514 (want (* arg py-indent-offset))
515 (pos (- (point-max) (point)))
516 (bol (save-excursion (beginning-of-line) (point))))
517 (if (<= 0 (- col want))
518 (progn
519 (beginning-of-line)
520 (delete-horizontal-space)
521 (indent-to (- col want))
522 (if (> (- (point-max) pos) (point))
523 (goto-char (- (point-max) pos)))
524 ))))
525
Barry Warsawb91b7431995-03-14 15:55:20 +0000526
Barry Warsaw7ae77681994-12-12 20:38:05 +0000527;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000528(defun py-shell ()
529 "Start an interactive Python interpreter in another window.
530This is like Shell mode, except that Python is running in the window
531instead of a shell. See the `Interactive Shell' and `Shell Mode'
532sections of the Emacs manual for details, especially for the key
533bindings active in the `*Python*' buffer.
534
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000535See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000536behavior in the process window.
537
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000538Warning: Don't use an interactive Python if you change sys.ps1 or
539sys.ps2 from their default values, or if you're running code that
540prints `>>> ' or `... ' at the start of a line. `python-mode' can't
541distinguish your output from Python's output, and assumes that `>>> '
542at the start of a line is a prompt from Python. Similarly, the Emacs
543Shell mode code assumes that both `>>> ' and `... ' at the start of a
544line are Python prompts. Bad things can happen if you fool either
545mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000546
547Warning: If you do any editing *in* the process buffer *while* the
548buffer is accepting output from Python, do NOT attempt to `undo' the
549changes. Some of the output (nowhere near the parts you changed!) may
550be lost if you do. This appears to be an Emacs bug, an unfortunate
551interaction between undo and process filters; the same problem exists in
552non-Python process buffers using the default (Emacs-supplied) process
553filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000554 ;; BAW - should undo be disabled in the python process buffer, if
555 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (interactive)
557 (if py-this-is-emacs-19-p
558 (progn
559 (require 'comint)
560 (switch-to-buffer-other-window
561 (make-comint "Python" py-python-command)))
562 (progn
563 (require 'shell)
564 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000565 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000566 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000567 (make-local-variable 'shell-prompt-pattern)
568 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
569 (set-process-filter (get-buffer-process (current-buffer))
570 'py-process-filter)
571 (set-syntax-table py-mode-syntax-table))
572
573(defun py-execute-region (start end)
574 "Send the region between START and END to a Python interpreter.
575If there is a *Python* process it is used.
576
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000577Hint: If you want to execute part of a Python file several times
578\(e.g., perhaps you're developing a function and want to flesh it out
579a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
580the region of interest, and send the code to a *Python* process via
581`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000582
583Following are subtleties to note when using a *Python* process:
584
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000585If a *Python* process is used, the region is copied into a temporary
586file (in directory `py-temp-directory'), and an `execfile' command is
587sent to Python naming that file. If you send regions faster than
588Python can execute them, `python-mode' will save them into distinct
589temp files, and execute the next one in the queue the next time it
590sees a `>>> ' prompt from Python. Each time this happens, the process
591buffer is popped into a window (if it's not already in some window) so
592you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000593
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000594 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000595
596is inserted at the end.
597
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000598Caution: No more than 26 regions can be pending at any given time.
599This limit is (indirectly) inherited from libc's mktemp(3).
600`python-mode' does not try to protect you from exceeding the limit.
601It's extremely unlikely that you'll get anywhere close to the limit in
602practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000603
604See the `\\[py-shell]' docs for additional warnings."
605 (interactive "r")
606 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000607 (let ((pyproc (get-process "Python"))
608 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000609 (if (null pyproc)
610 (shell-command-on-region start end py-python-command)
611 ;; else feed it thru a temp file
612 (setq fname (py-make-temp-name))
613 (write-region start end fname nil 'no-msg)
614 (setq py-file-queue (append py-file-queue (list fname)))
615 (if (cdr py-file-queue)
616 (message "File %s queued for execution" fname)
617 ;; else
618 (py-execute-file pyproc fname)))))
619
620(defun py-execute-file (pyproc fname)
621 (py-append-to-process-buffer
622 pyproc
623 (format "## working on region in file %s ...\n" fname))
624 (process-send-string pyproc (format "execfile('%s')\n" fname)))
625
626(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000627 (let ((curbuf (current-buffer))
628 (pbuf (process-buffer pyproc))
629 (pmark (process-mark pyproc))
630 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000631
632 ;; make sure we switch to a different buffer at least once. if we
633 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000634 ;; window, and point is before the end, and lots of output is
635 ;; coming at a fast pace, then (a) simple cursor-movement commands
636 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
637 ;; to have a visible effect (the window just doesn't get updated,
638 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
639 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000640 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000641 ;; #b makes no sense to me at all. #a almost makes sense: unless
642 ;; we actually change buffers, set_buffer_internal in buffer.c
643 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
644 ;; seems to make the Emacs command loop reluctant to update the
645 ;; display. Perhaps the default process filter in process.c's
646 ;; read_process_output has update_mode_lines++ for a similar
647 ;; reason? beats me ...
648
649 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000650 (if (eq curbuf pbuf) ; mysterious ugly hack
651 (set-buffer (get-buffer-create "*scratch*")))
652
653 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000654 (let* ((start (point))
655 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000656 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000657 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000658 (goto-char pmark)
659 (insert string)
660 (move-marker pmark (point))
661 (setq file-finished
662 (and py-file-queue
663 (equal ">>> "
664 (buffer-substring
665 (prog2 (beginning-of-line) (point)
666 (goto-char pmark))
667 (point)))))
668 (if goback (goto-char start)
669 ;; else
670 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000671 (let* ((pop-up-windows t)
672 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000673 (set-window-point pwin (point)))))
674 (set-buffer curbuf)
675 (if file-finished
676 (progn
677 (py-delete-file-silently (car py-file-queue))
678 (setq py-file-queue (cdr py-file-queue))
679 (if py-file-queue
680 (py-execute-file pyproc (car py-file-queue)))))
681 (and goend
682 (progn (set-buffer pbuf)
683 (goto-char (point-max))))
684 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000685
686(defun py-execute-buffer ()
687 "Send the contents of the buffer to a Python interpreter.
688If there is a *Python* process buffer it is used. If a clipping
689restriction is in effect, only the accessible portion of the buffer is
690sent. A trailing newline will be supplied if needed.
691
692See the `\\[py-execute-region]' docs for an account of some subtleties."
693 (interactive)
694 (py-execute-region (point-min) (point-max)))
695
696
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000697
698;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000699(defun py-delete-char ()
700 "Reduce indentation or delete character.
701If point is at the leftmost column, deletes the preceding newline.
702
703Else if point is at the leftmost non-blank character of a line that is
704neither a continuation line nor a non-indenting comment line, or if
705point is at the end of a blank line, reduces the indentation to match
706that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000707opened the block is displayed in the echo area to help you keep track
708of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000709
710Else the preceding character is deleted, converting a tab to spaces if
711needed so that only a single column position is deleted."
712 (interactive "*")
713 (if (or (/= (current-indentation) (current-column))
714 (bolp)
715 (py-continuation-line-p)
716 (looking-at "#[^ \t\n]")) ; non-indenting #
717 (backward-delete-char-untabify 1)
718 ;; else indent the same as the colon line that opened the block
719
720 ;; force non-blank so py-goto-block-up doesn't ignore it
721 (insert-char ?* 1)
722 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000723 (let ((base-indent 0) ; indentation of base line
724 (base-text "") ; and text of base line
725 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000726 (condition-case nil ; in case no enclosing block
727 (save-excursion
728 (py-goto-block-up 'no-mark)
729 (setq base-indent (current-indentation)
730 base-text (py-suck-up-leading-text)
731 base-found-p t))
732 (error nil))
733 (delete-char 1) ; toss the dummy character
734 (delete-horizontal-space)
735 (indent-to base-indent)
736 (if base-found-p
737 (message "Closes block: %s" base-text)))))
738
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000739;; required for pending-del and delsel modes
740(put 'py-delete-char 'delete-selection 'supersede)
741(put 'py-delete-char 'pending-delete 'supersede)
742
Barry Warsaw7ae77681994-12-12 20:38:05 +0000743(defun py-indent-line ()
744 "Fix the indentation of the current line according to Python rules."
745 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000746 (let* ((ci (current-indentation))
747 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000748 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000749 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000750 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000751 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000752 (if (/= ci need)
753 (save-excursion
754 (beginning-of-line)
755 (delete-horizontal-space)
756 (indent-to need)))
757 (if move-to-indentation-p (back-to-indentation))))
758
759(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000760 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000761This is just `strives to' because correct indentation can't be computed
762from scratch for Python code. In general, deletes the whitespace before
763point, inserts a newline, and takes an educated guess as to how you want
764the new line indented."
765 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000766 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000767 (if (< ci (current-column)) ; if point beyond indentation
768 (newline-and-indent)
769 ;; else try to act like newline-and-indent "normally" acts
770 (beginning-of-line)
771 (insert-char ?\n 1)
772 (move-to-column ci))))
773
774(defun py-compute-indentation ()
775 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000776 (let ((pps (parse-partial-sexp (save-excursion
777 (beginning-of-python-def-or-class)
778 (point))
779 (point))))
780 (beginning-of-line)
781 (cond
782 ;; are we inside a string or comment?
783 ((or (nth 3 pps) (nth 4 pps))
784 (save-excursion
785 (if (not py-align-multiline-strings-p) 0
786 ;; skip back over blank & non-indenting comment lines
787 ;; note: will skip a blank or non-indenting comment line
788 ;; that happens to be a continuation line too
789 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
790 (back-to-indentation)
791 (current-column))))
792 ;; are we on a continuation line?
793 ((py-continuation-line-p)
794 (let ((startpos (point))
795 (open-bracket-pos (py-nesting-level))
796 endpos searching found)
797 (if open-bracket-pos
798 (progn
799 ;; align with first item in list; else a normal
800 ;; indent beyond the line with the open bracket
801 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
802 ;; is the first list item on the same line?
803 (skip-chars-forward " \t")
804 (if (null (memq (following-char) '(?\n ?# ?\\)))
805 ; yes, so line up with it
806 (current-column)
807 ;; first list item on another line, or doesn't exist yet
808 (forward-line 1)
809 (while (and (< (point) startpos)
810 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
811 (forward-line 1))
812 (if (< (point) startpos)
813 ;; again mimic the first list item
814 (current-indentation)
815 ;; else they're about to enter the first item
816 (goto-char open-bracket-pos)
817 (+ (current-indentation) py-indent-offset))))
818
819 ;; else on backslash continuation line
820 (forward-line -1)
821 (if (py-continuation-line-p) ; on at least 3rd line in block
822 (current-indentation) ; so just continue the pattern
823 ;; else started on 2nd line in block, so indent more.
824 ;; if base line is an assignment with a start on a RHS,
825 ;; indent to 2 beyond the leftmost "="; else skip first
826 ;; chunk of non-whitespace characters on base line, + 1 more
827 ;; column
828 (end-of-line)
829 (setq endpos (point) searching t)
830 (back-to-indentation)
831 (setq startpos (point))
832 ;; look at all "=" from left to right, stopping at first
833 ;; one not nested in a list or string
834 (while searching
835 (skip-chars-forward "^=" endpos)
836 (if (= (point) endpos)
837 (setq searching nil)
838 (forward-char 1)
839 (setq state (parse-partial-sexp startpos (point)))
840 (if (and (zerop (car state)) ; not in a bracket
841 (null (nth 3 state))) ; & not in a string
842 (progn
843 (setq searching nil) ; done searching in any case
844 (setq found
845 (not (or
846 (eq (following-char) ?=)
847 (memq (char-after (- (point) 2))
848 '(?< ?> ?!)))))))))
849 (if (or (not found) ; not an assignment
850 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
851 (progn
852 (goto-char startpos)
853 (skip-chars-forward "^ \t\n")))
854 (1+ (current-column))))))
855
856 ;; not on a continuation line
857
858 ;; if at start of restriction, or on a non-indenting comment
859 ;; line, assume they intended whatever's there
860 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
861 (current-indentation))
862
863 ;; else indentation based on that of the statement that
864 ;; precedes us; use the first line of that statement to
865 ;; establish the base, in case the user forced a non-std
866 ;; indentation for the continuation lines (if any)
867 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000868 ;; skip back over blank & non-indenting comment lines note:
869 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000870 ;; happens to be a continuation line too. use fast Emacs 19
871 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000872 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000873 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000874 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000875 (let (done)
876 (while (not done)
877 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
878 nil 'move)
879 (setq done (or (eq py-honor-comment-indentation t)
880 (bobp)
881 (/= (following-char) ?#)
882 (not (zerop (current-column)))))
883 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000884 ;; if we landed inside a string, go to the beginning of that
885 ;; string. this handles triple quoted, multi-line spanning
886 ;; strings.
887 (py-goto-initial-line)
888 (if (py-statement-opens-block-p)
889 (+ (current-indentation) py-indent-offset)
890 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000891
892(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000893 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000894By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000895`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898their own buffer-local copy), both those currently existing and those
899created later in the Emacs session.
900
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000901Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000902There's no excuse for such foolishness, but sometimes you have to deal
903with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904`py-indent-offset' to what it thinks it was when they created the
905mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906
907Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908looking for a line that opens a block of code. `py-indent-offset' is
909set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000910statement following it. If the search doesn't succeed going forward,
911it's tried again going backward."
912 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000913 (let (new-value
914 (start (point))
915 restart
916 (found nil)
917 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918 (py-goto-initial-line)
919 (while (not (or found (eobp)))
920 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
921 (progn
922 (setq restart (point))
923 (py-goto-initial-line)
924 (if (py-statement-opens-block-p)
925 (setq found t)
926 (goto-char restart)))))
927 (if found
928 ()
929 (goto-char start)
930 (py-goto-initial-line)
931 (while (not (or found (bobp)))
932 (setq found
933 (and
934 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
935 (or (py-goto-initial-line) t) ; always true -- side effect
936 (py-statement-opens-block-p)))))
937 (setq colon-indent (current-indentation)
938 found (and found (zerop (py-next-statement 1)))
939 new-value (- (current-indentation) colon-indent))
940 (goto-char start)
941 (if found
942 (progn
943 (funcall (if global 'kill-local-variable 'make-local-variable)
944 'py-indent-offset)
945 (setq py-indent-offset new-value)
946 (message "%s value of py-indent-offset set to %d"
947 (if global "Global" "Local")
948 py-indent-offset))
949 (error "Sorry, couldn't guess a value for py-indent-offset"))))
950
951(defun py-shift-region (start end count)
952 (save-excursion
953 (goto-char end) (beginning-of-line) (setq end (point))
954 (goto-char start) (beginning-of-line) (setq start (point))
955 (indent-rigidly start end count)))
956
957(defun py-shift-region-left (start end &optional count)
958 "Shift region of Python code to the left.
959The lines from the line containing the start of the current region up
960to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000961shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000962
963If a prefix argument is given, the region is instead shifted by that
964many columns."
965 (interactive "*r\nP") ; region; raw prefix arg
966 (py-shift-region start end
967 (- (prefix-numeric-value
968 (or count py-indent-offset)))))
969
970(defun py-shift-region-right (start end &optional count)
971 "Shift region of Python code to the right.
972The lines from the line containing the start of the current region up
973to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000974shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000975
976If a prefix argument is given, the region is instead shifted by that
977many columns."
978 (interactive "*r\nP") ; region; raw prefix arg
979 (py-shift-region start end (prefix-numeric-value
980 (or count py-indent-offset))))
981
982(defun py-indent-region (start end &optional indent-offset)
983 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000984
Barry Warsaw7ae77681994-12-12 20:38:05 +0000985The lines from the line containing the start of the current region up
986to (but not including) the line containing the end of the region are
987reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000988character in the first column, the first line is left alone and the
989rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +0000990region is reindented with respect to the (closest code or indenting
991comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992
993This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994control structures are introduced or removed, or to reformat code
995using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996
997If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000998the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999used.
1000
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001001Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002is called! This function does not compute proper indentation from
1003scratch (that's impossible in Python), it merely adjusts the existing
1004indentation to be correct in context.
1005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001006Warning: This function really has no idea what to do with
1007non-indenting comment lines, and shifts them as if they were indenting
1008comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001009
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001010Special cases: whitespace is deleted from blank lines; continuation
1011lines are shifted by the same amount their initial line was shifted,
1012in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001014 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001015 (save-excursion
1016 (goto-char end) (beginning-of-line) (setq end (point-marker))
1017 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001018 (let ((py-indent-offset (prefix-numeric-value
1019 (or indent-offset py-indent-offset)))
1020 (indents '(-1)) ; stack of active indent levels
1021 (target-column 0) ; column to which to indent
1022 (base-shifted-by 0) ; amount last base line was shifted
1023 (indent-base (if (looking-at "[ \t\n]")
1024 (py-compute-indentation)
1025 0))
1026 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027 (while (< (point) end)
1028 (setq ci (current-indentation))
1029 ;; figure out appropriate target column
1030 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001031 ((or (eq (following-char) ?#) ; comment in column 1
1032 (looking-at "[ \t]*$")) ; entirely blank
1033 (setq target-column 0))
1034 ((py-continuation-line-p) ; shift relative to base line
1035 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001036 (t ; new base line
1037 (if (> ci (car indents)) ; going deeper; push it
1038 (setq indents (cons ci indents))
1039 ;; else we should have seen this indent before
1040 (setq indents (memq ci indents)) ; pop deeper indents
1041 (if (null indents)
1042 (error "Bad indentation in region, at line %d"
1043 (save-restriction
1044 (widen)
1045 (1+ (count-lines 1 (point)))))))
1046 (setq target-column (+ indent-base
1047 (* py-indent-offset
1048 (- (length indents) 2))))
1049 (setq base-shifted-by (- target-column ci))))
1050 ;; shift as needed
1051 (if (/= ci target-column)
1052 (progn
1053 (delete-horizontal-space)
1054 (indent-to target-column)))
1055 (forward-line 1))))
1056 (set-marker end nil))
1057
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001058
1059;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001060(defun py-previous-statement (count)
1061 "Go to the start of previous Python statement.
1062If the statement at point is the i'th Python statement, goes to the
1063start of statement i-COUNT. If there is no such statement, goes to the
1064first statement. Returns count of statements left to move.
1065`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001066 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001067 (if (< count 0) (py-next-statement (- count))
1068 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001071 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001072 (> count 0)
1073 (zerop (forward-line -1))
1074 (py-goto-statement-at-or-above))
1075 (setq count (1- count)))
1076 (if (> count 0) (goto-char start)))
1077 count))
1078
1079(defun py-next-statement (count)
1080 "Go to the start of next Python statement.
1081If the statement at point is the i'th Python statement, goes to the
1082start of statement i+COUNT. If there is no such statement, goes to the
1083last statement. Returns count of statements left to move. `Statements'
1084do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001086 (if (< count 0) (py-previous-statement (- count))
1087 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001088 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001089 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001090 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001091 (> count 0)
1092 (py-goto-statement-below))
1093 (setq count (1- count)))
1094 (if (> count 0) (goto-char start)))
1095 count))
1096
1097(defun py-goto-block-up (&optional nomark)
1098 "Move up to start of current block.
1099Go to the statement that starts the smallest enclosing block; roughly
1100speaking, this will be the closest preceding statement that ends with a
1101colon and is indented less than the statement you started on. If
1102successful, also sets the mark to the starting point.
1103
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001104`\\[py-mark-block]' can be used afterward to mark the whole code
1105block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001106
1107If called from a program, the mark will not be set if optional argument
1108NOMARK is not nil."
1109 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001110 (let ((start (point))
1111 (found nil)
1112 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001113 (py-goto-initial-line)
1114 ;; if on blank or non-indenting comment line, use the preceding stmt
1115 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1116 (progn
1117 (py-goto-statement-at-or-above)
1118 (setq found (py-statement-opens-block-p))))
1119 ;; search back for colon line indented less
1120 (setq initial-indent (current-indentation))
1121 (if (zerop initial-indent)
1122 ;; force fast exit
1123 (goto-char (point-min)))
1124 (while (not (or found (bobp)))
1125 (setq found
1126 (and
1127 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1128 (or (py-goto-initial-line) t) ; always true -- side effect
1129 (< (current-indentation) initial-indent)
1130 (py-statement-opens-block-p))))
1131 (if found
1132 (progn
1133 (or nomark (push-mark start))
1134 (back-to-indentation))
1135 (goto-char start)
1136 (error "Enclosing block not found"))))
1137
1138(defun beginning-of-python-def-or-class (&optional class)
1139 "Move point to start of def (or class, with prefix arg).
1140
1141Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001142arg, looks for a `class' instead. The docs assume the `def' case;
1143just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001144
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001145If point is in a def statement already, and after the `d', simply
1146moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001147
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148Else (point is not in a def statement, or at or before the `d' of a
1149def statement), searches for the closest preceding def statement, and
1150leaves point at its start. If no such statement can be found, leaves
1151point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001152
1153Returns t iff a def statement is found by these rules.
1154
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001155Note that doing this command repeatedly will take you closer to the
1156start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001158If you want to mark the current def/class, see
1159`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001160 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1162 (start-of-line (progn (beginning-of-line) (point)))
1163 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001164 (if (or (/= start-of-stmt start-of-line)
1165 (not at-or-before-p))
1166 (end-of-line)) ; OK to match on this line
1167 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001168 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169
1170(defun end-of-python-def-or-class (&optional class)
1171 "Move point beyond end of def (or class, with prefix arg) body.
1172
1173By default, looks for an appropriate `def'. If you supply a prefix arg,
1174looks for a `class' instead. The docs assume the `def' case; just
1175substitute `class' for `def' for the other case.
1176
1177If point is in a def statement already, this is the def we use.
1178
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001179Else if the def found by `\\[beginning-of-python-def-or-class]'
1180contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001181
1182Else we search forward for the closest following def, and use that.
1183
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001184If a def can be found by these rules, point is moved to the start of
1185the line immediately following the def block, and the position of the
1186start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001187
1188Else point is moved to the end of the buffer, and nil is returned.
1189
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001190Note that doing this command repeatedly will take you closer to the
1191end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193If you want to mark the current def/class, see
1194`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001196 (let ((start (progn (py-goto-initial-line) (point)))
1197 (which (if class "class" "def"))
1198 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001199 ;; move point to start of appropriate def/class
1200 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1201 (setq state 'at-beginning)
1202 ;; else see if beginning-of-python-def-or-class hits container
1203 (if (and (beginning-of-python-def-or-class class)
1204 (progn (py-goto-beyond-block)
1205 (> (point) start)))
1206 (setq state 'at-end)
1207 ;; else search forward
1208 (goto-char start)
1209 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1210 (progn (setq state 'at-beginning)
1211 (beginning-of-line)))))
1212 (cond
1213 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1214 ((eq state 'at-end) t)
1215 ((eq state 'not-found) nil)
1216 (t (error "internal error in end-of-python-def-or-class")))))
1217
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001218
1219;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001220(defun py-mark-block (&optional extend just-move)
1221 "Mark following block of lines. With prefix arg, mark structure.
1222Easier to use than explain. It sets the region to an `interesting'
1223block of succeeding lines. If point is on a blank line, it goes down to
1224the next non-blank line. That will be the start of the region. The end
1225of the region depends on the kind of line at the start:
1226
1227 - If a comment, the region will include all succeeding comment lines up
1228 to (but not including) the next non-comment line (if any).
1229
1230 - Else if a prefix arg is given, and the line begins one of these
1231 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001232
1233 if elif else try except finally for while def class
1234
Barry Warsaw7ae77681994-12-12 20:38:05 +00001235 the region will be set to the body of the structure, including
1236 following blocks that `belong' to it, but excluding trailing blank
1237 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001238 and all (if any) of the following `except' and `finally' blocks
1239 that belong to the `try' structure will be in the region. Ditto
1240 for if/elif/else, for/else and while/else structures, and (a bit
1241 degenerate, since they're always one-block structures) def and
1242 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001243
1244 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001245 block (see list above), and the block is not a `one-liner' (i.e.,
1246 the statement ends with a colon, not with code), the region will
1247 include all succeeding lines up to (but not including) the next
1248 code statement (if any) that's indented no more than the starting
1249 line, except that trailing blank and comment lines are excluded.
1250 E.g., if the starting line begins a multi-statement `def'
1251 structure, the region will be set to the full function definition,
1252 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001253
1254 - Else the region will include all succeeding lines up to (but not
1255 including) the next blank line, or code or indenting-comment line
1256 indented strictly less than the starting line. Trailing indenting
1257 comment lines are included in this case, but not trailing blank
1258 lines.
1259
1260A msg identifying the location of the mark is displayed in the echo
1261area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1262
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001263If called from a program, optional argument EXTEND plays the role of
1264the prefix arg, and if optional argument JUST-MOVE is not nil, just
1265moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001266 (interactive "P") ; raw prefix arg
1267 (py-goto-initial-line)
1268 ;; skip over blank lines
1269 (while (and
1270 (looking-at "[ \t]*$") ; while blank line
1271 (not (eobp))) ; & somewhere to go
1272 (forward-line 1))
1273 (if (eobp)
1274 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001275 (let ((initial-pos (point))
1276 (initial-indent (current-indentation))
1277 last-pos ; position of last stmt in region
1278 (followers
1279 '((if elif else) (elif elif else) (else)
1280 (try except finally) (except except) (finally)
1281 (for else) (while else)
1282 (def) (class) ) )
1283 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001284
1285 (cond
1286 ;; if comment line, suck up the following comment lines
1287 ((looking-at "[ \t]*#")
1288 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1289 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1290 (setq last-pos (point)))
1291
1292 ;; else if line is a block line and EXTEND given, suck up
1293 ;; the whole structure
1294 ((and extend
1295 (setq first-symbol (py-suck-up-first-keyword) )
1296 (assq first-symbol followers))
1297 (while (and
1298 (or (py-goto-beyond-block) t) ; side effect
1299 (forward-line -1) ; side effect
1300 (setq last-pos (point)) ; side effect
1301 (py-goto-statement-below)
1302 (= (current-indentation) initial-indent)
1303 (setq next-symbol (py-suck-up-first-keyword))
1304 (memq next-symbol (cdr (assq first-symbol followers))))
1305 (setq first-symbol next-symbol)))
1306
1307 ;; else if line *opens* a block, search for next stmt indented <=
1308 ((py-statement-opens-block-p)
1309 (while (and
1310 (setq last-pos (point)) ; always true -- side effect
1311 (py-goto-statement-below)
1312 (> (current-indentation) initial-indent))
1313 nil))
1314
1315 ;; else plain code line; stop at next blank line, or stmt or
1316 ;; indenting comment line indented <
1317 (t
1318 (while (and
1319 (setq last-pos (point)) ; always true -- side effect
1320 (or (py-goto-beyond-final-line) t)
1321 (not (looking-at "[ \t]*$")) ; stop at blank line
1322 (or
1323 (>= (current-indentation) initial-indent)
1324 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1325 nil)))
1326
1327 ;; skip to end of last stmt
1328 (goto-char last-pos)
1329 (py-goto-beyond-final-line)
1330
1331 ;; set mark & display
1332 (if just-move
1333 () ; just return
1334 (push-mark (point) 'no-msg)
1335 (forward-line -1)
1336 (message "Mark set after: %s" (py-suck-up-leading-text))
1337 (goto-char initial-pos))))
1338
1339(defun mark-python-def-or-class (&optional class)
1340 "Set region to body of def (or class, with prefix arg) enclosing point.
1341Pushes the current mark, then point, on the mark ring (all language
1342modes do this, but although it's handy it's never documented ...).
1343
1344In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001345hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1346`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001347
1348And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001349Turned out that was more confusing than useful: the `goto start' and
1350`goto end' commands are usually used to search through a file, and
1351people expect them to act a lot like `search backward' and `search
1352forward' string-search commands. But because Python `def' and `class'
1353can nest to arbitrary levels, finding the smallest def containing
1354point cannot be done via a simple backward search: the def containing
1355point may not be the closest preceding def, or even the closest
1356preceding def that's indented less. The fancy algorithm required is
1357appropriate for the usual uses of this `mark' command, but not for the
1358`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001359
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360So the def marked by this command may not be the one either of the
1361`goto' commands find: If point is on a blank or non-indenting comment
1362line, moves back to start of the closest preceding code statement or
1363indenting comment line. If this is a `def' statement, that's the def
1364we use. Else searches for the smallest enclosing `def' block and uses
1365that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001366
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001367When an enclosing def is found: The mark is left immediately beyond
1368the last line of the def block. Point is left at the start of the
1369def, except that: if the def is preceded by a number of comment lines
1370followed by (at most) one optional blank line, point is left at the
1371start of the comments; else if the def is preceded by a blank line,
1372point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
1374The intent is to mark the containing def/class and its associated
1375documentation, to make moving and duplicating functions and classes
1376pleasant."
1377 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001378 (let ((start (point))
1379 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380 (push-mark start)
1381 (if (not (py-go-up-tree-to-keyword which))
1382 (progn (goto-char start)
1383 (error "Enclosing %s not found" which))
1384 ;; else enclosing def/class found
1385 (setq start (point))
1386 (py-goto-beyond-block)
1387 (push-mark (point))
1388 (goto-char start)
1389 (if (zerop (forward-line -1)) ; if there is a preceding line
1390 (progn
1391 (if (looking-at "[ \t]*$") ; it's blank
1392 (setq start (point)) ; so reset start point
1393 (goto-char start)) ; else try again
1394 (if (zerop (forward-line -1))
1395 (if (looking-at "[ \t]*#") ; a comment
1396 ;; look back for non-comment line
1397 ;; tricky: note that the regexp matches a blank
1398 ;; line, cuz \n is in the 2nd character class
1399 (and
1400 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1401 (forward-line 1))
1402 ;; no comment, so go back
1403 (goto-char start))))))))
1404
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001405
1406;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001407
1408;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1410;; out of the right places, along with the keys they're on & current
1411;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001412(defun py-dump-help-string (str)
1413 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001414 (let ((locals (buffer-local-variables))
1415 funckind funcname func funcdoc
1416 (start 0) mstart end
1417 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1419 (setq mstart (match-beginning 0) end (match-end 0)
1420 funckind (substring str (match-beginning 1) (match-end 1))
1421 funcname (substring str (match-beginning 2) (match-end 2))
1422 func (intern funcname))
1423 (princ (substitute-command-keys (substring str start mstart)))
1424 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001425 ((equal funckind "c") ; command
1426 (setq funcdoc (documentation func)
1427 keys (concat
1428 "Key(s): "
1429 (mapconcat 'key-description
1430 (where-is-internal func py-mode-map)
1431 ", "))))
1432 ((equal funckind "v") ; variable
1433 (setq funcdoc (substitute-command-keys
1434 (get func 'variable-documentation))
1435 keys (if (assq func locals)
1436 (concat
1437 "Local/Global values: "
1438 (prin1-to-string (symbol-value func))
1439 " / "
1440 (prin1-to-string (default-value func)))
1441 (concat
1442 "Value: "
1443 (prin1-to-string (symbol-value func))))))
1444 (t ; unexpected
1445 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001446 (princ (format "\n-> %s:\t%s\t%s\n\n"
1447 (if (equal funckind "c") "Command" "Variable")
1448 funcname keys))
1449 (princ funcdoc)
1450 (terpri)
1451 (setq start end))
1452 (princ (substitute-command-keys (substring str start))))
1453 (print-help-return-message)))
1454
1455(defun py-describe-mode ()
1456 "Dump long form of Python-mode docs."
1457 (interactive)
1458 (py-dump-help-string "Major mode for editing Python files.
1459Knows about Python indentation, tokens, comments and continuation lines.
1460Paragraphs are separated by blank lines only.
1461
1462Major sections below begin with the string `@'; specific function and
1463variable docs begin with `->'.
1464
1465@EXECUTING PYTHON CODE
1466
1467\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1468\\[py-execute-region]\tsends the current region
1469\\[py-shell]\tstarts a Python interpreter window; this will be used by
1470\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1471%c:py-execute-buffer
1472%c:py-execute-region
1473%c:py-shell
1474
1475@VARIABLES
1476
1477py-indent-offset\tindentation increment
1478py-block-comment-prefix\tcomment string used by py-comment-region
1479
1480py-python-command\tshell command to invoke Python interpreter
1481py-scroll-process-buffer\talways scroll Python process buffer
1482py-temp-directory\tdirectory used for temp files (if needed)
1483
1484py-beep-if-tab-change\tring the bell if tab-width is changed
1485%v:py-indent-offset
1486%v:py-block-comment-prefix
1487%v:py-python-command
1488%v:py-scroll-process-buffer
1489%v:py-temp-directory
1490%v:py-beep-if-tab-change
1491
1492@KINDS OF LINES
1493
1494Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001495preceding line ends with a backslash that's not part of a comment, or
1496the paren/bracket/brace nesting level at the start of the line is
1497non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001498
1499An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001500possibly blanks or tabs), a `comment line' (leftmost non-blank
1501character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001502
1503Comment Lines
1504
1505Although all comment lines are treated alike by Python, Python mode
1506recognizes two kinds that act differently with respect to indentation.
1507
1508An `indenting comment line' is a comment line with a blank, tab or
1509nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001510treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001511indenting comment line will be indented like the comment line. All
1512other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001513following the initial `#') are `non-indenting comment lines', and
1514their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001515
1516Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517whenever possible. Non-indenting comment lines are useful in cases
1518like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001519
1520\ta = b # a very wordy single-line comment that ends up being
1521\t #... continued onto another line
1522
1523\tif a == b:
1524##\t\tprint 'panic!' # old code we've `commented out'
1525\t\treturn a
1526
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001527Since the `#...' and `##' comment lines have a non-whitespace
1528character following the initial `#', Python mode ignores them when
1529computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001530
1531Continuation Lines and Statements
1532
1533The Python-mode commands generally work on statements instead of on
1534individual lines, where a `statement' is a comment or blank line, or a
1535code line and all of its following continuation lines (if any)
1536considered as a single logical unit. The commands in this mode
1537generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001538statement containing point, even if point happens to be in the middle
1539of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540
1541
1542@INDENTATION
1543
1544Primarily for entering new code:
1545\t\\[indent-for-tab-command]\t indent line appropriately
1546\t\\[py-newline-and-indent]\t insert newline, then indent
1547\t\\[py-delete-char]\t reduce indentation, or delete single character
1548
1549Primarily for reindenting existing code:
1550\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1551\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1552
1553\t\\[py-indent-region]\t reindent region to match its context
1554\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1555\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1556
1557Unlike most programming languages, Python uses indentation, and only
1558indentation, to specify block structure. Hence the indentation supplied
1559automatically by Python-mode is just an educated guess: only you know
1560the block structure you intend, so only you can supply correct
1561indentation.
1562
1563The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1564the indentation of preceding statements. E.g., assuming
1565py-indent-offset is 4, after you enter
1566\tif a > 0: \\[py-newline-and-indent]
1567the cursor will be moved to the position of the `_' (_ is not a
1568character in the file, it's just used here to indicate the location of
1569the cursor):
1570\tif a > 0:
1571\t _
1572If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1573to
1574\tif a > 0:
1575\t c = d
1576\t _
1577Python-mode cannot know whether that's what you intended, or whether
1578\tif a > 0:
1579\t c = d
1580\t_
1581was your intent. In general, Python-mode either reproduces the
1582indentation of the (closest code or indenting-comment) preceding
1583statement, or adds an extra py-indent-offset blanks if the preceding
1584statement has `:' as its last significant (non-whitespace and non-
1585comment) character. If the suggested indentation is too much, use
1586\\[py-delete-char] to reduce it.
1587
1588Continuation lines are given extra indentation. If you don't like the
1589suggested indentation, change it to something you do like, and Python-
1590mode will strive to indent later lines of the statement in the same way.
1591
1592If a line is a continuation line by virtue of being in an unclosed
1593paren/bracket/brace structure (`list', for short), the suggested
1594indentation depends on whether the current line contains the first item
1595in the list. If it does, it's indented py-indent-offset columns beyond
1596the indentation of the line containing the open bracket. If you don't
1597like that, change it by hand. The remaining items in the list will mimic
1598whatever indentation you give to the first item.
1599
1600If a line is a continuation line because the line preceding it ends with
1601a backslash, the third and following lines of the statement inherit their
1602indentation from the line preceding them. The indentation of the second
1603line in the statement depends on the form of the first (base) line: if
1604the base line is an assignment statement with anything more interesting
1605than the backslash following the leftmost assigning `=', the second line
1606is indented two columns beyond that `='. Else it's indented to two
1607columns beyond the leftmost solid chunk of non-whitespace characters on
1608the base line.
1609
1610Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1611repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1612structure you intend.
1613%c:indent-for-tab-command
1614%c:py-newline-and-indent
1615%c:py-delete-char
1616
1617
1618The next function may be handy when editing code you didn't write:
1619%c:py-guess-indent-offset
1620
1621
1622The remaining `indent' functions apply to a region of Python code. They
1623assume the block structure (equals indentation, in Python) of the region
1624is correct, and alter the indentation in various ways while preserving
1625the block structure:
1626%c:py-indent-region
1627%c:py-shift-region-left
1628%c:py-shift-region-right
1629
1630@MARKING & MANIPULATING REGIONS OF CODE
1631
1632\\[py-mark-block]\t mark block of lines
1633\\[mark-python-def-or-class]\t mark smallest enclosing def
1634\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1635\\[py-comment-region]\t comment out region of code
1636\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1637%c:py-mark-block
1638%c:mark-python-def-or-class
1639%c:py-comment-region
1640
1641@MOVING POINT
1642
1643\\[py-previous-statement]\t move to statement preceding point
1644\\[py-next-statement]\t move to statement following point
1645\\[py-goto-block-up]\t move up to start of current block
1646\\[beginning-of-python-def-or-class]\t move to start of def
1647\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1648\\[end-of-python-def-or-class]\t move to end of def
1649\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1650
1651The first two move to one statement beyond the statement that contains
1652point. A numeric prefix argument tells them to move that many
1653statements instead. Blank lines, comment lines, and continuation lines
1654do not count as `statements' for these commands. So, e.g., you can go
1655to the first code statement in a file by entering
1656\t\\[beginning-of-buffer]\t to move to the top of the file
1657\t\\[py-next-statement]\t to skip over initial comments and blank lines
1658Or do `\\[py-previous-statement]' with a huge prefix argument.
1659%c:py-previous-statement
1660%c:py-next-statement
1661%c:py-goto-block-up
1662%c:beginning-of-python-def-or-class
1663%c:end-of-python-def-or-class
1664
1665@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1666
1667`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1668
1669`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1670overall class and def structure of a module.
1671
1672`\\[back-to-indentation]' moves point to a line's first non-blank character.
1673
1674`\\[indent-relative]' is handy for creating odd indentation.
1675
1676@OTHER EMACS HINTS
1677
1678If you don't like the default value of a variable, change its value to
1679whatever you do like by putting a `setq' line in your .emacs file.
1680E.g., to set the indentation increment to 4, put this line in your
1681.emacs:
1682\t(setq py-indent-offset 4)
1683To see the value of a variable, do `\\[describe-variable]' and enter the variable
1684name at the prompt.
1685
1686When entering a key sequence like `C-c C-n', it is not necessary to
1687release the CONTROL key after doing the `C-c' part -- it suffices to
1688press the CONTROL key, press and release `c' (while still holding down
1689CONTROL), press and release `n' (while still holding down CONTROL), &
1690then release CONTROL.
1691
1692Entering Python mode calls with no arguments the value of the variable
1693`python-mode-hook', if that value exists and is not nil; for backward
1694compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1695the Elisp manual for details.
1696
1697Obscure: When python-mode is first loaded, it looks for all bindings
1698to newline-and-indent in the global keymap, and shadows them with
1699local bindings to py-newline-and-indent."))
1700
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001701
1702;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001703(defvar py-parse-state-re
1704 (concat
1705 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1706 "\\|"
1707 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001708
Barry Warsaw7ae77681994-12-12 20:38:05 +00001709;; returns the parse state at point (see parse-partial-sexp docs)
1710(defun py-parse-state ()
1711 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713 ;; back up to the first preceding line (if any; else start of
1714 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001715 ;; whitespace and non-comment character. These are good places
1716 ;; to start parsing to see whether where we started is at a
1717 ;; non-zero nesting level. It may be slow for people who write
1718 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001719 (re-search-backward py-parse-state-re nil 'move)
1720 (beginning-of-line)
1721 (parse-partial-sexp (point) here))))
1722
1723;; if point is at a non-zero nesting level, returns the number of the
1724;; character that opens the smallest enclosing unclosed list; else
1725;; returns nil.
1726(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001727 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001728 (if (zerop (car status))
1729 nil ; not in a nest
1730 (car (cdr status))))) ; char# of open bracket
1731
1732;; t iff preceding line ends with backslash that's not in a comment
1733(defun py-backslash-continuation-line-p ()
1734 (save-excursion
1735 (beginning-of-line)
1736 (and
1737 ;; use a cheap test first to avoid the regexp if possible
1738 ;; use 'eq' because char-after may return nil
1739 (eq (char-after (- (point) 2)) ?\\ )
1740 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001742 (looking-at py-continued-re))))
1743
1744;; t iff current line is a continuation line
1745(defun py-continuation-line-p ()
1746 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001747 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001748 (or (py-backslash-continuation-line-p)
1749 (py-nesting-level))))
1750
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751;; go to initial line of current statement; usually this is the line
1752;; we're on, but if we're on the 2nd or following lines of a
1753;; continuation block, we need to go up to the first line of the
1754;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001755;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756;; Tricky: We want to avoid quadratic-time behavior for long continued
1757;; blocks, whether of the backslash or open-bracket varieties, or a
1758;; mix of the two. The following manages to do that in the usual
1759;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760(defun py-goto-initial-line ()
1761 (let ( open-bracket-pos )
1762 (while (py-continuation-line-p)
1763 (beginning-of-line)
1764 (if (py-backslash-continuation-line-p)
1765 (while (py-backslash-continuation-line-p)
1766 (forward-line -1))
1767 ;; else zip out of nested brackets/braces/parens
1768 (while (setq open-bracket-pos (py-nesting-level))
1769 (goto-char open-bracket-pos)))))
1770 (beginning-of-line))
1771
1772;; go to point right beyond final line of current statement; usually
1773;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001774;; statement we need to skip over the continuation lines. Tricky:
1775;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776(defun py-goto-beyond-final-line ()
1777 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779 (while (and (py-continuation-line-p)
1780 (not (eobp)))
1781 ;; skip over the backslash flavor
1782 (while (and (py-backslash-continuation-line-p)
1783 (not (eobp)))
1784 (forward-line 1))
1785 ;; if in nest, zip to the end of the nest
1786 (setq state (py-parse-state))
1787 (if (and (not (zerop (car state)))
1788 (not (eobp)))
1789 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791 ;; the 3rd argument should be plain 0
1792 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1793 nil state)
1794 (forward-line 1))))))
1795
1796;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001797;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001798(defun py-statement-opens-block-p ()
1799 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800 (let ((start (point))
1801 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1802 (searching t)
1803 (answer nil)
1804 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805 (goto-char start)
1806 (while searching
1807 ;; look for a colon with nothing after it except whitespace, and
1808 ;; maybe a comment
1809 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1810 finish t)
1811 (if (eq (point) finish) ; note: no `else' clause; just
1812 ; keep searching if we're not at
1813 ; the end yet
1814 ;; sure looks like it opens a block -- but it might
1815 ;; be in a comment
1816 (progn
1817 (setq searching nil) ; search is done either way
1818 (setq state (parse-partial-sexp start
1819 (match-beginning 0)))
1820 (setq answer (not (nth 4 state)))))
1821 ;; search failed: couldn't find another interesting colon
1822 (setq searching nil)))
1823 answer)))
1824
1825;; go to point right beyond final line of block begun by the current
1826;; line. This is the same as where py-goto-beyond-final-line goes
1827;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001828;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829(defun py-goto-beyond-block ()
1830 (if (py-statement-opens-block-p)
1831 (py-mark-block nil 'just-move)
1832 (py-goto-beyond-final-line)))
1833
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834;; go to start of first statement (not blank or comment or
1835;; continuation line) at or preceding point. returns t if there is
1836;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001837(defun py-goto-statement-at-or-above ()
1838 (py-goto-initial-line)
1839 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840 ;; skip back over blank & comment lines
1841 ;; note: will skip a blank or comment line that happens to be
1842 ;; a continuation line too
1843 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1844 (progn (py-goto-initial-line) t)
1845 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846 t))
1847
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001848;; go to start of first statement (not blank or comment or
1849;; continuation line) following the statement containing point returns
1850;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001851(defun py-goto-statement-below ()
1852 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854 (py-goto-beyond-final-line)
1855 (while (and
1856 (looking-at py-blank-or-comment-re)
1857 (not (eobp)))
1858 (forward-line 1))
1859 (if (eobp)
1860 (progn (goto-char start) nil)
1861 t)))
1862
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863;; go to start of statement, at or preceding point, starting with
1864;; keyword KEY. Skips blank lines and non-indenting comments upward
1865;; first. If that statement starts with KEY, done, else go back to
1866;; first enclosing block starting with KEY. If successful, leaves
1867;; point at the start of the KEY line & returns t. Else leaves point
1868;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001869(defun py-go-up-tree-to-keyword (key)
1870 ;; skip blanks and non-indenting #
1871 (py-goto-initial-line)
1872 (while (and
1873 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1874 (zerop (forward-line -1))) ; go back
1875 nil)
1876 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 (let* ((re (concat "[ \t]*" key "\\b"))
1878 (case-fold-search nil) ; let* so looking-at sees this
1879 (found (looking-at re))
1880 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (while (not (or found dead))
1882 (condition-case nil ; in case no enclosing block
1883 (py-goto-block-up 'no-mark)
1884 (error (setq dead t)))
1885 (or dead (setq found (looking-at re))))
1886 (beginning-of-line)
1887 found))
1888
1889;; return string in buffer from start of indentation to end of line;
1890;; prefix "..." if leading whitespace was skipped
1891(defun py-suck-up-leading-text ()
1892 (save-excursion
1893 (back-to-indentation)
1894 (concat
1895 (if (bolp) "" "...")
1896 (buffer-substring (point) (progn (end-of-line) (point))))))
1897
1898;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1899;; as a Lisp symbol; return nil if none
1900(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001901 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001902 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1903 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1904 nil)))
1905
1906(defun py-make-temp-name ()
1907 (make-temp-name
1908 (concat (file-name-as-directory py-temp-directory) "python")))
1909
1910(defun py-delete-file-silently (fname)
1911 (condition-case nil
1912 (delete-file fname)
1913 (error nil)))
1914
1915(defun py-kill-emacs-hook ()
1916 ;; delete our temp files
1917 (while py-file-queue
1918 (py-delete-file-silently (car py-file-queue))
1919 (setq py-file-queue (cdr py-file-queue)))
1920 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1921 ;; run the hook we inherited, if any
1922 (and py-inherited-kill-emacs-hook
1923 (funcall py-inherited-kill-emacs-hook))))
1924
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001925;; make PROCESS's buffer visible, append STRING to it, and force
1926;; display; also make shell-mode believe the user typed this string,
1927;; so that kill-output-from-shell and show-output-from-shell work
1928;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930 (let ((cbuf (current-buffer))
1931 (pbuf (process-buffer process))
1932 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001933 (set-buffer pbuf)
1934 (goto-char (point-max))
1935 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001936 (if (not (or py-this-is-emacs-19-p
1937 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938 (move-marker last-input-start (point))) ; muck w/ shell-mode
1939 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001940 (if (not (or py-this-is-emacs-19-p
1941 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001942 (move-marker last-input-end (point))) ; muck w/ shell-mode
1943 (set-buffer cbuf))
1944 (sit-for 0))
1945
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001946(defun py-keep-region-active ()
1947 ;; do whatever is necessary to keep the region active in XEmacs.
1948 ;; Ignore byte-compiler warnings you might see. Also note that
1949 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1950 ;; require us to take explicit action.
1951 (and (boundp 'zmacs-region-stays)
1952 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001953
1954
Barry Warsaw850437a1995-03-08 21:50:28 +00001955(defconst py-version "$Revision$"
1956 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001957(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001958 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001959
Barry Warsaw850437a1995-03-08 21:50:28 +00001960(defun py-version ()
1961 "Echo the current version of `python-mode' in the minibuffer."
1962 (interactive)
1963 (message "Using `python-mode' version %s" py-version)
1964 (py-keep-region-active))
1965
1966;; only works under Emacs 19
1967;(eval-when-compile
1968; (require 'reporter))
1969
1970(defun py-submit-bug-report (enhancement-p)
1971 "Submit via mail a bug report on `python-mode'.
1972With \\[universal-argument] just submit an enhancement request."
1973 (interactive
1974 (list (not (y-or-n-p
1975 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001976 (let ((reporter-prompt-for-summary-p (if enhancement-p
1977 "(Very) brief summary: "
1978 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001979 (require 'reporter)
1980 (reporter-submit-bug-report
1981 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001982 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001983 ;; varlist
1984 (if enhancement-p nil
1985 '(py-python-command
1986 py-indent-offset
1987 py-block-comment-prefix
1988 py-scroll-process-buffer
1989 py-temp-directory
1990 py-beep-if-tab-change))
1991 nil ;pre-hooks
1992 nil ;post-hooks
1993 "Dear Barry,") ;salutation
1994 (if enhancement-p nil
1995 (set-mark (point))
1996 (insert
1997"Please replace this text with a sufficiently large code sample\n\
1998and an exact recipe so that I can reproduce your problem. Failure\n\
1999to do so may mean a greater delay in fixing your bug.\n\n")
2000 (exchange-point-and-mark)
2001 (py-keep-region-active))))
2002
2003
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002004;; arrange to kill temp files when Emacs exists
2005(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2006 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2007 ;; have to trust that other people are as respectful of our hook
2008 ;; fiddling as we are of theirs
2009 (if (boundp 'py-inherited-kill-emacs-hook)
2010 ;; we were loaded before -- trust others not to have screwed us
2011 ;; in the meantime (no choice, really)
2012 nil
2013 ;; else arrange for our hook to run theirs
2014 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2015 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2016
2017
2018
2019(provide 'python-mode)
2020;;; python-mode.el ends here