blob: af1c24d53957fc780d2676015c634959127901c0 [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 Warsaw4669d7e1996-03-22 16:13:24 +00005;; Author: 1995-1996 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry 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 Warsaw4669d7e1996-03-22 16:13:24 +000024;; (Barry) 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
Barry Warsaw03970731996-07-03 23:12:52 +000028;; mode works exceedingly well, and I've simply been tweaking it as I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000029;; go along. Ain't it wonderful that Python has a much more sane
Barry Warsaw03970731996-07-03 23:12:52 +000030;; syntax than C? (or <shudder> C++?! :-). I can say that; I maintain
31;; cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
33;; The following statements, placed in your .emacs file or
34;; site-init.el, will cause this file to be autoloaded, and
35;; python-mode invoked, when visiting .py files (assuming this file is
36;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000037;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000041;;
42;; If you want font-lock support for Python source code (a.k.a. syntax
43;; coloring, highlighting), add this to your .emacs file:
44;;
45;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsaw7ae77681994-12-12 20:38:05 +000046
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000047;; Here's a brief list of recent additions/improvements:
48;;
49;; - Wrapping and indentation within triple quote strings should work
50;; properly now.
51;; - `Standard' bug reporting mechanism (use C-c C-b)
52;; - py-mark-block was moved to C-c C-m
53;; - C-c C-v shows you the python-mode version
54;; - a basic python-font-lock-keywords has been added for Emacs 19
55;; font-lock colorizations.
56;; - proper interaction with pending-del and del-sel modes.
57;; - New py-electric-colon (:) command for improved outdenting. Also
58;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw03970731996-07-03 23:12:52 +000059;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000060;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
61;; M-f and M-b respectively.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000062
Barry Warsaw7b0f5681995-03-08 21:33:04 +000063;; Here's a brief to do list:
64;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000065;; - Better integration with gud-mode for debugging.
66;; - Rewrite according to GNU Emacs Lisp standards.
67;; - py-delete-char should obey numeric arguments.
68;; - even better support for outdenting. Guido suggests outdents of
69;; at least one level after a return, raise, break, or continue
Barry Warsawfc9cc3a1996-07-08 22:37:06 +000070;; statement. I also suggest trying to match up try/finally's and
71;; the like.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000072;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000073
Barry Warsaw7b0f5681995-03-08 21:33:04 +000074;; If you can think of more things you'd like to see, drop me a line.
75;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
76;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000077;; Note that I only test things on XEmacs. If you port stuff to FSF
78;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
79;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
Barry Warsaw7b0f5681995-03-08 21:33:04 +000081;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000082;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000083;; |Major mode for editing Python programs
84;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000085
Barry Warsaw7b0f5681995-03-08 21:33:04 +000086;;; Code:
87
88
89;; user definable variables
90;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000091
92(defvar py-python-command "python"
93 "*Shell command used to start Python interpreter.")
94
Barry Warsaw17914f41995-11-03 18:25:15 +000095(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000096 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097Note that `\\[py-guess-indent-offset]' can usually guess a good value
98when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000099
Barry Warsaw095e9c61995-09-19 20:01:42 +0000100(defvar py-align-multiline-strings-p t
101 "*Flag describing how multiline triple quoted strings are aligned.
102When this flag is non-nil, continuation lines are lined up under the
103preceding line's indentation. When this flag is nil, continuation
104lines are aligned to column zero.")
105
Barry Warsaw7ae77681994-12-12 20:38:05 +0000106(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000107 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000108This should follow the convention for non-indenting comment lines so
109that the indentation commands won't get confused (i.e., the string
110should be of the form `#x...' where `x' is not a blank or a tab, and
111`...' is arbitrary).")
112
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000113(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000114 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000115
Barry Warsaw6d627751996-03-06 18:41:38 +0000116When nil, all comment lines are skipped for indentation purposes, and
117in Emacs 19, a faster algorithm is used.
118
119When t, lines that begin with a single `#' are a hint to subsequent
120line indentation. If the previous line is such a comment line (as
121opposed to one that starts with `py-block-comment-prefix'), then it's
122indentation is used as a hint for this line's indentation. Lines that
123begin with `py-block-comment-prefix' are ignored for indentation
124purposes.
125
126When not nil or t, comment lines that begin with a `#' are used as
127indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000128
Barry Warsaw7ae77681994-12-12 20:38:05 +0000129(defvar py-scroll-process-buffer t
130 "*Scroll Python process buffer as output arrives.
131If nil, the Python process buffer acts, with respect to scrolling, like
132Shell-mode buffers normally act. This is surprisingly complicated and
133so won't be explained here; in fact, you can't get the whole story
134without studying the Emacs C code.
135
136If non-nil, the behavior is different in two respects (which are
137slightly inaccurate in the interest of brevity):
138
139 - If the buffer is in a window, and you left point at its end, the
140 window will scroll as new output arrives, and point will move to the
141 buffer's end, even if the window is not the selected window (that
142 being the one the cursor is in). The usual behavior for shell-mode
143 windows is not to scroll, and to leave point where it was, if the
144 buffer is in a window other than the selected window.
145
146 - If the buffer is not visible in any window, and you left point at
147 its end, the buffer will be popped into a window as soon as more
148 output arrives. This is handy if you have a long-running
149 computation and don't want to tie up screen area waiting for the
150 output. The usual behavior for a shell-mode buffer is to stay
151 invisible until you explicitly visit it.
152
153Note the `and if you left point at its end' clauses in both of the
154above: you can `turn off' the special behaviors while output is in
155progress, by visiting the Python buffer and moving point to anywhere
156besides the end. Then the buffer won't scroll, point will remain where
157you leave it, and if you hide the buffer it will stay hidden until you
158visit it again. You can enable and disable the special behaviors as
159often as you like, while output is in progress, by (respectively) moving
160point to, or away from, the end of the buffer.
161
162Warning: If you expect a large amount of output, you'll probably be
163happier setting this option to nil.
164
165Obscure: `End of buffer' above should really say `at or beyond the
166process mark', but if you know what that means you didn't need to be
167told <grin>.")
168
169(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000170 (let ((ok '(lambda (x)
171 (and x
172 (setq x (expand-file-name x)) ; always true
173 (file-directory-p x)
174 (file-writable-p x)
175 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000176 (or (funcall ok (getenv "TMPDIR"))
177 (funcall ok "/usr/tmp")
178 (funcall ok "/tmp")
179 (funcall ok ".")
180 (error
181 "Couldn't find a usable temp directory -- set py-temp-directory")))
182 "*Directory used for temp files created by a *Python* process.
183By default, the first directory from this list that exists and that you
184can write into: the value (if any) of the environment variable TMPDIR,
185/usr/tmp, /tmp, or the current directory.")
186
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000187(defvar py-beep-if-tab-change t
188 "*Ring the bell if tab-width is changed.
189If a comment of the form
190
191 \t# vi:set tabsize=<number>:
192
193is found before the first code line when the file is entered, and the
194current value of (the general Emacs variable) `tab-width' does not
195equal <number>, `tab-width' is set to <number>, a message saying so is
196displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
197the Emacs bell is also rung as a warning.")
198
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000199(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000200 (let* ((keywords '("access" "and" "break" "class"
201 "continue" "def" "del" "elif"
202 "else:" "except" "except:" "exec"
203 "finally:" "for" "from" "global"
204 "if" "import" "in" "is"
205 "lambda" "not" "or" "pass"
206 "print" "raise" "return" "try:"
207 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000208 ))
209 (kwregex (mapconcat 'identity keywords "\\|")))
210 (list
211 ;; keywords not at beginning of line
212 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
213 ;; keywords at beginning of line. i don't think regexps are
214 ;; powerful enough to handle these two cases in one regexp.
215 ;; prove me wrong!
216 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
217 ;; classes
218 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
219 1 font-lock-type-face)
220 ;; functions
221 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
222 1 font-lock-function-name-face)
223 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000224 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000225
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000226
227;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
228;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
229
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000230(make-variable-buffer-local 'py-indent-offset)
231
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000232;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
233;; seems to be the standard way of checking this.
234;; BAW - This is *not* the right solution. When at all possible,
235;; instead of testing for the version of Emacs, use feature tests.
236
237(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
238(setq py-this-is-emacs-19-p
239 (and
240 (not py-this-is-lucid-emacs-p)
241 (string-match "^19\\." emacs-version)))
242
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243;; have to bind py-file-queue before installing the kill-emacs hook
244(defvar py-file-queue nil
245 "Queue of Python temp files awaiting execution.
246Currently-active file is at the head of the list.")
247
248;; define a mode-specific abbrev table for those who use such things
249(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251(define-abbrev-table 'python-mode-abbrev-table nil)
252
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253(defvar python-mode-hook nil
254 "*Hook called by `python-mode'.")
255
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256;; in previous version of python-mode.el, the hook was incorrectly
257;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000258(and (fboundp 'make-obsolete-variable)
259 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
260
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000261(defvar py-mode-map ()
262 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000263
Barry Warsaw7ae77681994-12-12 20:38:05 +0000264(if py-mode-map
265 ()
266 (setq py-mode-map (make-sparse-keymap))
267
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000268 ;; shadow global bindings for newline-and-indent w/ the py- version.
269 ;; BAW - this is extremely bad form, but I'm not going to change it
270 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271 (mapcar (function (lambda (key)
272 (define-key
273 py-mode-map key 'py-newline-and-indent)))
274 (where-is-internal 'newline-and-indent))
275
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 ;; BAW - you could do it this way, but its not considered proper
277 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000278 (mapcar (function
279 (lambda (x)
280 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000281 '((":" . py-electric-colon)
282 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 ("\C-c|" . py-execute-region)
284 ("\C-c!" . py-shell)
285 ("\177" . py-delete-char)
286 ("\n" . py-newline-and-indent)
287 ("\C-c:" . py-guess-indent-offset)
288 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000289 ("\C-c\C-l" . py-shift-region-left)
290 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 ("\C-c<" . py-shift-region-left)
292 ("\C-c>" . py-shift-region-right)
293 ("\C-c\C-n" . py-next-statement)
294 ("\C-c\C-p" . py-previous-statement)
295 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000296 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000297 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298 ("\C-c?" . py-describe-mode)
299 ("\C-c\C-hm" . py-describe-mode)
300 ("\e\C-a" . beginning-of-python-def-or-class)
301 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000302 ( "\e\C-h" . mark-python-def-or-class)))
303 ;; should do all keybindings this way
304 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
305 (define-key py-mode-map "\C-c\C-v" 'py-version)
306 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000307
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000308(defvar py-mode-syntax-table nil
309 "Syntax table used in `python-mode' buffers.")
310
Barry Warsaw7ae77681994-12-12 20:38:05 +0000311(if py-mode-syntax-table
312 ()
313 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000314 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315 (mapcar (function
316 (lambda (x) (modify-syntax-entry
317 (car x) (cdr x) py-mode-syntax-table)))
318 '(( ?\( . "()" ) ( ?\) . ")(" )
319 ( ?\[ . "(]" ) ( ?\] . ")[" )
320 ( ?\{ . "(}" ) ( ?\} . "){" )
321 ;; fix operator symbols misassigned in the std table
322 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
323 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
324 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
325 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000326 ;; for historical reasons, underscore is word class
327 ;; instead of symbol class. it should be symbol class,
328 ;; but if you're tempted to change it, try binding M-f and
329 ;; M-b to py-forward-into-nomenclature and
330 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000331 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000332 ( ?\' . "\"") ; single quote is string quote
333 ( ?\" . "\"" ) ; double quote is string quote too
334 ( ?\` . "$") ; backquote is open and close paren
335 ( ?\# . "<") ; hash starts comment
336 ( ?\n . ">")))) ; newline ends comment
337
338(defconst py-stringlit-re
339 (concat
340 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
341 "\\|" ; or
342 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000343 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000344
345;; this is tricky because a trailing backslash does not mean
346;; continuation if it's in a comment
347(defconst py-continued-re
348 (concat
349 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
350 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000351 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000352
353(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000354 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000356(defconst py-outdent-re
357 (concat "\\(" (mapconcat 'identity
358 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000359 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000360 "finally:"
361 "elif\\s +.*:")
362 "\\|")
363 "\\)")
364 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000366(defconst py-no-outdent-re
367 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000368 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000369 "except\\(\\s +.*\\)?:"
370 "while\\s +.*:"
371 "for\\s +.*:"
372 "if\\s +.*:"
373 "elif\\s +.*:")
374 "\\|")
375 "\\)")
376 "Regexp matching lines to not outdent after.")
377
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378
Barry Warsaw42f707f1996-07-29 21:05:05 +0000379;; Menu definitions, only relevent if you have the easymenu.el package
380;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
381(if (condition-case nil
382 (require 'easymenu)
383 (error nil))
384 (easy-menu-define
385 py-menu py-mode-map "Python Mode menu"
386 '("Python"
387 ["Comment Out Region" comment-region (mark)]
388 ["Uncomment Region" (comment-region (point) (mark) '(4)) (mark)]
389 "-"
390 ["Mark current block" py-mark-block t]
391 ["Mark current def" mark-python-def-or-class t]
392 ["Mark current class" (mark-python-def-or-class t) t]
393 "-"
394 ["Shift region left" py-shift-region-left (mark)]
395 ["Shift region right" py-shift-region-right (mark)]
396 "-"
397 ["Execute buffer" py-execute-buffer t]
398 ["Execute region" py-execute-region (mark)]
399 ["Start interpreter..." py-shell t]
400 "-"
401 ["Go to start of block" py-goto-block-up t]
402 ["Go to start of class" (beginning-of-python-def-or-class t) t]
403 ["Move to end of class" (end-of-python-def-or-class t) t]
404 ["Move to start of def" beginning-of-python-def-or-class t]
405 ["Move to end of def" end-of-python-def-or-class t]
406 "-"
407 ["Describe mode" py-describe-mode t]
408 )))
409
410
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000411;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000412(defun python-mode ()
413 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414To submit a problem report, enter `\\[py-submit-bug-report]' from a
415`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
416documentation. To see what version of `python-mode' you are running,
417enter `\\[py-version]'.
418
419This mode knows about Python indentation, tokens, comments and
420continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000421
422COMMANDS
423\\{py-mode-map}
424VARIABLES
425
Barry Warsaw42f707f1996-07-29 21:05:05 +0000426py-indent-offset\t\tindentation increment
427py-block-comment-prefix\t\tcomment string used by comment-region
428py-python-command\t\tshell command to invoke Python interpreter
429py-scroll-process-buffer\t\talways scroll Python process buffer
430py-temp-directory\t\tdirectory used for temp files (if needed)
431py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000432 (interactive)
433 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000434 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000435 (setq major-mode 'python-mode
436 mode-name "Python"
437 local-abbrev-table python-mode-abbrev-table)
438 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000439 ;; add the menu
440 (if py-menu
441 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000442 ;; Emacs 19 requires this
443 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
444 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000445 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000446 (mapcar (function (lambda (x)
447 (make-local-variable (car x))
448 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000449 '((paragraph-separate . "^[ \t]*$")
450 (paragraph-start . "^[ \t]*$")
451 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000452 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453 (comment-start-skip . "# *")
454 (comment-column . 40)
455 (indent-region-function . py-indent-region)
456 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000457 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000458 ;;
459 ;; not sure where the magic comment has to be; to save time
460 ;; searching for a rarity, we give up if it's not found prior to the
461 ;; first executable statement.
462 ;;
463 ;; BAW - on first glance, this seems like complete hackery. Why was
464 ;; this necessary, and is it still necessary?
465 (let ((case-fold-search nil)
466 (start (point))
467 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000468 (if (re-search-forward
469 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
470 (prog2 (py-next-statement 1) (point) (goto-char 1))
471 t)
472 (progn
473 (setq new-tab-width
474 (string-to-int
475 (buffer-substring (match-beginning 1) (match-end 1))))
476 (if (= tab-width new-tab-width)
477 nil
478 (setq tab-width new-tab-width)
479 (message "Caution: tab-width changed to %d" new-tab-width)
480 (if py-beep-if-tab-change (beep)))))
481 (goto-char start))
482
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000483 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000484 (if python-mode-hook
485 (run-hooks 'python-mode-hook)
486 (run-hooks 'py-mode-hook)))
487
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000488
Barry Warsaw826255b1996-03-22 16:09:34 +0000489(defun py-keep-region-active ()
490 ;; Do whatever is necessary to keep the region active in
491 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
492 ;; ignore byte-compiler warnings you might see.
493 (and (boundp 'zmacs-region-stays)
494 (setq zmacs-region-stays t)))
495
Barry Warsawb91b7431995-03-14 15:55:20 +0000496;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000497(defun py-outdent-p ()
498 ;; returns non-nil if the current line should outdent one level
499 (save-excursion
500 (and (progn (back-to-indentation)
501 (looking-at py-outdent-re))
502 (progn (backward-to-indentation 1)
503 (while (or (looking-at py-blank-or-comment-re)
504 (bobp))
505 (backward-to-indentation 1))
506 (not (looking-at py-no-outdent-re)))
507 )))
508
509
Barry Warsawb91b7431995-03-14 15:55:20 +0000510(defun py-electric-colon (arg)
511 "Insert a colon.
512In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000513argument is provided, that many colons are inserted non-electrically.
514Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000515 (interactive "P")
516 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000517 ;; are we in a string or comment?
518 (if (save-excursion
519 (let ((pps (parse-partial-sexp (save-excursion
520 (beginning-of-python-def-or-class)
521 (point))
522 (point))))
523 (not (or (nth 3 pps) (nth 4 pps)))))
524 (save-excursion
525 (let ((here (point))
526 (outdent 0)
527 (indent (py-compute-indentation)))
528 (if (and (not arg)
529 (py-outdent-p)
530 (= indent (save-excursion
531 (forward-line -1)
532 (py-compute-indentation)))
533 )
534 (setq outdent py-indent-offset))
535 ;; Don't indent, only outdent. This assumes that any lines that
536 ;; are already outdented relative to py-compute-indentation were
537 ;; put there on purpose. Its highly annoying to have `:' indent
538 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
539 ;; there a better way to determine this???
540 (if (< (current-indentation) indent) nil
541 (goto-char here)
542 (beginning-of-line)
543 (delete-horizontal-space)
544 (indent-to (- indent outdent))
545 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000546
547
Barry Warsaw7ae77681994-12-12 20:38:05 +0000548;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549(defun py-shell ()
550 "Start an interactive Python interpreter in another window.
551This is like Shell mode, except that Python is running in the window
552instead of a shell. See the `Interactive Shell' and `Shell Mode'
553sections of the Emacs manual for details, especially for the key
554bindings active in the `*Python*' buffer.
555
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000556See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557behavior in the process window.
558
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000559Warning: Don't use an interactive Python if you change sys.ps1 or
560sys.ps2 from their default values, or if you're running code that
561prints `>>> ' or `... ' at the start of a line. `python-mode' can't
562distinguish your output from Python's output, and assumes that `>>> '
563at the start of a line is a prompt from Python. Similarly, the Emacs
564Shell mode code assumes that both `>>> ' and `... ' at the start of a
565line are Python prompts. Bad things can happen if you fool either
566mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000567
568Warning: If you do any editing *in* the process buffer *while* the
569buffer is accepting output from Python, do NOT attempt to `undo' the
570changes. Some of the output (nowhere near the parts you changed!) may
571be lost if you do. This appears to be an Emacs bug, an unfortunate
572interaction between undo and process filters; the same problem exists in
573non-Python process buffers using the default (Emacs-supplied) process
574filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000575 ;; BAW - should undo be disabled in the python process buffer, if
576 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000577 (interactive)
578 (if py-this-is-emacs-19-p
579 (progn
580 (require 'comint)
581 (switch-to-buffer-other-window
582 (make-comint "Python" py-python-command)))
583 (progn
584 (require 'shell)
585 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000586 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000587 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000588 (make-local-variable 'shell-prompt-pattern)
589 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
590 (set-process-filter (get-buffer-process (current-buffer))
591 'py-process-filter)
592 (set-syntax-table py-mode-syntax-table))
593
594(defun py-execute-region (start end)
595 "Send the region between START and END to a Python interpreter.
596If there is a *Python* process it is used.
597
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000598Hint: If you want to execute part of a Python file several times
599\(e.g., perhaps you're developing a function and want to flesh it out
600a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
601the region of interest, and send the code to a *Python* process via
602`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000603
604Following are subtleties to note when using a *Python* process:
605
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000606If a *Python* process is used, the region is copied into a temporary
607file (in directory `py-temp-directory'), and an `execfile' command is
608sent to Python naming that file. If you send regions faster than
609Python can execute them, `python-mode' will save them into distinct
610temp files, and execute the next one in the queue the next time it
611sees a `>>> ' prompt from Python. Each time this happens, the process
612buffer is popped into a window (if it's not already in some window) so
613you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000614
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000615 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000616
617is inserted at the end.
618
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000619Caution: No more than 26 regions can be pending at any given time.
620This limit is (indirectly) inherited from libc's mktemp(3).
621`python-mode' does not try to protect you from exceeding the limit.
622It's extremely unlikely that you'll get anywhere close to the limit in
623practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000624
625See the `\\[py-shell]' docs for additional warnings."
626 (interactive "r")
627 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000628 (let ((pyproc (get-process "Python"))
629 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630 (if (null pyproc)
631 (shell-command-on-region start end py-python-command)
632 ;; else feed it thru a temp file
633 (setq fname (py-make-temp-name))
634 (write-region start end fname nil 'no-msg)
635 (setq py-file-queue (append py-file-queue (list fname)))
636 (if (cdr py-file-queue)
637 (message "File %s queued for execution" fname)
638 ;; else
639 (py-execute-file pyproc fname)))))
640
641(defun py-execute-file (pyproc fname)
642 (py-append-to-process-buffer
643 pyproc
644 (format "## working on region in file %s ...\n" fname))
645 (process-send-string pyproc (format "execfile('%s')\n" fname)))
646
647(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000648 (let ((curbuf (current-buffer))
649 (pbuf (process-buffer pyproc))
650 (pmark (process-mark pyproc))
651 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000652
653 ;; make sure we switch to a different buffer at least once. if we
654 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000655 ;; window, and point is before the end, and lots of output is
656 ;; coming at a fast pace, then (a) simple cursor-movement commands
657 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
658 ;; to have a visible effect (the window just doesn't get updated,
659 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
660 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000661 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000662 ;; #b makes no sense to me at all. #a almost makes sense: unless
663 ;; we actually change buffers, set_buffer_internal in buffer.c
664 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
665 ;; seems to make the Emacs command loop reluctant to update the
666 ;; display. Perhaps the default process filter in process.c's
667 ;; read_process_output has update_mode_lines++ for a similar
668 ;; reason? beats me ...
669
670 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000671 (if (eq curbuf pbuf) ; mysterious ugly hack
672 (set-buffer (get-buffer-create "*scratch*")))
673
674 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000675 (let* ((start (point))
676 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000677 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000678 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000679 (goto-char pmark)
680 (insert string)
681 (move-marker pmark (point))
682 (setq file-finished
683 (and py-file-queue
684 (equal ">>> "
685 (buffer-substring
686 (prog2 (beginning-of-line) (point)
687 (goto-char pmark))
688 (point)))))
689 (if goback (goto-char start)
690 ;; else
691 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000692 (let* ((pop-up-windows t)
693 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000694 (set-window-point pwin (point)))))
695 (set-buffer curbuf)
696 (if file-finished
697 (progn
698 (py-delete-file-silently (car py-file-queue))
699 (setq py-file-queue (cdr py-file-queue))
700 (if py-file-queue
701 (py-execute-file pyproc (car py-file-queue)))))
702 (and goend
703 (progn (set-buffer pbuf)
704 (goto-char (point-max))))
705 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000706
707(defun py-execute-buffer ()
708 "Send the contents of the buffer to a Python interpreter.
709If there is a *Python* process buffer it is used. If a clipping
710restriction is in effect, only the accessible portion of the buffer is
711sent. A trailing newline will be supplied if needed.
712
713See the `\\[py-execute-region]' docs for an account of some subtleties."
714 (interactive)
715 (py-execute-region (point-min) (point-max)))
716
717
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000718
719;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000720(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000721 "Reduce indentation or delete character.
722If point is at the leftmost column, deletes the preceding newline.
723
724Else if point is at the leftmost non-blank character of a line that is
725neither a continuation line nor a non-indenting comment line, or if
726point is at the end of a blank line, reduces the indentation to match
727that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000728opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000729of where you are. With numeric count, outdents that many blocks (but
730not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000731
732Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000733needed so that only a single column position is deleted. Numeric
734argument delets that many characters."
735 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000736 (if (or (/= (current-indentation) (current-column))
737 (bolp)
738 (py-continuation-line-p)
739 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000740 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000741 ;; else indent the same as the colon line that opened the block
742
743 ;; force non-blank so py-goto-block-up doesn't ignore it
744 (insert-char ?* 1)
745 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000746 (let ((base-indent 0) ; indentation of base line
747 (base-text "") ; and text of base line
748 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000749 (save-excursion
750 (while (< 0 count)
751 (condition-case nil ; in case no enclosing block
752 (progn
753 (py-goto-block-up 'no-mark)
754 (setq base-indent (current-indentation)
755 base-text (py-suck-up-leading-text)
756 base-found-p t))
757 (error nil))
758 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000759 (delete-char 1) ; toss the dummy character
760 (delete-horizontal-space)
761 (indent-to base-indent)
762 (if base-found-p
763 (message "Closes block: %s" base-text)))))
764
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000765;; required for pending-del and delsel modes
766(put 'py-delete-char 'delete-selection 'supersede)
767(put 'py-delete-char 'pending-delete 'supersede)
768
Barry Warsaw7ae77681994-12-12 20:38:05 +0000769(defun py-indent-line ()
770 "Fix the indentation of the current line according to Python rules."
771 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000772 (let* ((ci (current-indentation))
773 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000774 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000775 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000776 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000777 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000778 (if (/= ci need)
779 (save-excursion
780 (beginning-of-line)
781 (delete-horizontal-space)
782 (indent-to need)))
783 (if move-to-indentation-p (back-to-indentation))))
784
785(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000786 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000787This is just `strives to' because correct indentation can't be computed
788from scratch for Python code. In general, deletes the whitespace before
789point, inserts a newline, and takes an educated guess as to how you want
790the new line indented."
791 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000792 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000793 (if (< ci (current-column)) ; if point beyond indentation
794 (newline-and-indent)
795 ;; else try to act like newline-and-indent "normally" acts
796 (beginning-of-line)
797 (insert-char ?\n 1)
798 (move-to-column ci))))
799
800(defun py-compute-indentation ()
801 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000802 (let ((pps (parse-partial-sexp (save-excursion
803 (beginning-of-python-def-or-class)
804 (point))
805 (point))))
806 (beginning-of-line)
807 (cond
808 ;; are we inside a string or comment?
809 ((or (nth 3 pps) (nth 4 pps))
810 (save-excursion
811 (if (not py-align-multiline-strings-p) 0
812 ;; skip back over blank & non-indenting comment lines
813 ;; note: will skip a blank or non-indenting comment line
814 ;; that happens to be a continuation line too
815 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
816 (back-to-indentation)
817 (current-column))))
818 ;; are we on a continuation line?
819 ((py-continuation-line-p)
820 (let ((startpos (point))
821 (open-bracket-pos (py-nesting-level))
822 endpos searching found)
823 (if open-bracket-pos
824 (progn
825 ;; align with first item in list; else a normal
826 ;; indent beyond the line with the open bracket
827 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
828 ;; is the first list item on the same line?
829 (skip-chars-forward " \t")
830 (if (null (memq (following-char) '(?\n ?# ?\\)))
831 ; yes, so line up with it
832 (current-column)
833 ;; first list item on another line, or doesn't exist yet
834 (forward-line 1)
835 (while (and (< (point) startpos)
836 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
837 (forward-line 1))
838 (if (< (point) startpos)
839 ;; again mimic the first list item
840 (current-indentation)
841 ;; else they're about to enter the first item
842 (goto-char open-bracket-pos)
843 (+ (current-indentation) py-indent-offset))))
844
845 ;; else on backslash continuation line
846 (forward-line -1)
847 (if (py-continuation-line-p) ; on at least 3rd line in block
848 (current-indentation) ; so just continue the pattern
849 ;; else started on 2nd line in block, so indent more.
850 ;; if base line is an assignment with a start on a RHS,
851 ;; indent to 2 beyond the leftmost "="; else skip first
852 ;; chunk of non-whitespace characters on base line, + 1 more
853 ;; column
854 (end-of-line)
855 (setq endpos (point) searching t)
856 (back-to-indentation)
857 (setq startpos (point))
858 ;; look at all "=" from left to right, stopping at first
859 ;; one not nested in a list or string
860 (while searching
861 (skip-chars-forward "^=" endpos)
862 (if (= (point) endpos)
863 (setq searching nil)
864 (forward-char 1)
865 (setq state (parse-partial-sexp startpos (point)))
866 (if (and (zerop (car state)) ; not in a bracket
867 (null (nth 3 state))) ; & not in a string
868 (progn
869 (setq searching nil) ; done searching in any case
870 (setq found
871 (not (or
872 (eq (following-char) ?=)
873 (memq (char-after (- (point) 2))
874 '(?< ?> ?!)))))))))
875 (if (or (not found) ; not an assignment
876 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
877 (progn
878 (goto-char startpos)
879 (skip-chars-forward "^ \t\n")))
880 (1+ (current-column))))))
881
882 ;; not on a continuation line
883
884 ;; if at start of restriction, or on a non-indenting comment
885 ;; line, assume they intended whatever's there
886 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
887 (current-indentation))
888
889 ;; else indentation based on that of the statement that
890 ;; precedes us; use the first line of that statement to
891 ;; establish the base, in case the user forced a non-std
892 ;; indentation for the continuation lines (if any)
893 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000894 ;; skip back over blank & non-indenting comment lines note:
895 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000896 ;; happens to be a continuation line too. use fast Emacs 19
897 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000898 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000899 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000900 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000901 (let (done)
902 (while (not done)
903 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
904 nil 'move)
905 (setq done (or (eq py-honor-comment-indentation t)
906 (bobp)
907 (/= (following-char) ?#)
908 (not (zerop (current-column)))))
909 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000910 ;; if we landed inside a string, go to the beginning of that
911 ;; string. this handles triple quoted, multi-line spanning
912 ;; strings.
913 (py-goto-initial-line)
914 (if (py-statement-opens-block-p)
915 (+ (current-indentation) py-indent-offset)
916 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000917
918(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000919 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000920By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000921`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000922Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000923`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000924their own buffer-local copy), both those currently existing and those
925created later in the Emacs session.
926
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000927Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000928There's no excuse for such foolishness, but sometimes you have to deal
929with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000930`py-indent-offset' to what it thinks it was when they created the
931mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000932
933Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000934looking for a line that opens a block of code. `py-indent-offset' is
935set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000936statement following it. If the search doesn't succeed going forward,
937it's tried again going backward."
938 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000939 (let (new-value
940 (start (point))
941 restart
942 (found nil)
943 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000944 (py-goto-initial-line)
945 (while (not (or found (eobp)))
946 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
947 (progn
948 (setq restart (point))
949 (py-goto-initial-line)
950 (if (py-statement-opens-block-p)
951 (setq found t)
952 (goto-char restart)))))
953 (if found
954 ()
955 (goto-char start)
956 (py-goto-initial-line)
957 (while (not (or found (bobp)))
958 (setq found
959 (and
960 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
961 (or (py-goto-initial-line) t) ; always true -- side effect
962 (py-statement-opens-block-p)))))
963 (setq colon-indent (current-indentation)
964 found (and found (zerop (py-next-statement 1)))
965 new-value (- (current-indentation) colon-indent))
966 (goto-char start)
967 (if found
968 (progn
969 (funcall (if global 'kill-local-variable 'make-local-variable)
970 'py-indent-offset)
971 (setq py-indent-offset new-value)
972 (message "%s value of py-indent-offset set to %d"
973 (if global "Global" "Local")
974 py-indent-offset))
975 (error "Sorry, couldn't guess a value for py-indent-offset"))))
976
977(defun py-shift-region (start end count)
978 (save-excursion
979 (goto-char end) (beginning-of-line) (setq end (point))
980 (goto-char start) (beginning-of-line) (setq start (point))
981 (indent-rigidly start end count)))
982
983(defun py-shift-region-left (start end &optional count)
984 "Shift region of Python code to the left.
985The 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
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000987shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988
989If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000990many columns. With no active region, outdent only the current line.
991You cannot outdent the region if any line is already at column zero."
992 (interactive
993 (let ((p (point))
994 (m (mark))
995 (arg current-prefix-arg))
996 (if m
997 (list (min p m) (max p m) arg)
998 (list p (save-excursion (forward-line 1) (point)) arg))))
999 ;; if any line is at column zero, don't shift the region
1000 (save-excursion
1001 (goto-char start)
1002 (while (< (point) end)
1003 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001004 (if (and (zerop (current-column))
1005 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001006 (error "Region is at left edge."))
1007 (forward-line 1)))
1008 (py-shift-region start end (- (prefix-numeric-value
1009 (or count py-indent-offset))))
1010 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011
1012(defun py-shift-region-right (start end &optional count)
1013 "Shift region of Python code to the right.
1014The lines from the line containing the start of the current region up
1015to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001016shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001017
1018If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001019many columns. With no active region, indent only the current line."
1020 (interactive
1021 (let ((p (point))
1022 (m (mark))
1023 (arg current-prefix-arg))
1024 (if m
1025 (list (min p m) (max p m) arg)
1026 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001028 (or count py-indent-offset)))
1029 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030
1031(defun py-indent-region (start end &optional indent-offset)
1032 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001033
Barry Warsaw7ae77681994-12-12 20:38:05 +00001034The lines from the line containing the start of the current region up
1035to (but not including) the line containing the end of the region are
1036reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001037character in the first column, the first line is left alone and the
1038rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001039region is reindented with respect to the (closest code or indenting
1040comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041
1042This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001043control structures are introduced or removed, or to reformat code
1044using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001045
1046If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001047the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001048used.
1049
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001050Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001051is called! This function does not compute proper indentation from
1052scratch (that's impossible in Python), it merely adjusts the existing
1053indentation to be correct in context.
1054
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001055Warning: This function really has no idea what to do with
1056non-indenting comment lines, and shifts them as if they were indenting
1057comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001058
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001059Special cases: whitespace is deleted from blank lines; continuation
1060lines are shifted by the same amount their initial line was shifted,
1061in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001062initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001063 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001064 (save-excursion
1065 (goto-char end) (beginning-of-line) (setq end (point-marker))
1066 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001067 (let ((py-indent-offset (prefix-numeric-value
1068 (or indent-offset py-indent-offset)))
1069 (indents '(-1)) ; stack of active indent levels
1070 (target-column 0) ; column to which to indent
1071 (base-shifted-by 0) ; amount last base line was shifted
1072 (indent-base (if (looking-at "[ \t\n]")
1073 (py-compute-indentation)
1074 0))
1075 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (while (< (point) end)
1077 (setq ci (current-indentation))
1078 ;; figure out appropriate target column
1079 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 ((or (eq (following-char) ?#) ; comment in column 1
1081 (looking-at "[ \t]*$")) ; entirely blank
1082 (setq target-column 0))
1083 ((py-continuation-line-p) ; shift relative to base line
1084 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001085 (t ; new base line
1086 (if (> ci (car indents)) ; going deeper; push it
1087 (setq indents (cons ci indents))
1088 ;; else we should have seen this indent before
1089 (setq indents (memq ci indents)) ; pop deeper indents
1090 (if (null indents)
1091 (error "Bad indentation in region, at line %d"
1092 (save-restriction
1093 (widen)
1094 (1+ (count-lines 1 (point)))))))
1095 (setq target-column (+ indent-base
1096 (* py-indent-offset
1097 (- (length indents) 2))))
1098 (setq base-shifted-by (- target-column ci))))
1099 ;; shift as needed
1100 (if (/= ci target-column)
1101 (progn
1102 (delete-horizontal-space)
1103 (indent-to target-column)))
1104 (forward-line 1))))
1105 (set-marker end nil))
1106
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001107
1108;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001109(defun py-previous-statement (count)
1110 "Go to the start of previous Python statement.
1111If the statement at point is the i'th Python statement, goes to the
1112start of statement i-COUNT. If there is no such statement, goes to the
1113first statement. Returns count of statements left to move.
1114`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001115 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116 (if (< count 0) (py-next-statement (- count))
1117 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001118 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001119 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001120 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001121 (> count 0)
1122 (zerop (forward-line -1))
1123 (py-goto-statement-at-or-above))
1124 (setq count (1- count)))
1125 (if (> count 0) (goto-char start)))
1126 count))
1127
1128(defun py-next-statement (count)
1129 "Go to the start of next Python statement.
1130If the statement at point is the i'th Python statement, goes to the
1131start of statement i+COUNT. If there is no such statement, goes to the
1132last statement. Returns count of statements left to move. `Statements'
1133do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001134 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001135 (if (< count 0) (py-previous-statement (- count))
1136 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001137 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001138 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001139 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001140 (> count 0)
1141 (py-goto-statement-below))
1142 (setq count (1- count)))
1143 (if (> count 0) (goto-char start)))
1144 count))
1145
1146(defun py-goto-block-up (&optional nomark)
1147 "Move up to start of current block.
1148Go to the statement that starts the smallest enclosing block; roughly
1149speaking, this will be the closest preceding statement that ends with a
1150colon and is indented less than the statement you started on. If
1151successful, also sets the mark to the starting point.
1152
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001153`\\[py-mark-block]' can be used afterward to mark the whole code
1154block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001155
1156If called from a program, the mark will not be set if optional argument
1157NOMARK is not nil."
1158 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001159 (let ((start (point))
1160 (found nil)
1161 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162 (py-goto-initial-line)
1163 ;; if on blank or non-indenting comment line, use the preceding stmt
1164 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1165 (progn
1166 (py-goto-statement-at-or-above)
1167 (setq found (py-statement-opens-block-p))))
1168 ;; search back for colon line indented less
1169 (setq initial-indent (current-indentation))
1170 (if (zerop initial-indent)
1171 ;; force fast exit
1172 (goto-char (point-min)))
1173 (while (not (or found (bobp)))
1174 (setq found
1175 (and
1176 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1177 (or (py-goto-initial-line) t) ; always true -- side effect
1178 (< (current-indentation) initial-indent)
1179 (py-statement-opens-block-p))))
1180 (if found
1181 (progn
1182 (or nomark (push-mark start))
1183 (back-to-indentation))
1184 (goto-char start)
1185 (error "Enclosing block not found"))))
1186
1187(defun beginning-of-python-def-or-class (&optional class)
1188 "Move point to start of def (or class, with prefix arg).
1189
1190Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001191arg, looks for a `class' instead. The docs assume the `def' case;
1192just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001193
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001194If point is in a def statement already, and after the `d', simply
1195moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001196
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001197Else (point is not in a def statement, or at or before the `d' of a
1198def statement), searches for the closest preceding def statement, and
1199leaves point at its start. If no such statement can be found, leaves
1200point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
1202Returns t iff a def statement is found by these rules.
1203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001204Note that doing this command repeatedly will take you closer to the
1205start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001206
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207If you want to mark the current def/class, see
1208`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001209 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001210 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1211 (start-of-line (progn (beginning-of-line) (point)))
1212 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001213 (if (or (/= start-of-stmt start-of-line)
1214 (not at-or-before-p))
1215 (end-of-line)) ; OK to match on this line
1216 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001217 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001218
1219(defun end-of-python-def-or-class (&optional class)
1220 "Move point beyond end of def (or class, with prefix arg) body.
1221
1222By default, looks for an appropriate `def'. If you supply a prefix arg,
1223looks for a `class' instead. The docs assume the `def' case; just
1224substitute `class' for `def' for the other case.
1225
1226If point is in a def statement already, this is the def we use.
1227
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001228Else if the def found by `\\[beginning-of-python-def-or-class]'
1229contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001230
1231Else we search forward for the closest following def, and use that.
1232
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001233If a def can be found by these rules, point is moved to the start of
1234the line immediately following the def block, and the position of the
1235start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001236
1237Else point is moved to the end of the buffer, and nil is returned.
1238
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001239Note that doing this command repeatedly will take you closer to the
1240end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001241
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001242If you want to mark the current def/class, see
1243`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001244 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001245 (let ((start (progn (py-goto-initial-line) (point)))
1246 (which (if class "class" "def"))
1247 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001248 ;; move point to start of appropriate def/class
1249 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1250 (setq state 'at-beginning)
1251 ;; else see if beginning-of-python-def-or-class hits container
1252 (if (and (beginning-of-python-def-or-class class)
1253 (progn (py-goto-beyond-block)
1254 (> (point) start)))
1255 (setq state 'at-end)
1256 ;; else search forward
1257 (goto-char start)
1258 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1259 (progn (setq state 'at-beginning)
1260 (beginning-of-line)))))
1261 (cond
1262 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1263 ((eq state 'at-end) t)
1264 ((eq state 'not-found) nil)
1265 (t (error "internal error in end-of-python-def-or-class")))))
1266
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001267
1268;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001269(defun py-mark-block (&optional extend just-move)
1270 "Mark following block of lines. With prefix arg, mark structure.
1271Easier to use than explain. It sets the region to an `interesting'
1272block of succeeding lines. If point is on a blank line, it goes down to
1273the next non-blank line. That will be the start of the region. The end
1274of the region depends on the kind of line at the start:
1275
1276 - If a comment, the region will include all succeeding comment lines up
1277 to (but not including) the next non-comment line (if any).
1278
1279 - Else if a prefix arg is given, and the line begins one of these
1280 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281
1282 if elif else try except finally for while def class
1283
Barry Warsaw7ae77681994-12-12 20:38:05 +00001284 the region will be set to the body of the structure, including
1285 following blocks that `belong' to it, but excluding trailing blank
1286 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001287 and all (if any) of the following `except' and `finally' blocks
1288 that belong to the `try' structure will be in the region. Ditto
1289 for if/elif/else, for/else and while/else structures, and (a bit
1290 degenerate, since they're always one-block structures) def and
1291 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001292
1293 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001294 block (see list above), and the block is not a `one-liner' (i.e.,
1295 the statement ends with a colon, not with code), the region will
1296 include all succeeding lines up to (but not including) the next
1297 code statement (if any) that's indented no more than the starting
1298 line, except that trailing blank and comment lines are excluded.
1299 E.g., if the starting line begins a multi-statement `def'
1300 structure, the region will be set to the full function definition,
1301 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001302
1303 - Else the region will include all succeeding lines up to (but not
1304 including) the next blank line, or code or indenting-comment line
1305 indented strictly less than the starting line. Trailing indenting
1306 comment lines are included in this case, but not trailing blank
1307 lines.
1308
1309A msg identifying the location of the mark is displayed in the echo
1310area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1311
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001312If called from a program, optional argument EXTEND plays the role of
1313the prefix arg, and if optional argument JUST-MOVE is not nil, just
1314moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001315 (interactive "P") ; raw prefix arg
1316 (py-goto-initial-line)
1317 ;; skip over blank lines
1318 (while (and
1319 (looking-at "[ \t]*$") ; while blank line
1320 (not (eobp))) ; & somewhere to go
1321 (forward-line 1))
1322 (if (eobp)
1323 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001324 (let ((initial-pos (point))
1325 (initial-indent (current-indentation))
1326 last-pos ; position of last stmt in region
1327 (followers
1328 '((if elif else) (elif elif else) (else)
1329 (try except finally) (except except) (finally)
1330 (for else) (while else)
1331 (def) (class) ) )
1332 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001333
1334 (cond
1335 ;; if comment line, suck up the following comment lines
1336 ((looking-at "[ \t]*#")
1337 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1338 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1339 (setq last-pos (point)))
1340
1341 ;; else if line is a block line and EXTEND given, suck up
1342 ;; the whole structure
1343 ((and extend
1344 (setq first-symbol (py-suck-up-first-keyword) )
1345 (assq first-symbol followers))
1346 (while (and
1347 (or (py-goto-beyond-block) t) ; side effect
1348 (forward-line -1) ; side effect
1349 (setq last-pos (point)) ; side effect
1350 (py-goto-statement-below)
1351 (= (current-indentation) initial-indent)
1352 (setq next-symbol (py-suck-up-first-keyword))
1353 (memq next-symbol (cdr (assq first-symbol followers))))
1354 (setq first-symbol next-symbol)))
1355
1356 ;; else if line *opens* a block, search for next stmt indented <=
1357 ((py-statement-opens-block-p)
1358 (while (and
1359 (setq last-pos (point)) ; always true -- side effect
1360 (py-goto-statement-below)
1361 (> (current-indentation) initial-indent))
1362 nil))
1363
1364 ;; else plain code line; stop at next blank line, or stmt or
1365 ;; indenting comment line indented <
1366 (t
1367 (while (and
1368 (setq last-pos (point)) ; always true -- side effect
1369 (or (py-goto-beyond-final-line) t)
1370 (not (looking-at "[ \t]*$")) ; stop at blank line
1371 (or
1372 (>= (current-indentation) initial-indent)
1373 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1374 nil)))
1375
1376 ;; skip to end of last stmt
1377 (goto-char last-pos)
1378 (py-goto-beyond-final-line)
1379
1380 ;; set mark & display
1381 (if just-move
1382 () ; just return
1383 (push-mark (point) 'no-msg)
1384 (forward-line -1)
1385 (message "Mark set after: %s" (py-suck-up-leading-text))
1386 (goto-char initial-pos))))
1387
1388(defun mark-python-def-or-class (&optional class)
1389 "Set region to body of def (or class, with prefix arg) enclosing point.
1390Pushes the current mark, then point, on the mark ring (all language
1391modes do this, but although it's handy it's never documented ...).
1392
1393In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001394hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1395`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396
1397And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001398Turned out that was more confusing than useful: the `goto start' and
1399`goto end' commands are usually used to search through a file, and
1400people expect them to act a lot like `search backward' and `search
1401forward' string-search commands. But because Python `def' and `class'
1402can nest to arbitrary levels, finding the smallest def containing
1403point cannot be done via a simple backward search: the def containing
1404point may not be the closest preceding def, or even the closest
1405preceding def that's indented less. The fancy algorithm required is
1406appropriate for the usual uses of this `mark' command, but not for the
1407`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001408
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409So the def marked by this command may not be the one either of the
1410`goto' commands find: If point is on a blank or non-indenting comment
1411line, moves back to start of the closest preceding code statement or
1412indenting comment line. If this is a `def' statement, that's the def
1413we use. Else searches for the smallest enclosing `def' block and uses
1414that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001415
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001416When an enclosing def is found: The mark is left immediately beyond
1417the last line of the def block. Point is left at the start of the
1418def, except that: if the def is preceded by a number of comment lines
1419followed by (at most) one optional blank line, point is left at the
1420start of the comments; else if the def is preceded by a blank line,
1421point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422
1423The intent is to mark the containing def/class and its associated
1424documentation, to make moving and duplicating functions and classes
1425pleasant."
1426 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001427 (let ((start (point))
1428 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001429 (push-mark start)
1430 (if (not (py-go-up-tree-to-keyword which))
1431 (progn (goto-char start)
1432 (error "Enclosing %s not found" which))
1433 ;; else enclosing def/class found
1434 (setq start (point))
1435 (py-goto-beyond-block)
1436 (push-mark (point))
1437 (goto-char start)
1438 (if (zerop (forward-line -1)) ; if there is a preceding line
1439 (progn
1440 (if (looking-at "[ \t]*$") ; it's blank
1441 (setq start (point)) ; so reset start point
1442 (goto-char start)) ; else try again
1443 (if (zerop (forward-line -1))
1444 (if (looking-at "[ \t]*#") ; a comment
1445 ;; look back for non-comment line
1446 ;; tricky: note that the regexp matches a blank
1447 ;; line, cuz \n is in the 2nd character class
1448 (and
1449 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1450 (forward-line 1))
1451 ;; no comment, so go back
1452 (goto-char start))))))))
1453
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001454;; ripped from cc-mode
1455(defun py-forward-into-nomenclature (&optional arg)
1456 "Move forward to end of a nomenclature section or word.
1457With arg, to it arg times.
1458
1459A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1460 (interactive "p")
1461 (let ((case-fold-search nil))
1462 (if (> arg 0)
Barry Warsawc846f461996-07-25 18:53:17 +00001463 (re-search-forward "\\W*\\([A-Z_]*[a-z0-9]*\\)" (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001464 (while (and (< arg 0)
1465 (re-search-backward
1466 "\\(\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\W\\w+\\)"
1467 (point-min) 0))
1468 (forward-char 1)
1469 (setq arg (1+ arg)))))
1470 (py-keep-region-active))
1471
1472(defun py-backward-into-nomenclature (&optional arg)
1473 "Move backward to beginning of a nomenclature section or word.
1474With optional ARG, move that many times. If ARG is negative, move
1475forward.
1476
1477A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1478 (interactive "p")
1479 (py-forward-into-nomenclature (- arg))
1480 (py-keep-region-active))
1481
1482
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001483
1484;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001485
1486;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001487;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1488;; out of the right places, along with the keys they're on & current
1489;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001490(defun py-dump-help-string (str)
1491 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492 (let ((locals (buffer-local-variables))
1493 funckind funcname func funcdoc
1494 (start 0) mstart end
1495 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001496 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1497 (setq mstart (match-beginning 0) end (match-end 0)
1498 funckind (substring str (match-beginning 1) (match-end 1))
1499 funcname (substring str (match-beginning 2) (match-end 2))
1500 func (intern funcname))
1501 (princ (substitute-command-keys (substring str start mstart)))
1502 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503 ((equal funckind "c") ; command
1504 (setq funcdoc (documentation func)
1505 keys (concat
1506 "Key(s): "
1507 (mapconcat 'key-description
1508 (where-is-internal func py-mode-map)
1509 ", "))))
1510 ((equal funckind "v") ; variable
1511 (setq funcdoc (substitute-command-keys
1512 (get func 'variable-documentation))
1513 keys (if (assq func locals)
1514 (concat
1515 "Local/Global values: "
1516 (prin1-to-string (symbol-value func))
1517 " / "
1518 (prin1-to-string (default-value func)))
1519 (concat
1520 "Value: "
1521 (prin1-to-string (symbol-value func))))))
1522 (t ; unexpected
1523 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001524 (princ (format "\n-> %s:\t%s\t%s\n\n"
1525 (if (equal funckind "c") "Command" "Variable")
1526 funcname keys))
1527 (princ funcdoc)
1528 (terpri)
1529 (setq start end))
1530 (princ (substitute-command-keys (substring str start))))
1531 (print-help-return-message)))
1532
1533(defun py-describe-mode ()
1534 "Dump long form of Python-mode docs."
1535 (interactive)
1536 (py-dump-help-string "Major mode for editing Python files.
1537Knows about Python indentation, tokens, comments and continuation lines.
1538Paragraphs are separated by blank lines only.
1539
1540Major sections below begin with the string `@'; specific function and
1541variable docs begin with `->'.
1542
1543@EXECUTING PYTHON CODE
1544
1545\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1546\\[py-execute-region]\tsends the current region
1547\\[py-shell]\tstarts a Python interpreter window; this will be used by
1548\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1549%c:py-execute-buffer
1550%c:py-execute-region
1551%c:py-shell
1552
1553@VARIABLES
1554
1555py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001556py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001557
1558py-python-command\tshell command to invoke Python interpreter
1559py-scroll-process-buffer\talways scroll Python process buffer
1560py-temp-directory\tdirectory used for temp files (if needed)
1561
1562py-beep-if-tab-change\tring the bell if tab-width is changed
1563%v:py-indent-offset
1564%v:py-block-comment-prefix
1565%v:py-python-command
1566%v:py-scroll-process-buffer
1567%v:py-temp-directory
1568%v:py-beep-if-tab-change
1569
1570@KINDS OF LINES
1571
1572Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573preceding line ends with a backslash that's not part of a comment, or
1574the paren/bracket/brace nesting level at the start of the line is
1575non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001576
1577An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001578possibly blanks or tabs), a `comment line' (leftmost non-blank
1579character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001580
1581Comment Lines
1582
1583Although all comment lines are treated alike by Python, Python mode
1584recognizes two kinds that act differently with respect to indentation.
1585
1586An `indenting comment line' is a comment line with a blank, tab or
1587nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001588treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001589indenting comment line will be indented like the comment line. All
1590other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001591following the initial `#') are `non-indenting comment lines', and
1592their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001593
1594Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001595whenever possible. Non-indenting comment lines are useful in cases
1596like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001597
1598\ta = b # a very wordy single-line comment that ends up being
1599\t #... continued onto another line
1600
1601\tif a == b:
1602##\t\tprint 'panic!' # old code we've `commented out'
1603\t\treturn a
1604
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001605Since the `#...' and `##' comment lines have a non-whitespace
1606character following the initial `#', Python mode ignores them when
1607computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001608
1609Continuation Lines and Statements
1610
1611The Python-mode commands generally work on statements instead of on
1612individual lines, where a `statement' is a comment or blank line, or a
1613code line and all of its following continuation lines (if any)
1614considered as a single logical unit. The commands in this mode
1615generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001616statement containing point, even if point happens to be in the middle
1617of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001618
1619
1620@INDENTATION
1621
1622Primarily for entering new code:
1623\t\\[indent-for-tab-command]\t indent line appropriately
1624\t\\[py-newline-and-indent]\t insert newline, then indent
1625\t\\[py-delete-char]\t reduce indentation, or delete single character
1626
1627Primarily for reindenting existing code:
1628\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1629\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1630
1631\t\\[py-indent-region]\t reindent region to match its context
1632\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1633\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1634
1635Unlike most programming languages, Python uses indentation, and only
1636indentation, to specify block structure. Hence the indentation supplied
1637automatically by Python-mode is just an educated guess: only you know
1638the block structure you intend, so only you can supply correct
1639indentation.
1640
1641The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1642the indentation of preceding statements. E.g., assuming
1643py-indent-offset is 4, after you enter
1644\tif a > 0: \\[py-newline-and-indent]
1645the cursor will be moved to the position of the `_' (_ is not a
1646character in the file, it's just used here to indicate the location of
1647the cursor):
1648\tif a > 0:
1649\t _
1650If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1651to
1652\tif a > 0:
1653\t c = d
1654\t _
1655Python-mode cannot know whether that's what you intended, or whether
1656\tif a > 0:
1657\t c = d
1658\t_
1659was your intent. In general, Python-mode either reproduces the
1660indentation of the (closest code or indenting-comment) preceding
1661statement, or adds an extra py-indent-offset blanks if the preceding
1662statement has `:' as its last significant (non-whitespace and non-
1663comment) character. If the suggested indentation is too much, use
1664\\[py-delete-char] to reduce it.
1665
1666Continuation lines are given extra indentation. If you don't like the
1667suggested indentation, change it to something you do like, and Python-
1668mode will strive to indent later lines of the statement in the same way.
1669
1670If a line is a continuation line by virtue of being in an unclosed
1671paren/bracket/brace structure (`list', for short), the suggested
1672indentation depends on whether the current line contains the first item
1673in the list. If it does, it's indented py-indent-offset columns beyond
1674the indentation of the line containing the open bracket. If you don't
1675like that, change it by hand. The remaining items in the list will mimic
1676whatever indentation you give to the first item.
1677
1678If a line is a continuation line because the line preceding it ends with
1679a backslash, the third and following lines of the statement inherit their
1680indentation from the line preceding them. The indentation of the second
1681line in the statement depends on the form of the first (base) line: if
1682the base line is an assignment statement with anything more interesting
1683than the backslash following the leftmost assigning `=', the second line
1684is indented two columns beyond that `='. Else it's indented to two
1685columns beyond the leftmost solid chunk of non-whitespace characters on
1686the base line.
1687
1688Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1689repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1690structure you intend.
1691%c:indent-for-tab-command
1692%c:py-newline-and-indent
1693%c:py-delete-char
1694
1695
1696The next function may be handy when editing code you didn't write:
1697%c:py-guess-indent-offset
1698
1699
1700The remaining `indent' functions apply to a region of Python code. They
1701assume the block structure (equals indentation, in Python) of the region
1702is correct, and alter the indentation in various ways while preserving
1703the block structure:
1704%c:py-indent-region
1705%c:py-shift-region-left
1706%c:py-shift-region-right
1707
1708@MARKING & MANIPULATING REGIONS OF CODE
1709
1710\\[py-mark-block]\t mark block of lines
1711\\[mark-python-def-or-class]\t mark smallest enclosing def
1712\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001713\\[comment-region]\t comment out region of code
1714\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715%c:py-mark-block
1716%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001717%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718
1719@MOVING POINT
1720
1721\\[py-previous-statement]\t move to statement preceding point
1722\\[py-next-statement]\t move to statement following point
1723\\[py-goto-block-up]\t move up to start of current block
1724\\[beginning-of-python-def-or-class]\t move to start of def
1725\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1726\\[end-of-python-def-or-class]\t move to end of def
1727\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1728
1729The first two move to one statement beyond the statement that contains
1730point. A numeric prefix argument tells them to move that many
1731statements instead. Blank lines, comment lines, and continuation lines
1732do not count as `statements' for these commands. So, e.g., you can go
1733to the first code statement in a file by entering
1734\t\\[beginning-of-buffer]\t to move to the top of the file
1735\t\\[py-next-statement]\t to skip over initial comments and blank lines
1736Or do `\\[py-previous-statement]' with a huge prefix argument.
1737%c:py-previous-statement
1738%c:py-next-statement
1739%c:py-goto-block-up
1740%c:beginning-of-python-def-or-class
1741%c:end-of-python-def-or-class
1742
1743@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1744
1745`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1746
1747`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1748overall class and def structure of a module.
1749
1750`\\[back-to-indentation]' moves point to a line's first non-blank character.
1751
1752`\\[indent-relative]' is handy for creating odd indentation.
1753
1754@OTHER EMACS HINTS
1755
1756If you don't like the default value of a variable, change its value to
1757whatever you do like by putting a `setq' line in your .emacs file.
1758E.g., to set the indentation increment to 4, put this line in your
1759.emacs:
1760\t(setq py-indent-offset 4)
1761To see the value of a variable, do `\\[describe-variable]' and enter the variable
1762name at the prompt.
1763
1764When entering a key sequence like `C-c C-n', it is not necessary to
1765release the CONTROL key after doing the `C-c' part -- it suffices to
1766press the CONTROL key, press and release `c' (while still holding down
1767CONTROL), press and release `n' (while still holding down CONTROL), &
1768then release CONTROL.
1769
1770Entering Python mode calls with no arguments the value of the variable
1771`python-mode-hook', if that value exists and is not nil; for backward
1772compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1773the Elisp manual for details.
1774
1775Obscure: When python-mode is first loaded, it looks for all bindings
1776to newline-and-indent in the global keymap, and shadows them with
1777local bindings to py-newline-and-indent."))
1778
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001779
1780;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001781(defvar py-parse-state-re
1782 (concat
1783 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1784 "\\|"
1785 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001786
Barry Warsaw7ae77681994-12-12 20:38:05 +00001787;; returns the parse state at point (see parse-partial-sexp docs)
1788(defun py-parse-state ()
1789 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001790 (let ((here (point))
1791 pps done)
1792 (while (not done)
1793 ;; back up to the first preceding line (if any; else start of
1794 ;; buffer) that begins with a popular Python keyword, or a
1795 ;; non- whitespace and non-comment character. These are good
1796 ;; places to start parsing to see whether where we started is
1797 ;; at a non-zero nesting level. It may be slow for people who
1798 ;; write huge code blocks or huge lists ... tough beans.
1799 (re-search-backward py-parse-state-re nil 'move)
1800 (beginning-of-line)
1801 (save-excursion
1802 (setq pps (parse-partial-sexp (point) here)))
1803 ;; make sure we don't land inside a triple-quoted string
1804 (setq done (or (not (nth 3 pps)) (bobp))))
1805 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001806
1807;; if point is at a non-zero nesting level, returns the number of the
1808;; character that opens the smallest enclosing unclosed list; else
1809;; returns nil.
1810(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001812 (if (zerop (car status))
1813 nil ; not in a nest
1814 (car (cdr status))))) ; char# of open bracket
1815
1816;; t iff preceding line ends with backslash that's not in a comment
1817(defun py-backslash-continuation-line-p ()
1818 (save-excursion
1819 (beginning-of-line)
1820 (and
1821 ;; use a cheap test first to avoid the regexp if possible
1822 ;; use 'eq' because char-after may return nil
1823 (eq (char-after (- (point) 2)) ?\\ )
1824 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826 (looking-at py-continued-re))))
1827
1828;; t iff current line is a continuation line
1829(defun py-continuation-line-p ()
1830 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001831 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832 (or (py-backslash-continuation-line-p)
1833 (py-nesting-level))))
1834
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001835;; go to initial line of current statement; usually this is the line
1836;; we're on, but if we're on the 2nd or following lines of a
1837;; continuation block, we need to go up to the first line of the
1838;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840;; Tricky: We want to avoid quadratic-time behavior for long continued
1841;; blocks, whether of the backslash or open-bracket varieties, or a
1842;; mix of the two. The following manages to do that in the usual
1843;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844(defun py-goto-initial-line ()
1845 (let ( open-bracket-pos )
1846 (while (py-continuation-line-p)
1847 (beginning-of-line)
1848 (if (py-backslash-continuation-line-p)
1849 (while (py-backslash-continuation-line-p)
1850 (forward-line -1))
1851 ;; else zip out of nested brackets/braces/parens
1852 (while (setq open-bracket-pos (py-nesting-level))
1853 (goto-char open-bracket-pos)))))
1854 (beginning-of-line))
1855
1856;; go to point right beyond final line of current statement; usually
1857;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858;; statement we need to skip over the continuation lines. Tricky:
1859;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860(defun py-goto-beyond-final-line ()
1861 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 (while (and (py-continuation-line-p)
1864 (not (eobp)))
1865 ;; skip over the backslash flavor
1866 (while (and (py-backslash-continuation-line-p)
1867 (not (eobp)))
1868 (forward-line 1))
1869 ;; if in nest, zip to the end of the nest
1870 (setq state (py-parse-state))
1871 (if (and (not (zerop (car state)))
1872 (not (eobp)))
1873 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001874 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001875 ;; the 3rd argument should be plain 0
1876 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1877 nil state)
1878 (forward-line 1))))))
1879
1880;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001881;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001882(defun py-statement-opens-block-p ()
1883 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001884 (let ((start (point))
1885 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1886 (searching t)
1887 (answer nil)
1888 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889 (goto-char start)
1890 (while searching
1891 ;; look for a colon with nothing after it except whitespace, and
1892 ;; maybe a comment
1893 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1894 finish t)
1895 (if (eq (point) finish) ; note: no `else' clause; just
1896 ; keep searching if we're not at
1897 ; the end yet
1898 ;; sure looks like it opens a block -- but it might
1899 ;; be in a comment
1900 (progn
1901 (setq searching nil) ; search is done either way
1902 (setq state (parse-partial-sexp start
1903 (match-beginning 0)))
1904 (setq answer (not (nth 4 state)))))
1905 ;; search failed: couldn't find another interesting colon
1906 (setq searching nil)))
1907 answer)))
1908
1909;; go to point right beyond final line of block begun by the current
1910;; line. This is the same as where py-goto-beyond-final-line goes
1911;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001912;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001913(defun py-goto-beyond-block ()
1914 (if (py-statement-opens-block-p)
1915 (py-mark-block nil 'just-move)
1916 (py-goto-beyond-final-line)))
1917
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918;; go to start of first statement (not blank or comment or
1919;; continuation line) at or preceding point. returns t if there is
1920;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001921(defun py-goto-statement-at-or-above ()
1922 (py-goto-initial-line)
1923 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924 ;; skip back over blank & comment lines
1925 ;; note: will skip a blank or comment line that happens to be
1926 ;; a continuation line too
1927 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1928 (progn (py-goto-initial-line) t)
1929 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930 t))
1931
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001932;; go to start of first statement (not blank or comment or
1933;; continuation line) following the statement containing point returns
1934;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001935(defun py-goto-statement-below ()
1936 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001937 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938 (py-goto-beyond-final-line)
1939 (while (and
1940 (looking-at py-blank-or-comment-re)
1941 (not (eobp)))
1942 (forward-line 1))
1943 (if (eobp)
1944 (progn (goto-char start) nil)
1945 t)))
1946
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001947;; go to start of statement, at or preceding point, starting with
1948;; keyword KEY. Skips blank lines and non-indenting comments upward
1949;; first. If that statement starts with KEY, done, else go back to
1950;; first enclosing block starting with KEY. If successful, leaves
1951;; point at the start of the KEY line & returns t. Else leaves point
1952;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001953(defun py-go-up-tree-to-keyword (key)
1954 ;; skip blanks and non-indenting #
1955 (py-goto-initial-line)
1956 (while (and
1957 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1958 (zerop (forward-line -1))) ; go back
1959 nil)
1960 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961 (let* ((re (concat "[ \t]*" key "\\b"))
1962 (case-fold-search nil) ; let* so looking-at sees this
1963 (found (looking-at re))
1964 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001965 (while (not (or found dead))
1966 (condition-case nil ; in case no enclosing block
1967 (py-goto-block-up 'no-mark)
1968 (error (setq dead t)))
1969 (or dead (setq found (looking-at re))))
1970 (beginning-of-line)
1971 found))
1972
1973;; return string in buffer from start of indentation to end of line;
1974;; prefix "..." if leading whitespace was skipped
1975(defun py-suck-up-leading-text ()
1976 (save-excursion
1977 (back-to-indentation)
1978 (concat
1979 (if (bolp) "" "...")
1980 (buffer-substring (point) (progn (end-of-line) (point))))))
1981
1982;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1983;; as a Lisp symbol; return nil if none
1984(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001985 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001986 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1987 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1988 nil)))
1989
1990(defun py-make-temp-name ()
1991 (make-temp-name
1992 (concat (file-name-as-directory py-temp-directory) "python")))
1993
1994(defun py-delete-file-silently (fname)
1995 (condition-case nil
1996 (delete-file fname)
1997 (error nil)))
1998
1999(defun py-kill-emacs-hook ()
2000 ;; delete our temp files
2001 (while py-file-queue
2002 (py-delete-file-silently (car py-file-queue))
2003 (setq py-file-queue (cdr py-file-queue)))
2004 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2005 ;; run the hook we inherited, if any
2006 (and py-inherited-kill-emacs-hook
2007 (funcall py-inherited-kill-emacs-hook))))
2008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002009;; make PROCESS's buffer visible, append STRING to it, and force
2010;; display; also make shell-mode believe the user typed this string,
2011;; so that kill-output-from-shell and show-output-from-shell work
2012;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014 (let ((cbuf (current-buffer))
2015 (pbuf (process-buffer process))
2016 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002017 (set-buffer pbuf)
2018 (goto-char (point-max))
2019 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002020 (if (not (or py-this-is-emacs-19-p
2021 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022 (move-marker last-input-start (point))) ; muck w/ shell-mode
2023 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002024 (if (not (or py-this-is-emacs-19-p
2025 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002026 (move-marker last-input-end (point))) ; muck w/ shell-mode
2027 (set-buffer cbuf))
2028 (sit-for 0))
2029
Barry Warsaw74d9cc51995-03-08 22:05:16 +00002030(defun py-keep-region-active ()
2031 ;; do whatever is necessary to keep the region active in XEmacs.
2032 ;; Ignore byte-compiler warnings you might see. Also note that
2033 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
2034 ;; require us to take explicit action.
2035 (and (boundp 'zmacs-region-stays)
2036 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002037
2038
Barry Warsaw850437a1995-03-08 21:50:28 +00002039(defconst py-version "$Revision$"
2040 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002041(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002042 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002043
Barry Warsaw850437a1995-03-08 21:50:28 +00002044(defun py-version ()
2045 "Echo the current version of `python-mode' in the minibuffer."
2046 (interactive)
2047 (message "Using `python-mode' version %s" py-version)
2048 (py-keep-region-active))
2049
2050;; only works under Emacs 19
2051;(eval-when-compile
2052; (require 'reporter))
2053
2054(defun py-submit-bug-report (enhancement-p)
2055 "Submit via mail a bug report on `python-mode'.
2056With \\[universal-argument] just submit an enhancement request."
2057 (interactive
2058 (list (not (y-or-n-p
2059 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002060 (let ((reporter-prompt-for-summary-p (if enhancement-p
2061 "(Very) brief summary: "
2062 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002063 (require 'reporter)
2064 (reporter-submit-bug-report
2065 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002066 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002067 ;; varlist
2068 (if enhancement-p nil
2069 '(py-python-command
2070 py-indent-offset
2071 py-block-comment-prefix
2072 py-scroll-process-buffer
2073 py-temp-directory
2074 py-beep-if-tab-change))
2075 nil ;pre-hooks
2076 nil ;post-hooks
2077 "Dear Barry,") ;salutation
2078 (if enhancement-p nil
2079 (set-mark (point))
2080 (insert
2081"Please replace this text with a sufficiently large code sample\n\
2082and an exact recipe so that I can reproduce your problem. Failure\n\
2083to do so may mean a greater delay in fixing your bug.\n\n")
2084 (exchange-point-and-mark)
2085 (py-keep-region-active))))
2086
2087
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002088;; arrange to kill temp files when Emacs exists
2089(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2090 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2091 ;; have to trust that other people are as respectful of our hook
2092 ;; fiddling as we are of theirs
2093 (if (boundp 'py-inherited-kill-emacs-hook)
2094 ;; we were loaded before -- trust others not to have screwed us
2095 ;; in the meantime (no choice, really)
2096 nil
2097 ;; else arrange for our hook to run theirs
2098 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2099 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2100
2101
2102
2103(provide 'python-mode)
2104;;; python-mode.el ends here