blob: 7db9f38515aeeeb5556205c7ed29179a248f8fde [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 Warsawc08a9491996-07-31 22:27:58 +000046;;
47;; But you better be sure you're version of Emacs supports
48;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
49;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000050
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000051;; Here's a brief list of recent additions/improvements:
52;;
53;; - Wrapping and indentation within triple quote strings should work
54;; properly now.
55;; - `Standard' bug reporting mechanism (use C-c C-b)
56;; - py-mark-block was moved to C-c C-m
57;; - C-c C-v shows you the python-mode version
58;; - a basic python-font-lock-keywords has been added for Emacs 19
59;; font-lock colorizations.
60;; - proper interaction with pending-del and del-sel modes.
61;; - New py-electric-colon (:) command for improved outdenting. Also
62;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw03970731996-07-03 23:12:52 +000063;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000064;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
65;; M-f and M-b respectively.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000066
Barry Warsaw7b0f5681995-03-08 21:33:04 +000067;; Here's a brief to do list:
68;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000069;; - Better integration with gud-mode for debugging.
70;; - Rewrite according to GNU Emacs Lisp standards.
71;; - py-delete-char should obey numeric arguments.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000072;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000073;; - possibly force indent-tabs-mode == nil, and add a
74;; write-file-hooks that runs untabify on the whole buffer (to work
75;; around potential tab/space mismatch problems). In practice this
76;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000077;; - have py-execute-region on indented code act as if the region is
78;; left justified. Avoids syntax errors.
Barry Warsaw7ae77681994-12-12 20:38:05 +000079
Barry Warsaw7b0f5681995-03-08 21:33:04 +000080;; If you can think of more things you'd like to see, drop me a line.
81;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
82;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000083;; Note that I only test things on XEmacs. If you port stuff to FSF
84;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
85;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000086
Barry Warsaw7b0f5681995-03-08 21:33:04 +000087;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000088;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000089;; |Major mode for editing Python programs
90;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000091
Barry Warsaw7b0f5681995-03-08 21:33:04 +000092;;; Code:
93
94
95;; user definable variables
96;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000097
98(defvar py-python-command "python"
99 "*Shell command used to start Python interpreter.")
100
Barry Warsaw17914f41995-11-03 18:25:15 +0000101(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +0000102 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000103Note that `\\[py-guess-indent-offset]' can usually guess a good value
104when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw095e9c61995-09-19 20:01:42 +0000106(defvar py-align-multiline-strings-p t
107 "*Flag describing how multiline triple quoted strings are aligned.
108When this flag is non-nil, continuation lines are lined up under the
109preceding line's indentation. When this flag is nil, continuation
110lines are aligned to column zero.")
111
Barry Warsaw7ae77681994-12-12 20:38:05 +0000112(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000113 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000114This should follow the convention for non-indenting comment lines so
115that the indentation commands won't get confused (i.e., the string
116should be of the form `#x...' where `x' is not a blank or a tab, and
117`...' is arbitrary).")
118
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000119(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000120 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000121
Barry Warsaw6d627751996-03-06 18:41:38 +0000122When nil, all comment lines are skipped for indentation purposes, and
123in Emacs 19, a faster algorithm is used.
124
125When t, lines that begin with a single `#' are a hint to subsequent
126line indentation. If the previous line is such a comment line (as
127opposed to one that starts with `py-block-comment-prefix'), then it's
128indentation is used as a hint for this line's indentation. Lines that
129begin with `py-block-comment-prefix' are ignored for indentation
130purposes.
131
132When not nil or t, comment lines that begin with a `#' are used as
133indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000134
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135(defvar py-scroll-process-buffer t
136 "*Scroll Python process buffer as output arrives.
137If nil, the Python process buffer acts, with respect to scrolling, like
138Shell-mode buffers normally act. This is surprisingly complicated and
139so won't be explained here; in fact, you can't get the whole story
140without studying the Emacs C code.
141
142If non-nil, the behavior is different in two respects (which are
143slightly inaccurate in the interest of brevity):
144
145 - If the buffer is in a window, and you left point at its end, the
146 window will scroll as new output arrives, and point will move to the
147 buffer's end, even if the window is not the selected window (that
148 being the one the cursor is in). The usual behavior for shell-mode
149 windows is not to scroll, and to leave point where it was, if the
150 buffer is in a window other than the selected window.
151
152 - If the buffer is not visible in any window, and you left point at
153 its end, the buffer will be popped into a window as soon as more
154 output arrives. This is handy if you have a long-running
155 computation and don't want to tie up screen area waiting for the
156 output. The usual behavior for a shell-mode buffer is to stay
157 invisible until you explicitly visit it.
158
159Note the `and if you left point at its end' clauses in both of the
160above: you can `turn off' the special behaviors while output is in
161progress, by visiting the Python buffer and moving point to anywhere
162besides the end. Then the buffer won't scroll, point will remain where
163you leave it, and if you hide the buffer it will stay hidden until you
164visit it again. You can enable and disable the special behaviors as
165often as you like, while output is in progress, by (respectively) moving
166point to, or away from, the end of the buffer.
167
168Warning: If you expect a large amount of output, you'll probably be
169happier setting this option to nil.
170
171Obscure: `End of buffer' above should really say `at or beyond the
172process mark', but if you know what that means you didn't need to be
173told <grin>.")
174
175(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000176 (let ((ok '(lambda (x)
177 (and x
178 (setq x (expand-file-name x)) ; always true
179 (file-directory-p x)
180 (file-writable-p x)
181 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000182 (or (funcall ok (getenv "TMPDIR"))
183 (funcall ok "/usr/tmp")
184 (funcall ok "/tmp")
185 (funcall ok ".")
186 (error
187 "Couldn't find a usable temp directory -- set py-temp-directory")))
188 "*Directory used for temp files created by a *Python* process.
189By default, the first directory from this list that exists and that you
190can write into: the value (if any) of the environment variable TMPDIR,
191/usr/tmp, /tmp, or the current directory.")
192
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000193(defvar py-beep-if-tab-change t
194 "*Ring the bell if tab-width is changed.
195If a comment of the form
196
197 \t# vi:set tabsize=<number>:
198
199is found before the first code line when the file is entered, and the
200current value of (the general Emacs variable) `tab-width' does not
201equal <number>, `tab-width' is set to <number>, a message saying so is
202displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
203the Emacs bell is also rung as a warning.")
204
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000205(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000206 (let* ((keywords '("access" "and" "break" "class"
207 "continue" "def" "del" "elif"
208 "else:" "except" "except:" "exec"
209 "finally:" "for" "from" "global"
210 "if" "import" "in" "is"
211 "lambda" "not" "or" "pass"
212 "print" "raise" "return" "try:"
213 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000214 ))
215 (kwregex (mapconcat 'identity keywords "\\|")))
216 (list
217 ;; keywords not at beginning of line
218 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
219 ;; keywords at beginning of line. i don't think regexps are
220 ;; powerful enough to handle these two cases in one regexp.
221 ;; prove me wrong!
222 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
223 ;; classes
224 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
225 1 font-lock-type-face)
226 ;; functions
227 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
228 1 font-lock-function-name-face)
229 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000230 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000231
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000232
233;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
234;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
235
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000236(make-variable-buffer-local 'py-indent-offset)
237
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000238;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
239;; seems to be the standard way of checking this.
240;; BAW - This is *not* the right solution. When at all possible,
241;; instead of testing for the version of Emacs, use feature tests.
242
243(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
244(setq py-this-is-emacs-19-p
245 (and
246 (not py-this-is-lucid-emacs-p)
247 (string-match "^19\\." emacs-version)))
248
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249;; have to bind py-file-queue before installing the kill-emacs hook
250(defvar py-file-queue nil
251 "Queue of Python temp files awaiting execution.
252Currently-active file is at the head of the list.")
253
254;; define a mode-specific abbrev table for those who use such things
255(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000257(define-abbrev-table 'python-mode-abbrev-table nil)
258
Barry Warsaw7ae77681994-12-12 20:38:05 +0000259(defvar python-mode-hook nil
260 "*Hook called by `python-mode'.")
261
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000262;; in previous version of python-mode.el, the hook was incorrectly
263;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000264(and (fboundp 'make-obsolete-variable)
265 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
266
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000267(defvar py-mode-map ()
268 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269
Barry Warsaw7ae77681994-12-12 20:38:05 +0000270(if py-mode-map
271 ()
272 (setq py-mode-map (make-sparse-keymap))
273
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000274 ;; shadow global bindings for newline-and-indent w/ the py- version.
275 ;; BAW - this is extremely bad form, but I'm not going to change it
276 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000277 (mapcar (function (lambda (key)
278 (define-key
279 py-mode-map key 'py-newline-and-indent)))
280 (where-is-internal 'newline-and-indent))
281
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000282 ;; BAW - you could do it this way, but its not considered proper
283 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000284 (mapcar (function
285 (lambda (x)
286 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000287 '((":" . py-electric-colon)
288 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000289 ("\C-c|" . py-execute-region)
290 ("\C-c!" . py-shell)
291 ("\177" . py-delete-char)
292 ("\n" . py-newline-and-indent)
293 ("\C-c:" . py-guess-indent-offset)
294 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000295 ("\C-c\C-l" . py-shift-region-left)
296 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000297 ("\C-c<" . py-shift-region-left)
298 ("\C-c>" . py-shift-region-right)
299 ("\C-c\C-n" . py-next-statement)
300 ("\C-c\C-p" . py-previous-statement)
301 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000302 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000303 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000304 ("\C-c?" . py-describe-mode)
305 ("\C-c\C-hm" . py-describe-mode)
306 ("\e\C-a" . beginning-of-python-def-or-class)
307 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000308 ( "\e\C-h" . mark-python-def-or-class)))
309 ;; should do all keybindings this way
310 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
311 (define-key py-mode-map "\C-c\C-v" 'py-version)
312 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000313
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000314(defvar py-mode-syntax-table nil
315 "Syntax table used in `python-mode' buffers.")
316
Barry Warsaw7ae77681994-12-12 20:38:05 +0000317(if py-mode-syntax-table
318 ()
319 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000320 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000321 (mapcar (function
322 (lambda (x) (modify-syntax-entry
323 (car x) (cdr x) py-mode-syntax-table)))
324 '(( ?\( . "()" ) ( ?\) . ")(" )
325 ( ?\[ . "(]" ) ( ?\] . ")[" )
326 ( ?\{ . "(}" ) ( ?\} . "){" )
327 ;; fix operator symbols misassigned in the std table
328 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
329 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
330 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
331 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000332 ;; for historical reasons, underscore is word class
333 ;; instead of symbol class. it should be symbol class,
334 ;; but if you're tempted to change it, try binding M-f and
335 ;; M-b to py-forward-into-nomenclature and
336 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000337 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000338 ( ?\' . "\"") ; single quote is string quote
339 ( ?\" . "\"" ) ; double quote is string quote too
340 ( ?\` . "$") ; backquote is open and close paren
341 ( ?\# . "<") ; hash starts comment
342 ( ?\n . ">")))) ; newline ends comment
343
344(defconst py-stringlit-re
345 (concat
346 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
347 "\\|" ; or
348 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000349 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000350
351;; this is tricky because a trailing backslash does not mean
352;; continuation if it's in a comment
353(defconst py-continued-re
354 (concat
355 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
356 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000357 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000358
359(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000360 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000361
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000362(defconst py-outdent-re
363 (concat "\\(" (mapconcat 'identity
364 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000365 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000366 "finally:"
367 "elif\\s +.*:")
368 "\\|")
369 "\\)")
370 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000371
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000372(defconst py-no-outdent-re
373 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000374 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000375 "except\\(\\s +.*\\)?:"
376 "while\\s +.*:"
377 "for\\s +.*:"
378 "if\\s +.*:"
379 "elif\\s +.*:")
380 "\\|")
381 "\\)")
382 "Regexp matching lines to not outdent after.")
383
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000384
Barry Warsaw42f707f1996-07-29 21:05:05 +0000385;; Menu definitions, only relevent if you have the easymenu.el package
386;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
387(if (condition-case nil
388 (require 'easymenu)
389 (error nil))
390 (easy-menu-define
391 py-menu py-mode-map "Python Mode menu"
392 '("Python"
393 ["Comment Out Region" comment-region (mark)]
394 ["Uncomment Region" (comment-region (point) (mark) '(4)) (mark)]
395 "-"
396 ["Mark current block" py-mark-block t]
397 ["Mark current def" mark-python-def-or-class t]
398 ["Mark current class" (mark-python-def-or-class t) t]
399 "-"
400 ["Shift region left" py-shift-region-left (mark)]
401 ["Shift region right" py-shift-region-right (mark)]
402 "-"
403 ["Execute buffer" py-execute-buffer t]
404 ["Execute region" py-execute-region (mark)]
405 ["Start interpreter..." py-shell t]
406 "-"
407 ["Go to start of block" py-goto-block-up t]
408 ["Go to start of class" (beginning-of-python-def-or-class t) t]
409 ["Move to end of class" (end-of-python-def-or-class t) t]
410 ["Move to start of def" beginning-of-python-def-or-class t]
411 ["Move to end of def" end-of-python-def-or-class t]
412 "-"
413 ["Describe mode" py-describe-mode t]
414 )))
415
416
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000417;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000418(defun python-mode ()
419 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000420To submit a problem report, enter `\\[py-submit-bug-report]' from a
421`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
422documentation. To see what version of `python-mode' you are running,
423enter `\\[py-version]'.
424
425This mode knows about Python indentation, tokens, comments and
426continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000427
428COMMANDS
429\\{py-mode-map}
430VARIABLES
431
Barry Warsaw42f707f1996-07-29 21:05:05 +0000432py-indent-offset\t\tindentation increment
433py-block-comment-prefix\t\tcomment string used by comment-region
434py-python-command\t\tshell command to invoke Python interpreter
435py-scroll-process-buffer\t\talways scroll Python process buffer
436py-temp-directory\t\tdirectory used for temp files (if needed)
437py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000438 (interactive)
439 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000440 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000441 (setq major-mode 'python-mode
442 mode-name "Python"
443 local-abbrev-table python-mode-abbrev-table)
444 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000445 ;; add the menu
446 (if py-menu
447 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000448 ;; Emacs 19 requires this
449 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
450 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000451 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000452 (mapcar (function (lambda (x)
453 (make-local-variable (car x))
454 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000455 '((paragraph-separate . "^[ \t]*$")
456 (paragraph-start . "^[ \t]*$")
457 (require-final-newline . t)
Barry Warsawa7891711996-08-01 15:53:09 +0000458 (comment-start . "# ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000459 (comment-start-skip . "# *")
460 (comment-column . 40)
461 (indent-region-function . py-indent-region)
462 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000463 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000464 ;;
465 ;; not sure where the magic comment has to be; to save time
466 ;; searching for a rarity, we give up if it's not found prior to the
467 ;; first executable statement.
468 ;;
469 ;; BAW - on first glance, this seems like complete hackery. Why was
470 ;; this necessary, and is it still necessary?
471 (let ((case-fold-search nil)
472 (start (point))
473 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000474 (if (re-search-forward
475 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
476 (prog2 (py-next-statement 1) (point) (goto-char 1))
477 t)
478 (progn
479 (setq new-tab-width
480 (string-to-int
481 (buffer-substring (match-beginning 1) (match-end 1))))
482 (if (= tab-width new-tab-width)
483 nil
484 (setq tab-width new-tab-width)
485 (message "Caution: tab-width changed to %d" new-tab-width)
486 (if py-beep-if-tab-change (beep)))))
487 (goto-char start))
488
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000489 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000490 (if python-mode-hook
491 (run-hooks 'python-mode-hook)
492 (run-hooks 'py-mode-hook)))
493
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000494
Barry Warsaw826255b1996-03-22 16:09:34 +0000495(defun py-keep-region-active ()
Barry Warsawce60bc71996-08-01 18:17:14 +0000496 ;; do whatever is necessary to keep the region active in XEmacs.
497 ;; Ignore byte-compiler warnings you might see. Also note that
498 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
499 ;; require us to take explicit action.
Barry Warsaw826255b1996-03-22 16:09:34 +0000500 (and (boundp 'zmacs-region-stays)
501 (setq zmacs-region-stays t)))
502
Barry Warsawce60bc71996-08-01 18:17:14 +0000503
Barry Warsawb91b7431995-03-14 15:55:20 +0000504;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000505(defun py-outdent-p ()
506 ;; returns non-nil if the current line should outdent one level
507 (save-excursion
508 (and (progn (back-to-indentation)
509 (looking-at py-outdent-re))
510 (progn (backward-to-indentation 1)
511 (while (or (looking-at py-blank-or-comment-re)
512 (bobp))
513 (backward-to-indentation 1))
514 (not (looking-at py-no-outdent-re)))
515 )))
516
517
Barry Warsawb91b7431995-03-14 15:55:20 +0000518(defun py-electric-colon (arg)
519 "Insert a colon.
520In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000521argument is provided, that many colons are inserted non-electrically.
522Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000523 (interactive "P")
524 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000525 ;; are we in a string or comment?
526 (if (save-excursion
527 (let ((pps (parse-partial-sexp (save-excursion
528 (beginning-of-python-def-or-class)
529 (point))
530 (point))))
531 (not (or (nth 3 pps) (nth 4 pps)))))
532 (save-excursion
533 (let ((here (point))
534 (outdent 0)
535 (indent (py-compute-indentation)))
536 (if (and (not arg)
537 (py-outdent-p)
538 (= indent (save-excursion
539 (forward-line -1)
540 (py-compute-indentation)))
541 )
542 (setq outdent py-indent-offset))
543 ;; Don't indent, only outdent. This assumes that any lines that
544 ;; are already outdented relative to py-compute-indentation were
545 ;; put there on purpose. Its highly annoying to have `:' indent
546 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
547 ;; there a better way to determine this???
548 (if (< (current-indentation) indent) nil
549 (goto-char here)
550 (beginning-of-line)
551 (delete-horizontal-space)
552 (indent-to (- indent outdent))
553 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000554
555
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557(defun py-shell ()
558 "Start an interactive Python interpreter in another window.
559This is like Shell mode, except that Python is running in the window
560instead of a shell. See the `Interactive Shell' and `Shell Mode'
561sections of the Emacs manual for details, especially for the key
562bindings active in the `*Python*' buffer.
563
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000564See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000565behavior in the process window.
566
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000567Warning: Don't use an interactive Python if you change sys.ps1 or
568sys.ps2 from their default values, or if you're running code that
569prints `>>> ' or `... ' at the start of a line. `python-mode' can't
570distinguish your output from Python's output, and assumes that `>>> '
571at the start of a line is a prompt from Python. Similarly, the Emacs
572Shell mode code assumes that both `>>> ' and `... ' at the start of a
573line are Python prompts. Bad things can happen if you fool either
574mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000575
576Warning: If you do any editing *in* the process buffer *while* the
577buffer is accepting output from Python, do NOT attempt to `undo' the
578changes. Some of the output (nowhere near the parts you changed!) may
579be lost if you do. This appears to be an Emacs bug, an unfortunate
580interaction between undo and process filters; the same problem exists in
581non-Python process buffers using the default (Emacs-supplied) process
582filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000583 ;; BAW - should undo be disabled in the python process buffer, if
584 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000585 (interactive)
586 (if py-this-is-emacs-19-p
587 (progn
588 (require 'comint)
589 (switch-to-buffer-other-window
590 (make-comint "Python" py-python-command)))
591 (progn
592 (require 'shell)
593 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000594 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000595 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000596 (make-local-variable 'shell-prompt-pattern)
597 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
598 (set-process-filter (get-buffer-process (current-buffer))
599 'py-process-filter)
600 (set-syntax-table py-mode-syntax-table))
601
602(defun py-execute-region (start end)
603 "Send the region between START and END to a Python interpreter.
604If there is a *Python* process it is used.
605
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000606Hint: If you want to execute part of a Python file several times
607\(e.g., perhaps you're developing a function and want to flesh it out
608a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
609the region of interest, and send the code to a *Python* process via
610`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000611
612Following are subtleties to note when using a *Python* process:
613
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000614If a *Python* process is used, the region is copied into a temporary
615file (in directory `py-temp-directory'), and an `execfile' command is
616sent to Python naming that file. If you send regions faster than
617Python can execute them, `python-mode' will save them into distinct
618temp files, and execute the next one in the queue the next time it
619sees a `>>> ' prompt from Python. Each time this happens, the process
620buffer is popped into a window (if it's not already in some window) so
621you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000622
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000623 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000624
625is inserted at the end.
626
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000627Caution: No more than 26 regions can be pending at any given time.
628This limit is (indirectly) inherited from libc's mktemp(3).
629`python-mode' does not try to protect you from exceeding the limit.
630It's extremely unlikely that you'll get anywhere close to the limit in
631practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000632
633See the `\\[py-shell]' docs for additional warnings."
634 (interactive "r")
635 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000636 (let ((pyproc (get-process "Python"))
637 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000638 (if (null pyproc)
639 (shell-command-on-region start end py-python-command)
640 ;; else feed it thru a temp file
641 (setq fname (py-make-temp-name))
642 (write-region start end fname nil 'no-msg)
643 (setq py-file-queue (append py-file-queue (list fname)))
644 (if (cdr py-file-queue)
645 (message "File %s queued for execution" fname)
646 ;; else
647 (py-execute-file pyproc fname)))))
648
649(defun py-execute-file (pyproc fname)
650 (py-append-to-process-buffer
651 pyproc
652 (format "## working on region in file %s ...\n" fname))
653 (process-send-string pyproc (format "execfile('%s')\n" fname)))
654
655(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000656 (let ((curbuf (current-buffer))
657 (pbuf (process-buffer pyproc))
658 (pmark (process-mark pyproc))
659 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000660
661 ;; make sure we switch to a different buffer at least once. if we
662 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000663 ;; window, and point is before the end, and lots of output is
664 ;; coming at a fast pace, then (a) simple cursor-movement commands
665 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
666 ;; to have a visible effect (the window just doesn't get updated,
667 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
668 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000669 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000670 ;; #b makes no sense to me at all. #a almost makes sense: unless
671 ;; we actually change buffers, set_buffer_internal in buffer.c
672 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
673 ;; seems to make the Emacs command loop reluctant to update the
674 ;; display. Perhaps the default process filter in process.c's
675 ;; read_process_output has update_mode_lines++ for a similar
676 ;; reason? beats me ...
677
678 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000679 (if (eq curbuf pbuf) ; mysterious ugly hack
680 (set-buffer (get-buffer-create "*scratch*")))
681
682 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683 (let* ((start (point))
684 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000685 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000686 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000687 (goto-char pmark)
688 (insert string)
689 (move-marker pmark (point))
690 (setq file-finished
691 (and py-file-queue
692 (equal ">>> "
693 (buffer-substring
694 (prog2 (beginning-of-line) (point)
695 (goto-char pmark))
696 (point)))))
697 (if goback (goto-char start)
698 ;; else
699 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000700 (let* ((pop-up-windows t)
701 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000702 (set-window-point pwin (point)))))
703 (set-buffer curbuf)
704 (if file-finished
705 (progn
706 (py-delete-file-silently (car py-file-queue))
707 (setq py-file-queue (cdr py-file-queue))
708 (if py-file-queue
709 (py-execute-file pyproc (car py-file-queue)))))
710 (and goend
711 (progn (set-buffer pbuf)
712 (goto-char (point-max))))
713 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000714
715(defun py-execute-buffer ()
716 "Send the contents of the buffer to a Python interpreter.
717If there is a *Python* process buffer it is used. If a clipping
718restriction is in effect, only the accessible portion of the buffer is
719sent. A trailing newline will be supplied if needed.
720
721See the `\\[py-execute-region]' docs for an account of some subtleties."
722 (interactive)
723 (py-execute-region (point-min) (point-max)))
724
725
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000726
727;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000728(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000729 "Reduce indentation or delete character.
730If point is at the leftmost column, deletes the preceding newline.
731
732Else if point is at the leftmost non-blank character of a line that is
733neither a continuation line nor a non-indenting comment line, or if
734point is at the end of a blank line, reduces the indentation to match
735that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000736opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000737of where you are. With numeric count, outdents that many blocks (but
738not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000739
740Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000741needed so that only a single column position is deleted. Numeric
742argument delets that many characters."
743 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744 (if (or (/= (current-indentation) (current-column))
745 (bolp)
746 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +0000747 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000749 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000750 ;; else indent the same as the colon line that opened the block
751
752 ;; force non-blank so py-goto-block-up doesn't ignore it
753 (insert-char ?* 1)
754 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000755 (let ((base-indent 0) ; indentation of base line
756 (base-text "") ; and text of base line
757 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000758 (save-excursion
759 (while (< 0 count)
760 (condition-case nil ; in case no enclosing block
761 (progn
762 (py-goto-block-up 'no-mark)
763 (setq base-indent (current-indentation)
764 base-text (py-suck-up-leading-text)
765 base-found-p t))
766 (error nil))
767 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000768 (delete-char 1) ; toss the dummy character
769 (delete-horizontal-space)
770 (indent-to base-indent)
771 (if base-found-p
772 (message "Closes block: %s" base-text)))))
773
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000774;; required for pending-del and delsel modes
775(put 'py-delete-char 'delete-selection 'supersede)
776(put 'py-delete-char 'pending-delete 'supersede)
777
Barry Warsaw7ae77681994-12-12 20:38:05 +0000778(defun py-indent-line ()
779 "Fix the indentation of the current line according to Python rules."
780 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000781 (let* ((ci (current-indentation))
782 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000783 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000784 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000785 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000786 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000787 (if (/= ci need)
788 (save-excursion
789 (beginning-of-line)
790 (delete-horizontal-space)
791 (indent-to need)))
792 (if move-to-indentation-p (back-to-indentation))))
793
794(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000795 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000796This is just `strives to' because correct indentation can't be computed
797from scratch for Python code. In general, deletes the whitespace before
798point, inserts a newline, and takes an educated guess as to how you want
799the new line indented."
800 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000801 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000802 (if (< ci (current-column)) ; if point beyond indentation
803 (newline-and-indent)
804 ;; else try to act like newline-and-indent "normally" acts
805 (beginning-of-line)
806 (insert-char ?\n 1)
807 (move-to-column ci))))
808
809(defun py-compute-indentation ()
810 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000811 (let ((pps (parse-partial-sexp (save-excursion
812 (beginning-of-python-def-or-class)
813 (point))
814 (point))))
815 (beginning-of-line)
816 (cond
817 ;; are we inside a string or comment?
818 ((or (nth 3 pps) (nth 4 pps))
819 (save-excursion
820 (if (not py-align-multiline-strings-p) 0
821 ;; skip back over blank & non-indenting comment lines
822 ;; note: will skip a blank or non-indenting comment line
823 ;; that happens to be a continuation line too
824 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
825 (back-to-indentation)
826 (current-column))))
827 ;; are we on a continuation line?
828 ((py-continuation-line-p)
829 (let ((startpos (point))
830 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +0000831 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000832 (if open-bracket-pos
833 (progn
834 ;; align with first item in list; else a normal
835 ;; indent beyond the line with the open bracket
836 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
837 ;; is the first list item on the same line?
838 (skip-chars-forward " \t")
839 (if (null (memq (following-char) '(?\n ?# ?\\)))
840 ; yes, so line up with it
841 (current-column)
842 ;; first list item on another line, or doesn't exist yet
843 (forward-line 1)
844 (while (and (< (point) startpos)
845 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
846 (forward-line 1))
847 (if (< (point) startpos)
848 ;; again mimic the first list item
849 (current-indentation)
850 ;; else they're about to enter the first item
851 (goto-char open-bracket-pos)
852 (+ (current-indentation) py-indent-offset))))
853
854 ;; else on backslash continuation line
855 (forward-line -1)
856 (if (py-continuation-line-p) ; on at least 3rd line in block
857 (current-indentation) ; so just continue the pattern
858 ;; else started on 2nd line in block, so indent more.
859 ;; if base line is an assignment with a start on a RHS,
860 ;; indent to 2 beyond the leftmost "="; else skip first
861 ;; chunk of non-whitespace characters on base line, + 1 more
862 ;; column
863 (end-of-line)
864 (setq endpos (point) searching t)
865 (back-to-indentation)
866 (setq startpos (point))
867 ;; look at all "=" from left to right, stopping at first
868 ;; one not nested in a list or string
869 (while searching
870 (skip-chars-forward "^=" endpos)
871 (if (= (point) endpos)
872 (setq searching nil)
873 (forward-char 1)
874 (setq state (parse-partial-sexp startpos (point)))
875 (if (and (zerop (car state)) ; not in a bracket
876 (null (nth 3 state))) ; & not in a string
877 (progn
878 (setq searching nil) ; done searching in any case
879 (setq found
880 (not (or
881 (eq (following-char) ?=)
882 (memq (char-after (- (point) 2))
883 '(?< ?> ?!)))))))))
884 (if (or (not found) ; not an assignment
885 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
886 (progn
887 (goto-char startpos)
888 (skip-chars-forward "^ \t\n")))
889 (1+ (current-column))))))
890
891 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +0000892 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000893
Barry Warsawa7891711996-08-01 15:53:09 +0000894 ;; Dfn: "Indenting comment line". A line containing only a
895 ;; comment, but which is treated like a statement for
896 ;; indentation calculation purposes. Such lines are only
897 ;; treated specially by the mode; they are not treated
898 ;; specially by the Python interpreter.
899
900 ;; The rules for indenting comment lines are a line where:
901 ;; - the first non-whitespace character is `#', and
902 ;; - the character following the `#' is whitespace, and
903 ;; - the line is outdented with respect to (i.e. to the left
904 ;; of) the indentation of the preceding non-blank line.
905
906 ;; The first non-blank line following an indenting comment
907 ;; line is given the same amount of indentation as the
908 ;; indenting comment line.
909
910 ;; All other comment-only lines are ignored for indentation
911 ;; purposes.
912
913 ;; Are we looking at a comment-only line which is *not* an
914 ;; indenting comment line? If so, we assume that its been
915 ;; placed at the desired indentation, so leave it alone.
916 ;; Indenting comment lines are aligned as statements down
917 ;; below.
918 ((and (looking-at "[ \t]*#[^ \t\n]")
919 ;; NOTE: this test will not be performed in older Emacsen
920 (fboundp 'forward-comment)
921 (<= (current-indentation)
922 (save-excursion
923 (forward-comment (- (point-max)))
924 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000925 (current-indentation))
926
927 ;; else indentation based on that of the statement that
928 ;; precedes us; use the first line of that statement to
929 ;; establish the base, in case the user forced a non-std
930 ;; indentation for the continuation lines (if any)
931 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000932 ;; skip back over blank & non-indenting comment lines note:
933 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000934 ;; happens to be a continuation line too. use fast Emacs 19
935 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000936 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000937 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000938 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000939 (let (done)
940 (while (not done)
941 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
942 nil 'move)
943 (setq done (or (eq py-honor-comment-indentation t)
944 (bobp)
945 (/= (following-char) ?#)
946 (not (zerop (current-column)))))
947 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000948 ;; if we landed inside a string, go to the beginning of that
949 ;; string. this handles triple quoted, multi-line spanning
950 ;; strings.
951 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +0000952 (+ (current-indentation)
953 (if (py-statement-opens-block-p)
954 py-indent-offset
955 (if (py-statement-closes-block-p)
956 (- py-indent-offset)
957 0)))
958 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000959
960(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000961 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000962By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000963`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000964Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000965`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966their own buffer-local copy), both those currently existing and those
967created later in the Emacs session.
968
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000969Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000970There's no excuse for such foolishness, but sometimes you have to deal
971with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000972`py-indent-offset' to what it thinks it was when they created the
973mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000974
975Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000976looking for a line that opens a block of code. `py-indent-offset' is
977set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978statement following it. If the search doesn't succeed going forward,
979it's tried again going backward."
980 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981 (let (new-value
982 (start (point))
983 restart
984 (found nil)
985 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000986 (py-goto-initial-line)
987 (while (not (or found (eobp)))
988 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
989 (progn
990 (setq restart (point))
991 (py-goto-initial-line)
992 (if (py-statement-opens-block-p)
993 (setq found t)
994 (goto-char restart)))))
995 (if found
996 ()
997 (goto-char start)
998 (py-goto-initial-line)
999 (while (not (or found (bobp)))
1000 (setq found
1001 (and
1002 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1003 (or (py-goto-initial-line) t) ; always true -- side effect
1004 (py-statement-opens-block-p)))))
1005 (setq colon-indent (current-indentation)
1006 found (and found (zerop (py-next-statement 1)))
1007 new-value (- (current-indentation) colon-indent))
1008 (goto-char start)
1009 (if found
1010 (progn
1011 (funcall (if global 'kill-local-variable 'make-local-variable)
1012 'py-indent-offset)
1013 (setq py-indent-offset new-value)
1014 (message "%s value of py-indent-offset set to %d"
1015 (if global "Global" "Local")
1016 py-indent-offset))
1017 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1018
1019(defun py-shift-region (start end count)
1020 (save-excursion
1021 (goto-char end) (beginning-of-line) (setq end (point))
1022 (goto-char start) (beginning-of-line) (setq start (point))
1023 (indent-rigidly start end count)))
1024
1025(defun py-shift-region-left (start end &optional count)
1026 "Shift region of Python code to the left.
1027The lines from the line containing the start of the current region up
1028to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001029shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030
1031If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001032many columns. With no active region, outdent only the current line.
1033You cannot outdent the region if any line is already at column zero."
1034 (interactive
1035 (let ((p (point))
1036 (m (mark))
1037 (arg current-prefix-arg))
1038 (if m
1039 (list (min p m) (max p m) arg)
1040 (list p (save-excursion (forward-line 1) (point)) arg))))
1041 ;; if any line is at column zero, don't shift the region
1042 (save-excursion
1043 (goto-char start)
1044 (while (< (point) end)
1045 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001046 (if (and (zerop (current-column))
1047 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001048 (error "Region is at left edge."))
1049 (forward-line 1)))
1050 (py-shift-region start end (- (prefix-numeric-value
1051 (or count py-indent-offset))))
1052 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001053
1054(defun py-shift-region-right (start end &optional count)
1055 "Shift region of Python code to the right.
1056The lines from the line containing the start of the current region up
1057to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001058shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001059
1060If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001061many columns. With no active region, indent only the current line."
1062 (interactive
1063 (let ((p (point))
1064 (m (mark))
1065 (arg current-prefix-arg))
1066 (if m
1067 (list (min p m) (max p m) arg)
1068 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001069 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001070 (or count py-indent-offset)))
1071 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001072
1073(defun py-indent-region (start end &optional indent-offset)
1074 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001075
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076The lines from the line containing the start of the current region up
1077to (but not including) the line containing the end of the region are
1078reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001079character in the first column, the first line is left alone and the
1080rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001081region is reindented with respect to the (closest code or indenting
1082comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001083
1084This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085control structures are introduced or removed, or to reformat code
1086using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001087
1088If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001089the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001090used.
1091
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001092Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001093is called! This function does not compute proper indentation from
1094scratch (that's impossible in Python), it merely adjusts the existing
1095indentation to be correct in context.
1096
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001097Warning: This function really has no idea what to do with
1098non-indenting comment lines, and shifts them as if they were indenting
1099comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001101Special cases: whitespace is deleted from blank lines; continuation
1102lines are shifted by the same amount their initial line was shifted,
1103in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001104initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001105 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001106 (save-excursion
1107 (goto-char end) (beginning-of-line) (setq end (point-marker))
1108 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001109 (let ((py-indent-offset (prefix-numeric-value
1110 (or indent-offset py-indent-offset)))
1111 (indents '(-1)) ; stack of active indent levels
1112 (target-column 0) ; column to which to indent
1113 (base-shifted-by 0) ; amount last base line was shifted
1114 (indent-base (if (looking-at "[ \t\n]")
1115 (py-compute-indentation)
1116 0))
1117 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001118 (while (< (point) end)
1119 (setq ci (current-indentation))
1120 ;; figure out appropriate target column
1121 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001122 ((or (eq (following-char) ?#) ; comment in column 1
1123 (looking-at "[ \t]*$")) ; entirely blank
1124 (setq target-column 0))
1125 ((py-continuation-line-p) ; shift relative to base line
1126 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001127 (t ; new base line
1128 (if (> ci (car indents)) ; going deeper; push it
1129 (setq indents (cons ci indents))
1130 ;; else we should have seen this indent before
1131 (setq indents (memq ci indents)) ; pop deeper indents
1132 (if (null indents)
1133 (error "Bad indentation in region, at line %d"
1134 (save-restriction
1135 (widen)
1136 (1+ (count-lines 1 (point)))))))
1137 (setq target-column (+ indent-base
1138 (* py-indent-offset
1139 (- (length indents) 2))))
1140 (setq base-shifted-by (- target-column ci))))
1141 ;; shift as needed
1142 (if (/= ci target-column)
1143 (progn
1144 (delete-horizontal-space)
1145 (indent-to target-column)))
1146 (forward-line 1))))
1147 (set-marker end nil))
1148
Barry Warsawa7891711996-08-01 15:53:09 +00001149(defun py-comment-region (beg end &optional arg)
1150 "Like `comment-region' but uses double hash (`#') comment starter."
1151 (interactive "r\nP")
1152 (let ((comment-start "## "))
1153 (comment-region beg end arg)))
1154
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001155
1156;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001157(defun py-previous-statement (count)
1158 "Go to the start of previous Python statement.
1159If the statement at point is the i'th Python statement, goes to the
1160start of statement i-COUNT. If there is no such statement, goes to the
1161first statement. Returns count of statements left to move.
1162`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001163 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001164 (if (< count 0) (py-next-statement (- count))
1165 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001166 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001167 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001168 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169 (> count 0)
1170 (zerop (forward-line -1))
1171 (py-goto-statement-at-or-above))
1172 (setq count (1- count)))
1173 (if (> count 0) (goto-char start)))
1174 count))
1175
1176(defun py-next-statement (count)
1177 "Go to the start of next Python statement.
1178If the statement at point is the i'th Python statement, goes to the
1179start of statement i+COUNT. If there is no such statement, goes to the
1180last statement. Returns count of statements left to move. `Statements'
1181do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183 (if (< count 0) (py-previous-statement (- count))
1184 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001185 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001186 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001187 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001188 (> count 0)
1189 (py-goto-statement-below))
1190 (setq count (1- count)))
1191 (if (> count 0) (goto-char start)))
1192 count))
1193
1194(defun py-goto-block-up (&optional nomark)
1195 "Move up to start of current block.
1196Go to the statement that starts the smallest enclosing block; roughly
1197speaking, this will be the closest preceding statement that ends with a
1198colon and is indented less than the statement you started on. If
1199successful, also sets the mark to the starting point.
1200
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001201`\\[py-mark-block]' can be used afterward to mark the whole code
1202block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001203
1204If called from a program, the mark will not be set if optional argument
1205NOMARK is not nil."
1206 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207 (let ((start (point))
1208 (found nil)
1209 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001210 (py-goto-initial-line)
1211 ;; if on blank or non-indenting comment line, use the preceding stmt
1212 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1213 (progn
1214 (py-goto-statement-at-or-above)
1215 (setq found (py-statement-opens-block-p))))
1216 ;; search back for colon line indented less
1217 (setq initial-indent (current-indentation))
1218 (if (zerop initial-indent)
1219 ;; force fast exit
1220 (goto-char (point-min)))
1221 (while (not (or found (bobp)))
1222 (setq found
1223 (and
1224 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1225 (or (py-goto-initial-line) t) ; always true -- side effect
1226 (< (current-indentation) initial-indent)
1227 (py-statement-opens-block-p))))
1228 (if found
1229 (progn
1230 (or nomark (push-mark start))
1231 (back-to-indentation))
1232 (goto-char start)
1233 (error "Enclosing block not found"))))
1234
1235(defun beginning-of-python-def-or-class (&optional class)
1236 "Move point to start of def (or class, with prefix arg).
1237
1238Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001239arg, looks for a `class' instead. The docs assume the `def' case;
1240just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001241
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001242If point is in a def statement already, and after the `d', simply
1243moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001244
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001245Else (point is not in a def statement, or at or before the `d' of a
1246def statement), searches for the closest preceding def statement, and
1247leaves point at its start. If no such statement can be found, leaves
1248point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001249
1250Returns t iff a def statement is found by these rules.
1251
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001252Note that doing this command repeatedly will take you closer to the
1253start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001254
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001255If you want to mark the current def/class, see
1256`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001258 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1259 (start-of-line (progn (beginning-of-line) (point)))
1260 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001261 (if (or (/= start-of-stmt start-of-line)
1262 (not at-or-before-p))
1263 (end-of-line)) ; OK to match on this line
1264 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001265 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001266
1267(defun end-of-python-def-or-class (&optional class)
1268 "Move point beyond end of def (or class, with prefix arg) body.
1269
1270By default, looks for an appropriate `def'. If you supply a prefix arg,
1271looks for a `class' instead. The docs assume the `def' case; just
1272substitute `class' for `def' for the other case.
1273
1274If point is in a def statement already, this is the def we use.
1275
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001276Else if the def found by `\\[beginning-of-python-def-or-class]'
1277contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001278
1279Else we search forward for the closest following def, and use that.
1280
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281If a def can be found by these rules, point is moved to the start of
1282the line immediately following the def block, and the position of the
1283start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001284
1285Else point is moved to the end of the buffer, and nil is returned.
1286
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001287Note that doing this command repeatedly will take you closer to the
1288end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001289
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001290If you want to mark the current def/class, see
1291`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001292 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001293 (let ((start (progn (py-goto-initial-line) (point)))
1294 (which (if class "class" "def"))
1295 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296 ;; move point to start of appropriate def/class
1297 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1298 (setq state 'at-beginning)
1299 ;; else see if beginning-of-python-def-or-class hits container
1300 (if (and (beginning-of-python-def-or-class class)
1301 (progn (py-goto-beyond-block)
1302 (> (point) start)))
1303 (setq state 'at-end)
1304 ;; else search forward
1305 (goto-char start)
1306 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1307 (progn (setq state 'at-beginning)
1308 (beginning-of-line)))))
1309 (cond
1310 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1311 ((eq state 'at-end) t)
1312 ((eq state 'not-found) nil)
1313 (t (error "internal error in end-of-python-def-or-class")))))
1314
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001315
1316;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001317(defun py-mark-block (&optional extend just-move)
1318 "Mark following block of lines. With prefix arg, mark structure.
1319Easier to use than explain. It sets the region to an `interesting'
1320block of succeeding lines. If point is on a blank line, it goes down to
1321the next non-blank line. That will be the start of the region. The end
1322of the region depends on the kind of line at the start:
1323
1324 - If a comment, the region will include all succeeding comment lines up
1325 to (but not including) the next non-comment line (if any).
1326
1327 - Else if a prefix arg is given, and the line begins one of these
1328 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001329
1330 if elif else try except finally for while def class
1331
Barry Warsaw7ae77681994-12-12 20:38:05 +00001332 the region will be set to the body of the structure, including
1333 following blocks that `belong' to it, but excluding trailing blank
1334 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001335 and all (if any) of the following `except' and `finally' blocks
1336 that belong to the `try' structure will be in the region. Ditto
1337 for if/elif/else, for/else and while/else structures, and (a bit
1338 degenerate, since they're always one-block structures) def and
1339 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340
1341 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001342 block (see list above), and the block is not a `one-liner' (i.e.,
1343 the statement ends with a colon, not with code), the region will
1344 include all succeeding lines up to (but not including) the next
1345 code statement (if any) that's indented no more than the starting
1346 line, except that trailing blank and comment lines are excluded.
1347 E.g., if the starting line begins a multi-statement `def'
1348 structure, the region will be set to the full function definition,
1349 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001350
1351 - Else the region will include all succeeding lines up to (but not
1352 including) the next blank line, or code or indenting-comment line
1353 indented strictly less than the starting line. Trailing indenting
1354 comment lines are included in this case, but not trailing blank
1355 lines.
1356
1357A msg identifying the location of the mark is displayed in the echo
1358area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1359
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360If called from a program, optional argument EXTEND plays the role of
1361the prefix arg, and if optional argument JUST-MOVE is not nil, just
1362moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001363 (interactive "P") ; raw prefix arg
1364 (py-goto-initial-line)
1365 ;; skip over blank lines
1366 (while (and
1367 (looking-at "[ \t]*$") ; while blank line
1368 (not (eobp))) ; & somewhere to go
1369 (forward-line 1))
1370 (if (eobp)
1371 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001372 (let ((initial-pos (point))
1373 (initial-indent (current-indentation))
1374 last-pos ; position of last stmt in region
1375 (followers
1376 '((if elif else) (elif elif else) (else)
1377 (try except finally) (except except) (finally)
1378 (for else) (while else)
1379 (def) (class) ) )
1380 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001381
1382 (cond
1383 ;; if comment line, suck up the following comment lines
1384 ((looking-at "[ \t]*#")
1385 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1386 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1387 (setq last-pos (point)))
1388
1389 ;; else if line is a block line and EXTEND given, suck up
1390 ;; the whole structure
1391 ((and extend
1392 (setq first-symbol (py-suck-up-first-keyword) )
1393 (assq first-symbol followers))
1394 (while (and
1395 (or (py-goto-beyond-block) t) ; side effect
1396 (forward-line -1) ; side effect
1397 (setq last-pos (point)) ; side effect
1398 (py-goto-statement-below)
1399 (= (current-indentation) initial-indent)
1400 (setq next-symbol (py-suck-up-first-keyword))
1401 (memq next-symbol (cdr (assq first-symbol followers))))
1402 (setq first-symbol next-symbol)))
1403
1404 ;; else if line *opens* a block, search for next stmt indented <=
1405 ((py-statement-opens-block-p)
1406 (while (and
1407 (setq last-pos (point)) ; always true -- side effect
1408 (py-goto-statement-below)
1409 (> (current-indentation) initial-indent))
1410 nil))
1411
1412 ;; else plain code line; stop at next blank line, or stmt or
1413 ;; indenting comment line indented <
1414 (t
1415 (while (and
1416 (setq last-pos (point)) ; always true -- side effect
1417 (or (py-goto-beyond-final-line) t)
1418 (not (looking-at "[ \t]*$")) ; stop at blank line
1419 (or
1420 (>= (current-indentation) initial-indent)
1421 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1422 nil)))
1423
1424 ;; skip to end of last stmt
1425 (goto-char last-pos)
1426 (py-goto-beyond-final-line)
1427
1428 ;; set mark & display
1429 (if just-move
1430 () ; just return
1431 (push-mark (point) 'no-msg)
1432 (forward-line -1)
1433 (message "Mark set after: %s" (py-suck-up-leading-text))
1434 (goto-char initial-pos))))
1435
1436(defun mark-python-def-or-class (&optional class)
1437 "Set region to body of def (or class, with prefix arg) enclosing point.
1438Pushes the current mark, then point, on the mark ring (all language
1439modes do this, but although it's handy it's never documented ...).
1440
1441In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001442hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1443`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001444
1445And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001446Turned out that was more confusing than useful: the `goto start' and
1447`goto end' commands are usually used to search through a file, and
1448people expect them to act a lot like `search backward' and `search
1449forward' string-search commands. But because Python `def' and `class'
1450can nest to arbitrary levels, finding the smallest def containing
1451point cannot be done via a simple backward search: the def containing
1452point may not be the closest preceding def, or even the closest
1453preceding def that's indented less. The fancy algorithm required is
1454appropriate for the usual uses of this `mark' command, but not for the
1455`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001456
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457So the def marked by this command may not be the one either of the
1458`goto' commands find: If point is on a blank or non-indenting comment
1459line, moves back to start of the closest preceding code statement or
1460indenting comment line. If this is a `def' statement, that's the def
1461we use. Else searches for the smallest enclosing `def' block and uses
1462that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001463
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001464When an enclosing def is found: The mark is left immediately beyond
1465the last line of the def block. Point is left at the start of the
1466def, except that: if the def is preceded by a number of comment lines
1467followed by (at most) one optional blank line, point is left at the
1468start of the comments; else if the def is preceded by a blank line,
1469point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001470
1471The intent is to mark the containing def/class and its associated
1472documentation, to make moving and duplicating functions and classes
1473pleasant."
1474 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001475 (let ((start (point))
1476 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001477 (push-mark start)
1478 (if (not (py-go-up-tree-to-keyword which))
1479 (progn (goto-char start)
1480 (error "Enclosing %s not found" which))
1481 ;; else enclosing def/class found
1482 (setq start (point))
1483 (py-goto-beyond-block)
1484 (push-mark (point))
1485 (goto-char start)
1486 (if (zerop (forward-line -1)) ; if there is a preceding line
1487 (progn
1488 (if (looking-at "[ \t]*$") ; it's blank
1489 (setq start (point)) ; so reset start point
1490 (goto-char start)) ; else try again
1491 (if (zerop (forward-line -1))
1492 (if (looking-at "[ \t]*#") ; a comment
1493 ;; look back for non-comment line
1494 ;; tricky: note that the regexp matches a blank
1495 ;; line, cuz \n is in the 2nd character class
1496 (and
1497 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1498 (forward-line 1))
1499 ;; no comment, so go back
1500 (goto-char start))))))))
1501
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001502;; ripped from cc-mode
1503(defun py-forward-into-nomenclature (&optional arg)
1504 "Move forward to end of a nomenclature section or word.
1505With arg, to it arg times.
1506
1507A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1508 (interactive "p")
1509 (let ((case-fold-search nil))
1510 (if (> arg 0)
Barry Warsawc846f461996-07-25 18:53:17 +00001511 (re-search-forward "\\W*\\([A-Z_]*[a-z0-9]*\\)" (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001512 (while (and (< arg 0)
1513 (re-search-backward
1514 "\\(\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\W\\w+\\)"
1515 (point-min) 0))
1516 (forward-char 1)
1517 (setq arg (1+ arg)))))
1518 (py-keep-region-active))
1519
1520(defun py-backward-into-nomenclature (&optional arg)
1521 "Move backward to beginning of a nomenclature section or word.
1522With optional ARG, move that many times. If ARG is negative, move
1523forward.
1524
1525A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1526 (interactive "p")
1527 (py-forward-into-nomenclature (- arg))
1528 (py-keep-region-active))
1529
1530
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531
1532;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533
1534;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001535;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1536;; out of the right places, along with the keys they're on & current
1537;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001538(defun py-dump-help-string (str)
1539 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001540 (let ((locals (buffer-local-variables))
1541 funckind funcname func funcdoc
1542 (start 0) mstart end
1543 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1545 (setq mstart (match-beginning 0) end (match-end 0)
1546 funckind (substring str (match-beginning 1) (match-end 1))
1547 funcname (substring str (match-beginning 2) (match-end 2))
1548 func (intern funcname))
1549 (princ (substitute-command-keys (substring str start mstart)))
1550 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551 ((equal funckind "c") ; command
1552 (setq funcdoc (documentation func)
1553 keys (concat
1554 "Key(s): "
1555 (mapconcat 'key-description
1556 (where-is-internal func py-mode-map)
1557 ", "))))
1558 ((equal funckind "v") ; variable
1559 (setq funcdoc (substitute-command-keys
1560 (get func 'variable-documentation))
1561 keys (if (assq func locals)
1562 (concat
1563 "Local/Global values: "
1564 (prin1-to-string (symbol-value func))
1565 " / "
1566 (prin1-to-string (default-value func)))
1567 (concat
1568 "Value: "
1569 (prin1-to-string (symbol-value func))))))
1570 (t ; unexpected
1571 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001572 (princ (format "\n-> %s:\t%s\t%s\n\n"
1573 (if (equal funckind "c") "Command" "Variable")
1574 funcname keys))
1575 (princ funcdoc)
1576 (terpri)
1577 (setq start end))
1578 (princ (substitute-command-keys (substring str start))))
1579 (print-help-return-message)))
1580
1581(defun py-describe-mode ()
1582 "Dump long form of Python-mode docs."
1583 (interactive)
1584 (py-dump-help-string "Major mode for editing Python files.
1585Knows about Python indentation, tokens, comments and continuation lines.
1586Paragraphs are separated by blank lines only.
1587
1588Major sections below begin with the string `@'; specific function and
1589variable docs begin with `->'.
1590
1591@EXECUTING PYTHON CODE
1592
1593\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1594\\[py-execute-region]\tsends the current region
1595\\[py-shell]\tstarts a Python interpreter window; this will be used by
1596\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1597%c:py-execute-buffer
1598%c:py-execute-region
1599%c:py-shell
1600
1601@VARIABLES
1602
1603py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001604py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001605
1606py-python-command\tshell command to invoke Python interpreter
1607py-scroll-process-buffer\talways scroll Python process buffer
1608py-temp-directory\tdirectory used for temp files (if needed)
1609
1610py-beep-if-tab-change\tring the bell if tab-width is changed
1611%v:py-indent-offset
1612%v:py-block-comment-prefix
1613%v:py-python-command
1614%v:py-scroll-process-buffer
1615%v:py-temp-directory
1616%v:py-beep-if-tab-change
1617
1618@KINDS OF LINES
1619
1620Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001621preceding line ends with a backslash that's not part of a comment, or
1622the paren/bracket/brace nesting level at the start of the line is
1623non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001624
1625An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001626possibly blanks or tabs), a `comment line' (leftmost non-blank
1627character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001628
1629Comment Lines
1630
1631Although all comment lines are treated alike by Python, Python mode
1632recognizes two kinds that act differently with respect to indentation.
1633
1634An `indenting comment line' is a comment line with a blank, tab or
1635nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001636treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637indenting comment line will be indented like the comment line. All
1638other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001639following the initial `#') are `non-indenting comment lines', and
1640their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641
1642Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001643whenever possible. Non-indenting comment lines are useful in cases
1644like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001645
1646\ta = b # a very wordy single-line comment that ends up being
1647\t #... continued onto another line
1648
1649\tif a == b:
1650##\t\tprint 'panic!' # old code we've `commented out'
1651\t\treturn a
1652
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001653Since the `#...' and `##' comment lines have a non-whitespace
1654character following the initial `#', Python mode ignores them when
1655computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
1657Continuation Lines and Statements
1658
1659The Python-mode commands generally work on statements instead of on
1660individual lines, where a `statement' is a comment or blank line, or a
1661code line and all of its following continuation lines (if any)
1662considered as a single logical unit. The commands in this mode
1663generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001664statement containing point, even if point happens to be in the middle
1665of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001666
1667
1668@INDENTATION
1669
1670Primarily for entering new code:
1671\t\\[indent-for-tab-command]\t indent line appropriately
1672\t\\[py-newline-and-indent]\t insert newline, then indent
1673\t\\[py-delete-char]\t reduce indentation, or delete single character
1674
1675Primarily for reindenting existing code:
1676\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1677\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1678
1679\t\\[py-indent-region]\t reindent region to match its context
1680\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1681\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1682
1683Unlike most programming languages, Python uses indentation, and only
1684indentation, to specify block structure. Hence the indentation supplied
1685automatically by Python-mode is just an educated guess: only you know
1686the block structure you intend, so only you can supply correct
1687indentation.
1688
1689The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1690the indentation of preceding statements. E.g., assuming
1691py-indent-offset is 4, after you enter
1692\tif a > 0: \\[py-newline-and-indent]
1693the cursor will be moved to the position of the `_' (_ is not a
1694character in the file, it's just used here to indicate the location of
1695the cursor):
1696\tif a > 0:
1697\t _
1698If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1699to
1700\tif a > 0:
1701\t c = d
1702\t _
1703Python-mode cannot know whether that's what you intended, or whether
1704\tif a > 0:
1705\t c = d
1706\t_
1707was your intent. In general, Python-mode either reproduces the
1708indentation of the (closest code or indenting-comment) preceding
1709statement, or adds an extra py-indent-offset blanks if the preceding
1710statement has `:' as its last significant (non-whitespace and non-
1711comment) character. If the suggested indentation is too much, use
1712\\[py-delete-char] to reduce it.
1713
1714Continuation lines are given extra indentation. If you don't like the
1715suggested indentation, change it to something you do like, and Python-
1716mode will strive to indent later lines of the statement in the same way.
1717
1718If a line is a continuation line by virtue of being in an unclosed
1719paren/bracket/brace structure (`list', for short), the suggested
1720indentation depends on whether the current line contains the first item
1721in the list. If it does, it's indented py-indent-offset columns beyond
1722the indentation of the line containing the open bracket. If you don't
1723like that, change it by hand. The remaining items in the list will mimic
1724whatever indentation you give to the first item.
1725
1726If a line is a continuation line because the line preceding it ends with
1727a backslash, the third and following lines of the statement inherit their
1728indentation from the line preceding them. The indentation of the second
1729line in the statement depends on the form of the first (base) line: if
1730the base line is an assignment statement with anything more interesting
1731than the backslash following the leftmost assigning `=', the second line
1732is indented two columns beyond that `='. Else it's indented to two
1733columns beyond the leftmost solid chunk of non-whitespace characters on
1734the base line.
1735
1736Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1737repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1738structure you intend.
1739%c:indent-for-tab-command
1740%c:py-newline-and-indent
1741%c:py-delete-char
1742
1743
1744The next function may be handy when editing code you didn't write:
1745%c:py-guess-indent-offset
1746
1747
1748The remaining `indent' functions apply to a region of Python code. They
1749assume the block structure (equals indentation, in Python) of the region
1750is correct, and alter the indentation in various ways while preserving
1751the block structure:
1752%c:py-indent-region
1753%c:py-shift-region-left
1754%c:py-shift-region-right
1755
1756@MARKING & MANIPULATING REGIONS OF CODE
1757
1758\\[py-mark-block]\t mark block of lines
1759\\[mark-python-def-or-class]\t mark smallest enclosing def
1760\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001761\\[comment-region]\t comment out region of code
1762\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00001763%c:py-mark-block
1764%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00001765%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766
1767@MOVING POINT
1768
1769\\[py-previous-statement]\t move to statement preceding point
1770\\[py-next-statement]\t move to statement following point
1771\\[py-goto-block-up]\t move up to start of current block
1772\\[beginning-of-python-def-or-class]\t move to start of def
1773\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1774\\[end-of-python-def-or-class]\t move to end of def
1775\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1776
1777The first two move to one statement beyond the statement that contains
1778point. A numeric prefix argument tells them to move that many
1779statements instead. Blank lines, comment lines, and continuation lines
1780do not count as `statements' for these commands. So, e.g., you can go
1781to the first code statement in a file by entering
1782\t\\[beginning-of-buffer]\t to move to the top of the file
1783\t\\[py-next-statement]\t to skip over initial comments and blank lines
1784Or do `\\[py-previous-statement]' with a huge prefix argument.
1785%c:py-previous-statement
1786%c:py-next-statement
1787%c:py-goto-block-up
1788%c:beginning-of-python-def-or-class
1789%c:end-of-python-def-or-class
1790
1791@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1792
1793`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1794
1795`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1796overall class and def structure of a module.
1797
1798`\\[back-to-indentation]' moves point to a line's first non-blank character.
1799
1800`\\[indent-relative]' is handy for creating odd indentation.
1801
1802@OTHER EMACS HINTS
1803
1804If you don't like the default value of a variable, change its value to
1805whatever you do like by putting a `setq' line in your .emacs file.
1806E.g., to set the indentation increment to 4, put this line in your
1807.emacs:
1808\t(setq py-indent-offset 4)
1809To see the value of a variable, do `\\[describe-variable]' and enter the variable
1810name at the prompt.
1811
1812When entering a key sequence like `C-c C-n', it is not necessary to
1813release the CONTROL key after doing the `C-c' part -- it suffices to
1814press the CONTROL key, press and release `c' (while still holding down
1815CONTROL), press and release `n' (while still holding down CONTROL), &
1816then release CONTROL.
1817
1818Entering Python mode calls with no arguments the value of the variable
1819`python-mode-hook', if that value exists and is not nil; for backward
1820compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1821the Elisp manual for details.
1822
1823Obscure: When python-mode is first loaded, it looks for all bindings
1824to newline-and-indent in the global keymap, and shadows them with
1825local bindings to py-newline-and-indent."))
1826
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827
1828;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829(defvar py-parse-state-re
1830 (concat
1831 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1832 "\\|"
1833 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834
Barry Warsaw7ae77681994-12-12 20:38:05 +00001835;; returns the parse state at point (see parse-partial-sexp docs)
1836(defun py-parse-state ()
1837 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001838 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00001839 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001840 (while (not done)
1841 ;; back up to the first preceding line (if any; else start of
1842 ;; buffer) that begins with a popular Python keyword, or a
1843 ;; non- whitespace and non-comment character. These are good
1844 ;; places to start parsing to see whether where we started is
1845 ;; at a non-zero nesting level. It may be slow for people who
1846 ;; write huge code blocks or huge lists ... tough beans.
1847 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00001848 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001849 (beginning-of-line)
1850 (save-excursion
1851 (setq pps (parse-partial-sexp (point) here)))
1852 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00001853 (setq done (or (zerop ci)
1854 (not (nth 3 pps))
1855 (bobp)))
1856 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001857 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858
1859;; if point is at a non-zero nesting level, returns the number of the
1860;; character that opens the smallest enclosing unclosed list; else
1861;; returns nil.
1862(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864 (if (zerop (car status))
1865 nil ; not in a nest
1866 (car (cdr status))))) ; char# of open bracket
1867
1868;; t iff preceding line ends with backslash that's not in a comment
1869(defun py-backslash-continuation-line-p ()
1870 (save-excursion
1871 (beginning-of-line)
1872 (and
1873 ;; use a cheap test first to avoid the regexp if possible
1874 ;; use 'eq' because char-after may return nil
1875 (eq (char-after (- (point) 2)) ?\\ )
1876 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878 (looking-at py-continued-re))))
1879
1880;; t iff current line is a continuation line
1881(defun py-continuation-line-p ()
1882 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001883 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884 (or (py-backslash-continuation-line-p)
1885 (py-nesting-level))))
1886
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001887;; go to initial line of current statement; usually this is the line
1888;; we're on, but if we're on the 2nd or following lines of a
1889;; continuation block, we need to go up to the first line of the
1890;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001891;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892;; Tricky: We want to avoid quadratic-time behavior for long continued
1893;; blocks, whether of the backslash or open-bracket varieties, or a
1894;; mix of the two. The following manages to do that in the usual
1895;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896(defun py-goto-initial-line ()
1897 (let ( open-bracket-pos )
1898 (while (py-continuation-line-p)
1899 (beginning-of-line)
1900 (if (py-backslash-continuation-line-p)
1901 (while (py-backslash-continuation-line-p)
1902 (forward-line -1))
1903 ;; else zip out of nested brackets/braces/parens
1904 (while (setq open-bracket-pos (py-nesting-level))
1905 (goto-char open-bracket-pos)))))
1906 (beginning-of-line))
1907
1908;; go to point right beyond final line of current statement; usually
1909;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001910;; statement we need to skip over the continuation lines. Tricky:
1911;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001912(defun py-goto-beyond-final-line ()
1913 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001915 (while (and (py-continuation-line-p)
1916 (not (eobp)))
1917 ;; skip over the backslash flavor
1918 (while (and (py-backslash-continuation-line-p)
1919 (not (eobp)))
1920 (forward-line 1))
1921 ;; if in nest, zip to the end of the nest
1922 (setq state (py-parse-state))
1923 (if (and (not (zerop (car state)))
1924 (not (eobp)))
1925 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001926 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001927 ;; the 3rd argument should be plain 0
1928 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1929 nil state)
1930 (forward-line 1))))))
1931
1932;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001933;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934(defun py-statement-opens-block-p ()
1935 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936 (let ((start (point))
1937 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1938 (searching t)
1939 (answer nil)
1940 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941 (goto-char start)
1942 (while searching
1943 ;; look for a colon with nothing after it except whitespace, and
1944 ;; maybe a comment
1945 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1946 finish t)
1947 (if (eq (point) finish) ; note: no `else' clause; just
1948 ; keep searching if we're not at
1949 ; the end yet
1950 ;; sure looks like it opens a block -- but it might
1951 ;; be in a comment
1952 (progn
1953 (setq searching nil) ; search is done either way
1954 (setq state (parse-partial-sexp start
1955 (match-beginning 0)))
1956 (setq answer (not (nth 4 state)))))
1957 ;; search failed: couldn't find another interesting colon
1958 (setq searching nil)))
1959 answer)))
1960
Barry Warsawf831d811996-07-31 20:42:59 +00001961(defun py-statement-closes-block-p ()
1962 ;; true iff the current statement `closes' a block == the line
1963 ;; starts with `return', `raise', `break' or `continue'. doesn't
1964 ;; catch embedded statements
1965 (let ((here (point)))
1966 (back-to-indentation)
1967 (prog1
1968 (looking-at "\\(return\\|raise\\|break\\|continue\\)\\>")
1969 (goto-char here))))
1970
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971;; go to point right beyond final line of block begun by the current
1972;; line. This is the same as where py-goto-beyond-final-line goes
1973;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001975(defun py-goto-beyond-block ()
1976 (if (py-statement-opens-block-p)
1977 (py-mark-block nil 'just-move)
1978 (py-goto-beyond-final-line)))
1979
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980;; go to start of first statement (not blank or comment or
1981;; continuation line) at or preceding point. returns t if there is
1982;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001983(defun py-goto-statement-at-or-above ()
1984 (py-goto-initial-line)
1985 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001986 ;; skip back over blank & comment lines
1987 ;; note: will skip a blank or comment line that happens to be
1988 ;; a continuation line too
1989 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1990 (progn (py-goto-initial-line) t)
1991 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001992 t))
1993
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001994;; go to start of first statement (not blank or comment or
1995;; continuation line) following the statement containing point returns
1996;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001997(defun py-goto-statement-below ()
1998 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002000 (py-goto-beyond-final-line)
2001 (while (and
2002 (looking-at py-blank-or-comment-re)
2003 (not (eobp)))
2004 (forward-line 1))
2005 (if (eobp)
2006 (progn (goto-char start) nil)
2007 t)))
2008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002009;; go to start of statement, at or preceding point, starting with
2010;; keyword KEY. Skips blank lines and non-indenting comments upward
2011;; first. If that statement starts with KEY, done, else go back to
2012;; first enclosing block starting with KEY. If successful, leaves
2013;; point at the start of the KEY line & returns t. Else leaves point
2014;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015(defun py-go-up-tree-to-keyword (key)
2016 ;; skip blanks and non-indenting #
2017 (py-goto-initial-line)
2018 (while (and
2019 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2020 (zerop (forward-line -1))) ; go back
2021 nil)
2022 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023 (let* ((re (concat "[ \t]*" key "\\b"))
2024 (case-fold-search nil) ; let* so looking-at sees this
2025 (found (looking-at re))
2026 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (while (not (or found dead))
2028 (condition-case nil ; in case no enclosing block
2029 (py-goto-block-up 'no-mark)
2030 (error (setq dead t)))
2031 (or dead (setq found (looking-at re))))
2032 (beginning-of-line)
2033 found))
2034
2035;; return string in buffer from start of indentation to end of line;
2036;; prefix "..." if leading whitespace was skipped
2037(defun py-suck-up-leading-text ()
2038 (save-excursion
2039 (back-to-indentation)
2040 (concat
2041 (if (bolp) "" "...")
2042 (buffer-substring (point) (progn (end-of-line) (point))))))
2043
2044;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2045;; as a Lisp symbol; return nil if none
2046(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002047 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002048 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2049 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2050 nil)))
2051
2052(defun py-make-temp-name ()
2053 (make-temp-name
2054 (concat (file-name-as-directory py-temp-directory) "python")))
2055
2056(defun py-delete-file-silently (fname)
2057 (condition-case nil
2058 (delete-file fname)
2059 (error nil)))
2060
2061(defun py-kill-emacs-hook ()
2062 ;; delete our temp files
2063 (while py-file-queue
2064 (py-delete-file-silently (car py-file-queue))
2065 (setq py-file-queue (cdr py-file-queue)))
2066 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
2067 ;; run the hook we inherited, if any
2068 (and py-inherited-kill-emacs-hook
2069 (funcall py-inherited-kill-emacs-hook))))
2070
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002071;; make PROCESS's buffer visible, append STRING to it, and force
2072;; display; also make shell-mode believe the user typed this string,
2073;; so that kill-output-from-shell and show-output-from-shell work
2074;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002075(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002076 (let ((cbuf (current-buffer))
2077 (pbuf (process-buffer process))
2078 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002079 (set-buffer pbuf)
2080 (goto-char (point-max))
2081 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002082 (if (not (or py-this-is-emacs-19-p
2083 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002084 (move-marker last-input-start (point))) ; muck w/ shell-mode
2085 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00002086 (if (not (or py-this-is-emacs-19-p
2087 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002088 (move-marker last-input-end (point))) ; muck w/ shell-mode
2089 (set-buffer cbuf))
2090 (sit-for 0))
2091
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002092
2093
Barry Warsaw850437a1995-03-08 21:50:28 +00002094(defconst py-version "$Revision$"
2095 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002096(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002097 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002098
Barry Warsaw850437a1995-03-08 21:50:28 +00002099(defun py-version ()
2100 "Echo the current version of `python-mode' in the minibuffer."
2101 (interactive)
2102 (message "Using `python-mode' version %s" py-version)
2103 (py-keep-region-active))
2104
2105;; only works under Emacs 19
2106;(eval-when-compile
2107; (require 'reporter))
2108
2109(defun py-submit-bug-report (enhancement-p)
2110 "Submit via mail a bug report on `python-mode'.
2111With \\[universal-argument] just submit an enhancement request."
2112 (interactive
2113 (list (not (y-or-n-p
2114 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002115 (let ((reporter-prompt-for-summary-p (if enhancement-p
2116 "(Very) brief summary: "
2117 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002118 (require 'reporter)
2119 (reporter-submit-bug-report
2120 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002121 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002122 ;; varlist
2123 (if enhancement-p nil
2124 '(py-python-command
2125 py-indent-offset
2126 py-block-comment-prefix
2127 py-scroll-process-buffer
2128 py-temp-directory
2129 py-beep-if-tab-change))
2130 nil ;pre-hooks
2131 nil ;post-hooks
2132 "Dear Barry,") ;salutation
2133 (if enhancement-p nil
2134 (set-mark (point))
2135 (insert
2136"Please replace this text with a sufficiently large code sample\n\
2137and an exact recipe so that I can reproduce your problem. Failure\n\
2138to do so may mean a greater delay in fixing your bug.\n\n")
2139 (exchange-point-and-mark)
2140 (py-keep-region-active))))
2141
2142
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002143;; arrange to kill temp files when Emacs exists
2144(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2145 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2146 ;; have to trust that other people are as respectful of our hook
2147 ;; fiddling as we are of theirs
2148 (if (boundp 'py-inherited-kill-emacs-hook)
2149 ;; we were loaded before -- trust others not to have screwed us
2150 ;; in the meantime (no choice, really)
2151 nil
2152 ;; else arrange for our hook to run theirs
2153 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2154 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2155
2156
2157
2158(provide 'python-mode)
2159;;; python-mode.el ends here