blob: 229ba4e1e5aaf324c972700b7fbf3e6a9b8db0fb [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw4669d7e1996-03-22 16:13:24 +00005;; Author: 1995-1996 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
22;; by Tim Peters <tim@ksr.com> after an original idea by Michael
23;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000024;; (Barry) have undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
27;; line with GNU Emacs Lisp coding standards. But all in all, the
Barry Warsaw03970731996-07-03 23:12:52 +000028;; mode works exceedingly well, and I've simply been tweaking it as I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000029;; go along. Ain't it wonderful that Python has a much more sane
Barry Warsaw03970731996-07-03 23:12:52 +000030;; syntax than C? (or <shudder> C++?! :-). I can say that; I maintain
31;; cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
33;; The following statements, placed in your .emacs file or
34;; site-init.el, will cause this file to be autoloaded, and
35;; python-mode invoked, when visiting .py files (assuming this file is
36;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000037;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000041;;
42;; If you want font-lock support for Python source code (a.k.a. syntax
43;; coloring, highlighting), add this to your .emacs file:
44;;
45;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsaw7ae77681994-12-12 20:38:05 +000046
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000047;; Here's a brief list of recent additions/improvements:
48;;
49;; - Wrapping and indentation within triple quote strings should work
50;; properly now.
51;; - `Standard' bug reporting mechanism (use C-c C-b)
52;; - py-mark-block was moved to C-c C-m
53;; - C-c C-v shows you the python-mode version
54;; - a basic python-font-lock-keywords has been added for Emacs 19
55;; font-lock colorizations.
56;; - proper interaction with pending-del and del-sel modes.
57;; - New py-electric-colon (:) command for improved outdenting. Also
58;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw03970731996-07-03 23:12:52 +000059;; - improved (I think) C-c > and C-c <
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000060
Barry Warsaw7b0f5681995-03-08 21:33:04 +000061;; Here's a brief to do list:
62;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000063;; - Better integration with gud-mode for debugging.
64;; - Rewrite according to GNU Emacs Lisp standards.
65;; - py-delete-char should obey numeric arguments.
66;; - even better support for outdenting. Guido suggests outdents of
67;; at least one level after a return, raise, break, or continue
Barry Warsawfc9cc3a1996-07-08 22:37:06 +000068;; statement. I also suggest trying to match up try/finally's and
69;; the like.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000070;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsaw7b0f5681995-03-08 21:33:04 +000072;; If you can think of more things you'd like to see, drop me a line.
73;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
74;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000075;; Note that I only test things on XEmacs. If you port stuff to FSF
76;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
77;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000078
Barry Warsaw7b0f5681995-03-08 21:33:04 +000079;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000080;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000081;; |Major mode for editing Python programs
82;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000083
Barry Warsaw7b0f5681995-03-08 21:33:04 +000084;;; Code:
85
86
87;; user definable variables
88;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000089
90(defvar py-python-command "python"
91 "*Shell command used to start Python interpreter.")
92
Barry Warsaw17914f41995-11-03 18:25:15 +000093(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000094 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000095Note that `\\[py-guess-indent-offset]' can usually guess a good value
96when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000097
Barry Warsaw095e9c61995-09-19 20:01:42 +000098(defvar py-align-multiline-strings-p t
99 "*Flag describing how multiline triple quoted strings are aligned.
100When this flag is non-nil, continuation lines are lined up under the
101preceding line's indentation. When this flag is nil, continuation
102lines are aligned to column zero.")
103
Barry Warsaw7ae77681994-12-12 20:38:05 +0000104(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000105 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000106This should follow the convention for non-indenting comment lines so
107that the indentation commands won't get confused (i.e., the string
108should be of the form `#x...' where `x' is not a blank or a tab, and
109`...' is arbitrary).")
110
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000111(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000112 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000113
Barry Warsaw6d627751996-03-06 18:41:38 +0000114When nil, all comment lines are skipped for indentation purposes, and
115in Emacs 19, a faster algorithm is used.
116
117When t, lines that begin with a single `#' are a hint to subsequent
118line indentation. If the previous line is such a comment line (as
119opposed to one that starts with `py-block-comment-prefix'), then it's
120indentation is used as a hint for this line's indentation. Lines that
121begin with `py-block-comment-prefix' are ignored for indentation
122purposes.
123
124When not nil or t, comment lines that begin with a `#' are used as
125indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000126
Barry Warsaw7ae77681994-12-12 20:38:05 +0000127(defvar py-scroll-process-buffer t
128 "*Scroll Python process buffer as output arrives.
129If nil, the Python process buffer acts, with respect to scrolling, like
130Shell-mode buffers normally act. This is surprisingly complicated and
131so won't be explained here; in fact, you can't get the whole story
132without studying the Emacs C code.
133
134If non-nil, the behavior is different in two respects (which are
135slightly inaccurate in the interest of brevity):
136
137 - If the buffer is in a window, and you left point at its end, the
138 window will scroll as new output arrives, and point will move to the
139 buffer's end, even if the window is not the selected window (that
140 being the one the cursor is in). The usual behavior for shell-mode
141 windows is not to scroll, and to leave point where it was, if the
142 buffer is in a window other than the selected window.
143
144 - If the buffer is not visible in any window, and you left point at
145 its end, the buffer will be popped into a window as soon as more
146 output arrives. This is handy if you have a long-running
147 computation and don't want to tie up screen area waiting for the
148 output. The usual behavior for a shell-mode buffer is to stay
149 invisible until you explicitly visit it.
150
151Note the `and if you left point at its end' clauses in both of the
152above: you can `turn off' the special behaviors while output is in
153progress, by visiting the Python buffer and moving point to anywhere
154besides the end. Then the buffer won't scroll, point will remain where
155you leave it, and if you hide the buffer it will stay hidden until you
156visit it again. You can enable and disable the special behaviors as
157often as you like, while output is in progress, by (respectively) moving
158point to, or away from, the end of the buffer.
159
160Warning: If you expect a large amount of output, you'll probably be
161happier setting this option to nil.
162
163Obscure: `End of buffer' above should really say `at or beyond the
164process mark', but if you know what that means you didn't need to be
165told <grin>.")
166
167(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000168 (let ((ok '(lambda (x)
169 (and x
170 (setq x (expand-file-name x)) ; always true
171 (file-directory-p x)
172 (file-writable-p x)
173 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000174 (or (funcall ok (getenv "TMPDIR"))
175 (funcall ok "/usr/tmp")
176 (funcall ok "/tmp")
177 (funcall ok ".")
178 (error
179 "Couldn't find a usable temp directory -- set py-temp-directory")))
180 "*Directory used for temp files created by a *Python* process.
181By default, the first directory from this list that exists and that you
182can write into: the value (if any) of the environment variable TMPDIR,
183/usr/tmp, /tmp, or the current directory.")
184
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000185(defvar py-beep-if-tab-change t
186 "*Ring the bell if tab-width is changed.
187If a comment of the form
188
189 \t# vi:set tabsize=<number>:
190
191is found before the first code line when the file is entered, and the
192current value of (the general Emacs variable) `tab-width' does not
193equal <number>, `tab-width' is set to <number>, a message saying so is
194displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
195the Emacs bell is also rung as a warning.")
196
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000197(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000198 (let* ((keywords '("access" "and" "break" "class"
199 "continue" "def" "del" "elif"
200 "else:" "except" "except:" "exec"
201 "finally:" "for" "from" "global"
202 "if" "import" "in" "is"
203 "lambda" "not" "or" "pass"
204 "print" "raise" "return" "try:"
205 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000206 ))
207 (kwregex (mapconcat 'identity keywords "\\|")))
208 (list
209 ;; keywords not at beginning of line
210 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
211 ;; keywords at beginning of line. i don't think regexps are
212 ;; powerful enough to handle these two cases in one regexp.
213 ;; prove me wrong!
214 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
215 ;; classes
216 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
217 1 font-lock-type-face)
218 ;; functions
219 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
220 1 font-lock-function-name-face)
221 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000222 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000223
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000224
225;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
226;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
227
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000228(make-variable-buffer-local 'py-indent-offset)
229
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000230;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
231;; seems to be the standard way of checking this.
232;; BAW - This is *not* the right solution. When at all possible,
233;; instead of testing for the version of Emacs, use feature tests.
234
235(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
236(setq py-this-is-emacs-19-p
237 (and
238 (not py-this-is-lucid-emacs-p)
239 (string-match "^19\\." emacs-version)))
240
Barry Warsaw7ae77681994-12-12 20:38:05 +0000241;; have to bind py-file-queue before installing the kill-emacs hook
242(defvar py-file-queue nil
243 "Queue of Python temp files awaiting execution.
244Currently-active file is at the head of the list.")
245
246;; define a mode-specific abbrev table for those who use such things
247(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000248 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249(define-abbrev-table 'python-mode-abbrev-table nil)
250
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251(defvar python-mode-hook nil
252 "*Hook called by `python-mode'.")
253
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000254;; in previous version of python-mode.el, the hook was incorrectly
255;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000256(and (fboundp 'make-obsolete-variable)
257 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
258
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000259(defvar py-mode-map ()
260 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261
Barry Warsaw7ae77681994-12-12 20:38:05 +0000262(if py-mode-map
263 ()
264 (setq py-mode-map (make-sparse-keymap))
265
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000266 ;; shadow global bindings for newline-and-indent w/ the py- version.
267 ;; BAW - this is extremely bad form, but I'm not going to change it
268 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269 (mapcar (function (lambda (key)
270 (define-key
271 py-mode-map key 'py-newline-and-indent)))
272 (where-is-internal 'newline-and-indent))
273
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000274 ;; BAW - you could do it this way, but its not considered proper
275 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000276 (mapcar (function
277 (lambda (x)
278 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000279 '((":" . py-electric-colon)
280 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000281 ("\C-c|" . py-execute-region)
282 ("\C-c!" . py-shell)
283 ("\177" . py-delete-char)
284 ("\n" . py-newline-and-indent)
285 ("\C-c:" . py-guess-indent-offset)
286 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000287 ("\C-c\C-l" . py-shift-region-left)
288 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000289 ("\C-c<" . py-shift-region-left)
290 ("\C-c>" . py-shift-region-right)
291 ("\C-c\C-n" . py-next-statement)
292 ("\C-c\C-p" . py-previous-statement)
293 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000294 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000295 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000296 ("\C-c?" . py-describe-mode)
297 ("\C-c\C-hm" . py-describe-mode)
298 ("\e\C-a" . beginning-of-python-def-or-class)
299 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000300 ( "\e\C-h" . mark-python-def-or-class)))
301 ;; should do all keybindings this way
302 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
303 (define-key py-mode-map "\C-c\C-v" 'py-version)
304 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000305
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000306(defvar py-mode-syntax-table nil
307 "Syntax table used in `python-mode' buffers.")
308
Barry Warsaw7ae77681994-12-12 20:38:05 +0000309(if py-mode-syntax-table
310 ()
311 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000312 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000313 (mapcar (function
314 (lambda (x) (modify-syntax-entry
315 (car x) (cdr x) py-mode-syntax-table)))
316 '(( ?\( . "()" ) ( ?\) . ")(" )
317 ( ?\[ . "(]" ) ( ?\] . ")[" )
318 ( ?\{ . "(}" ) ( ?\} . "){" )
319 ;; fix operator symbols misassigned in the std table
320 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
321 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
322 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
323 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000324 ;; Guido and I disagree about this. Underscore should be
325 ;; symbol constituent by not word. For historical
326 ;; reasons, I leave it as is. -baw
327 ;;( ?\_ . "_" ) ; underscore is legit in symbols, but not words
328 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000329 ( ?\' . "\"") ; single quote is string quote
330 ( ?\" . "\"" ) ; double quote is string quote too
331 ( ?\` . "$") ; backquote is open and close paren
332 ( ?\# . "<") ; hash starts comment
333 ( ?\n . ">")))) ; newline ends comment
334
335(defconst py-stringlit-re
336 (concat
337 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
338 "\\|" ; or
339 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000340 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000341
342;; this is tricky because a trailing backslash does not mean
343;; continuation if it's in a comment
344(defconst py-continued-re
345 (concat
346 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
347 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000348 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000349
350(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000351 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000352
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000353(defconst py-outdent-re
354 (concat "\\(" (mapconcat 'identity
355 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000356 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000357 "finally:"
358 "elif\\s +.*:")
359 "\\|")
360 "\\)")
361 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000362
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000363(defconst py-no-outdent-re
364 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000365 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000366 "except\\(\\s +.*\\)?:"
367 "while\\s +.*:"
368 "for\\s +.*:"
369 "if\\s +.*:"
370 "elif\\s +.*:")
371 "\\|")
372 "\\)")
373 "Regexp matching lines to not outdent after.")
374
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000375
376;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000377(defun python-mode ()
378 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000379To submit a problem report, enter `\\[py-submit-bug-report]' from a
380`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
381documentation. To see what version of `python-mode' you are running,
382enter `\\[py-version]'.
383
384This mode knows about Python indentation, tokens, comments and
385continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386
387COMMANDS
388\\{py-mode-map}
389VARIABLES
390
391py-indent-offset\tindentation increment
392py-block-comment-prefix\tcomment string used by py-comment-region
393py-python-command\tshell command to invoke Python interpreter
394py-scroll-process-buffer\talways scroll Python process buffer
395py-temp-directory\tdirectory used for temp files (if needed)
396py-beep-if-tab-change\tring the bell if tab-width is changed"
397 (interactive)
398 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000399 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000400 (setq major-mode 'python-mode
401 mode-name "Python"
402 local-abbrev-table python-mode-abbrev-table)
403 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000404 ;; Emacs 19 requires this
405 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
406 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000407 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000408 (mapcar (function (lambda (x)
409 (make-local-variable (car x))
410 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000411 '((paragraph-separate . "^[ \t]*$")
412 (paragraph-start . "^[ \t]*$")
413 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000414 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000415 (comment-start-skip . "# *")
416 (comment-column . 40)
417 (indent-region-function . py-indent-region)
418 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000419 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000420 ;;
421 ;; not sure where the magic comment has to be; to save time
422 ;; searching for a rarity, we give up if it's not found prior to the
423 ;; first executable statement.
424 ;;
425 ;; BAW - on first glance, this seems like complete hackery. Why was
426 ;; this necessary, and is it still necessary?
427 (let ((case-fold-search nil)
428 (start (point))
429 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000430 (if (re-search-forward
431 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
432 (prog2 (py-next-statement 1) (point) (goto-char 1))
433 t)
434 (progn
435 (setq new-tab-width
436 (string-to-int
437 (buffer-substring (match-beginning 1) (match-end 1))))
438 (if (= tab-width new-tab-width)
439 nil
440 (setq tab-width new-tab-width)
441 (message "Caution: tab-width changed to %d" new-tab-width)
442 (if py-beep-if-tab-change (beep)))))
443 (goto-char start))
444
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000445 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000446 (if python-mode-hook
447 (run-hooks 'python-mode-hook)
448 (run-hooks 'py-mode-hook)))
449
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000450
Barry Warsaw826255b1996-03-22 16:09:34 +0000451(defun py-keep-region-active ()
452 ;; Do whatever is necessary to keep the region active in
453 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
454 ;; ignore byte-compiler warnings you might see.
455 (and (boundp 'zmacs-region-stays)
456 (setq zmacs-region-stays t)))
457
Barry Warsawb91b7431995-03-14 15:55:20 +0000458;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000459(defun py-outdent-p ()
460 ;; returns non-nil if the current line should outdent one level
461 (save-excursion
462 (and (progn (back-to-indentation)
463 (looking-at py-outdent-re))
464 (progn (backward-to-indentation 1)
465 (while (or (looking-at py-blank-or-comment-re)
466 (bobp))
467 (backward-to-indentation 1))
468 (not (looking-at py-no-outdent-re)))
469 )))
470
471
Barry Warsawb91b7431995-03-14 15:55:20 +0000472(defun py-electric-colon (arg)
473 "Insert a colon.
474In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000475argument is provided, that many colons are inserted non-electrically.
476Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000477 (interactive "P")
478 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000479 ;; are we in a string or comment?
480 (if (save-excursion
481 (let ((pps (parse-partial-sexp (save-excursion
482 (beginning-of-python-def-or-class)
483 (point))
484 (point))))
485 (not (or (nth 3 pps) (nth 4 pps)))))
486 (save-excursion
487 (let ((here (point))
488 (outdent 0)
489 (indent (py-compute-indentation)))
490 (if (and (not arg)
491 (py-outdent-p)
492 (= indent (save-excursion
493 (forward-line -1)
494 (py-compute-indentation)))
495 )
496 (setq outdent py-indent-offset))
497 ;; Don't indent, only outdent. This assumes that any lines that
498 ;; are already outdented relative to py-compute-indentation were
499 ;; put there on purpose. Its highly annoying to have `:' indent
500 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
501 ;; there a better way to determine this???
502 (if (< (current-indentation) indent) nil
503 (goto-char here)
504 (beginning-of-line)
505 (delete-horizontal-space)
506 (indent-to (- indent outdent))
507 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000508
509
Barry Warsaw7ae77681994-12-12 20:38:05 +0000510;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000511(defun py-shell ()
512 "Start an interactive Python interpreter in another window.
513This is like Shell mode, except that Python is running in the window
514instead of a shell. See the `Interactive Shell' and `Shell Mode'
515sections of the Emacs manual for details, especially for the key
516bindings active in the `*Python*' buffer.
517
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000518See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000519behavior in the process window.
520
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000521Warning: Don't use an interactive Python if you change sys.ps1 or
522sys.ps2 from their default values, or if you're running code that
523prints `>>> ' or `... ' at the start of a line. `python-mode' can't
524distinguish your output from Python's output, and assumes that `>>> '
525at the start of a line is a prompt from Python. Similarly, the Emacs
526Shell mode code assumes that both `>>> ' and `... ' at the start of a
527line are Python prompts. Bad things can happen if you fool either
528mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000529
530Warning: If you do any editing *in* the process buffer *while* the
531buffer is accepting output from Python, do NOT attempt to `undo' the
532changes. Some of the output (nowhere near the parts you changed!) may
533be lost if you do. This appears to be an Emacs bug, an unfortunate
534interaction between undo and process filters; the same problem exists in
535non-Python process buffers using the default (Emacs-supplied) process
536filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000537 ;; BAW - should undo be disabled in the python process buffer, if
538 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539 (interactive)
540 (if py-this-is-emacs-19-p
541 (progn
542 (require 'comint)
543 (switch-to-buffer-other-window
544 (make-comint "Python" py-python-command)))
545 (progn
546 (require 'shell)
547 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000548 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000549 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000550 (make-local-variable 'shell-prompt-pattern)
551 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
552 (set-process-filter (get-buffer-process (current-buffer))
553 'py-process-filter)
554 (set-syntax-table py-mode-syntax-table))
555
556(defun py-execute-region (start end)
557 "Send the region between START and END to a Python interpreter.
558If there is a *Python* process it is used.
559
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000560Hint: If you want to execute part of a Python file several times
561\(e.g., perhaps you're developing a function and want to flesh it out
562a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
563the region of interest, and send the code to a *Python* process via
564`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000565
566Following are subtleties to note when using a *Python* process:
567
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000568If a *Python* process is used, the region is copied into a temporary
569file (in directory `py-temp-directory'), and an `execfile' command is
570sent to Python naming that file. If you send regions faster than
571Python can execute them, `python-mode' will save them into distinct
572temp files, and execute the next one in the queue the next time it
573sees a `>>> ' prompt from Python. Each time this happens, the process
574buffer is popped into a window (if it's not already in some window) so
575you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000577 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000578
579is inserted at the end.
580
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000581Caution: No more than 26 regions can be pending at any given time.
582This limit is (indirectly) inherited from libc's mktemp(3).
583`python-mode' does not try to protect you from exceeding the limit.
584It's extremely unlikely that you'll get anywhere close to the limit in
585practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000586
587See the `\\[py-shell]' docs for additional warnings."
588 (interactive "r")
589 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000590 (let ((pyproc (get-process "Python"))
591 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000592 (if (null pyproc)
593 (shell-command-on-region start end py-python-command)
594 ;; else feed it thru a temp file
595 (setq fname (py-make-temp-name))
596 (write-region start end fname nil 'no-msg)
597 (setq py-file-queue (append py-file-queue (list fname)))
598 (if (cdr py-file-queue)
599 (message "File %s queued for execution" fname)
600 ;; else
601 (py-execute-file pyproc fname)))))
602
603(defun py-execute-file (pyproc fname)
604 (py-append-to-process-buffer
605 pyproc
606 (format "## working on region in file %s ...\n" fname))
607 (process-send-string pyproc (format "execfile('%s')\n" fname)))
608
609(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000610 (let ((curbuf (current-buffer))
611 (pbuf (process-buffer pyproc))
612 (pmark (process-mark pyproc))
613 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000614
615 ;; make sure we switch to a different buffer at least once. if we
616 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000617 ;; window, and point is before the end, and lots of output is
618 ;; coming at a fast pace, then (a) simple cursor-movement commands
619 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
620 ;; to have a visible effect (the window just doesn't get updated,
621 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
622 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000623 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000624 ;; #b makes no sense to me at all. #a almost makes sense: unless
625 ;; we actually change buffers, set_buffer_internal in buffer.c
626 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
627 ;; seems to make the Emacs command loop reluctant to update the
628 ;; display. Perhaps the default process filter in process.c's
629 ;; read_process_output has update_mode_lines++ for a similar
630 ;; reason? beats me ...
631
632 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000633 (if (eq curbuf pbuf) ; mysterious ugly hack
634 (set-buffer (get-buffer-create "*scratch*")))
635
636 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000637 (let* ((start (point))
638 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000639 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000640 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000641 (goto-char pmark)
642 (insert string)
643 (move-marker pmark (point))
644 (setq file-finished
645 (and py-file-queue
646 (equal ">>> "
647 (buffer-substring
648 (prog2 (beginning-of-line) (point)
649 (goto-char pmark))
650 (point)))))
651 (if goback (goto-char start)
652 ;; else
653 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000654 (let* ((pop-up-windows t)
655 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000656 (set-window-point pwin (point)))))
657 (set-buffer curbuf)
658 (if file-finished
659 (progn
660 (py-delete-file-silently (car py-file-queue))
661 (setq py-file-queue (cdr py-file-queue))
662 (if py-file-queue
663 (py-execute-file pyproc (car py-file-queue)))))
664 (and goend
665 (progn (set-buffer pbuf)
666 (goto-char (point-max))))
667 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000668
669(defun py-execute-buffer ()
670 "Send the contents of the buffer to a Python interpreter.
671If there is a *Python* process buffer it is used. If a clipping
672restriction is in effect, only the accessible portion of the buffer is
673sent. A trailing newline will be supplied if needed.
674
675See the `\\[py-execute-region]' docs for an account of some subtleties."
676 (interactive)
677 (py-execute-region (point-min) (point-max)))
678
679
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000680
681;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000682(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000683 "Reduce indentation or delete character.
684If point is at the leftmost column, deletes the preceding newline.
685
686Else if point is at the leftmost non-blank character of a line that is
687neither a continuation line nor a non-indenting comment line, or if
688point is at the end of a blank line, reduces the indentation to match
689that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000690opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000691of where you are. With numeric count, outdents that many blocks (but
692not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000693
694Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000695needed so that only a single column position is deleted. Numeric
696argument delets that many characters."
697 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000698 (if (or (/= (current-indentation) (current-column))
699 (bolp)
700 (py-continuation-line-p)
701 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000702 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000703 ;; else indent the same as the colon line that opened the block
704
705 ;; force non-blank so py-goto-block-up doesn't ignore it
706 (insert-char ?* 1)
707 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708 (let ((base-indent 0) ; indentation of base line
709 (base-text "") ; and text of base line
710 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000711 (save-excursion
712 (while (< 0 count)
713 (condition-case nil ; in case no enclosing block
714 (progn
715 (py-goto-block-up 'no-mark)
716 (setq base-indent (current-indentation)
717 base-text (py-suck-up-leading-text)
718 base-found-p t))
719 (error nil))
720 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000721 (delete-char 1) ; toss the dummy character
722 (delete-horizontal-space)
723 (indent-to base-indent)
724 (if base-found-p
725 (message "Closes block: %s" base-text)))))
726
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000727;; required for pending-del and delsel modes
728(put 'py-delete-char 'delete-selection 'supersede)
729(put 'py-delete-char 'pending-delete 'supersede)
730
Barry Warsaw7ae77681994-12-12 20:38:05 +0000731(defun py-indent-line ()
732 "Fix the indentation of the current line according to Python rules."
733 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000734 (let* ((ci (current-indentation))
735 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000736 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000737 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000738 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000739 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000740 (if (/= ci need)
741 (save-excursion
742 (beginning-of-line)
743 (delete-horizontal-space)
744 (indent-to need)))
745 (if move-to-indentation-p (back-to-indentation))))
746
747(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000748 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000749This is just `strives to' because correct indentation can't be computed
750from scratch for Python code. In general, deletes the whitespace before
751point, inserts a newline, and takes an educated guess as to how you want
752the new line indented."
753 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000754 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000755 (if (< ci (current-column)) ; if point beyond indentation
756 (newline-and-indent)
757 ;; else try to act like newline-and-indent "normally" acts
758 (beginning-of-line)
759 (insert-char ?\n 1)
760 (move-to-column ci))))
761
762(defun py-compute-indentation ()
763 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000764 (let ((pps (parse-partial-sexp (save-excursion
765 (beginning-of-python-def-or-class)
766 (point))
767 (point))))
768 (beginning-of-line)
769 (cond
770 ;; are we inside a string or comment?
771 ((or (nth 3 pps) (nth 4 pps))
772 (save-excursion
773 (if (not py-align-multiline-strings-p) 0
774 ;; skip back over blank & non-indenting comment lines
775 ;; note: will skip a blank or non-indenting comment line
776 ;; that happens to be a continuation line too
777 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
778 (back-to-indentation)
779 (current-column))))
780 ;; are we on a continuation line?
781 ((py-continuation-line-p)
782 (let ((startpos (point))
783 (open-bracket-pos (py-nesting-level))
784 endpos searching found)
785 (if open-bracket-pos
786 (progn
787 ;; align with first item in list; else a normal
788 ;; indent beyond the line with the open bracket
789 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
790 ;; is the first list item on the same line?
791 (skip-chars-forward " \t")
792 (if (null (memq (following-char) '(?\n ?# ?\\)))
793 ; yes, so line up with it
794 (current-column)
795 ;; first list item on another line, or doesn't exist yet
796 (forward-line 1)
797 (while (and (< (point) startpos)
798 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
799 (forward-line 1))
800 (if (< (point) startpos)
801 ;; again mimic the first list item
802 (current-indentation)
803 ;; else they're about to enter the first item
804 (goto-char open-bracket-pos)
805 (+ (current-indentation) py-indent-offset))))
806
807 ;; else on backslash continuation line
808 (forward-line -1)
809 (if (py-continuation-line-p) ; on at least 3rd line in block
810 (current-indentation) ; so just continue the pattern
811 ;; else started on 2nd line in block, so indent more.
812 ;; if base line is an assignment with a start on a RHS,
813 ;; indent to 2 beyond the leftmost "="; else skip first
814 ;; chunk of non-whitespace characters on base line, + 1 more
815 ;; column
816 (end-of-line)
817 (setq endpos (point) searching t)
818 (back-to-indentation)
819 (setq startpos (point))
820 ;; look at all "=" from left to right, stopping at first
821 ;; one not nested in a list or string
822 (while searching
823 (skip-chars-forward "^=" endpos)
824 (if (= (point) endpos)
825 (setq searching nil)
826 (forward-char 1)
827 (setq state (parse-partial-sexp startpos (point)))
828 (if (and (zerop (car state)) ; not in a bracket
829 (null (nth 3 state))) ; & not in a string
830 (progn
831 (setq searching nil) ; done searching in any case
832 (setq found
833 (not (or
834 (eq (following-char) ?=)
835 (memq (char-after (- (point) 2))
836 '(?< ?> ?!)))))))))
837 (if (or (not found) ; not an assignment
838 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
839 (progn
840 (goto-char startpos)
841 (skip-chars-forward "^ \t\n")))
842 (1+ (current-column))))))
843
844 ;; not on a continuation line
845
846 ;; if at start of restriction, or on a non-indenting comment
847 ;; line, assume they intended whatever's there
848 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
849 (current-indentation))
850
851 ;; else indentation based on that of the statement that
852 ;; precedes us; use the first line of that statement to
853 ;; establish the base, in case the user forced a non-std
854 ;; indentation for the continuation lines (if any)
855 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000856 ;; skip back over blank & non-indenting comment lines note:
857 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000858 ;; happens to be a continuation line too. use fast Emacs 19
859 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000860 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000861 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000862 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000863 (let (done)
864 (while (not done)
865 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
866 nil 'move)
867 (setq done (or (eq py-honor-comment-indentation t)
868 (bobp)
869 (/= (following-char) ?#)
870 (not (zerop (current-column)))))
871 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000872 ;; if we landed inside a string, go to the beginning of that
873 ;; string. this handles triple quoted, multi-line spanning
874 ;; strings.
875 (py-goto-initial-line)
876 (if (py-statement-opens-block-p)
877 (+ (current-indentation) py-indent-offset)
878 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000879
880(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000881 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000883`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000884Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000885`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000886their own buffer-local copy), both those currently existing and those
887created later in the Emacs session.
888
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000890There's no excuse for such foolishness, but sometimes you have to deal
891with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000892`py-indent-offset' to what it thinks it was when they created the
893mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000894
895Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000896looking for a line that opens a block of code. `py-indent-offset' is
897set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898statement following it. If the search doesn't succeed going forward,
899it's tried again going backward."
900 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000901 (let (new-value
902 (start (point))
903 restart
904 (found nil)
905 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906 (py-goto-initial-line)
907 (while (not (or found (eobp)))
908 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
909 (progn
910 (setq restart (point))
911 (py-goto-initial-line)
912 (if (py-statement-opens-block-p)
913 (setq found t)
914 (goto-char restart)))))
915 (if found
916 ()
917 (goto-char start)
918 (py-goto-initial-line)
919 (while (not (or found (bobp)))
920 (setq found
921 (and
922 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
923 (or (py-goto-initial-line) t) ; always true -- side effect
924 (py-statement-opens-block-p)))))
925 (setq colon-indent (current-indentation)
926 found (and found (zerop (py-next-statement 1)))
927 new-value (- (current-indentation) colon-indent))
928 (goto-char start)
929 (if found
930 (progn
931 (funcall (if global 'kill-local-variable 'make-local-variable)
932 'py-indent-offset)
933 (setq py-indent-offset new-value)
934 (message "%s value of py-indent-offset set to %d"
935 (if global "Global" "Local")
936 py-indent-offset))
937 (error "Sorry, couldn't guess a value for py-indent-offset"))))
938
939(defun py-shift-region (start end count)
940 (save-excursion
941 (goto-char end) (beginning-of-line) (setq end (point))
942 (goto-char start) (beginning-of-line) (setq start (point))
943 (indent-rigidly start end count)))
944
945(defun py-shift-region-left (start end &optional count)
946 "Shift region of Python code to the left.
947The lines from the line containing the start of the current region up
948to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000949shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000950
951If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000952many columns. With no active region, outdent only the current line.
953You cannot outdent the region if any line is already at column zero."
954 (interactive
955 (let ((p (point))
956 (m (mark))
957 (arg current-prefix-arg))
958 (if m
959 (list (min p m) (max p m) arg)
960 (list p (save-excursion (forward-line 1) (point)) arg))))
961 ;; if any line is at column zero, don't shift the region
962 (save-excursion
963 (goto-char start)
964 (while (< (point) end)
965 (back-to-indentation)
966 (if (zerop (current-column))
967 (error "Region is at left edge."))
968 (forward-line 1)))
969 (py-shift-region start end (- (prefix-numeric-value
970 (or count py-indent-offset))))
971 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000972
973(defun py-shift-region-right (start end &optional count)
974 "Shift region of Python code to the right.
975The lines from the line containing the start of the current region up
976to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000977shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978
979If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000980many columns. With no active region, indent only the current line."
981 (interactive
982 (let ((p (point))
983 (m (mark))
984 (arg current-prefix-arg))
985 (if m
986 (list (min p m) (max p m) arg)
987 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000989 (or count py-indent-offset)))
990 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000991
992(defun py-indent-region (start end &optional indent-offset)
993 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000994
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995The lines from the line containing the start of the current region up
996to (but not including) the line containing the end of the region are
997reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000998character in the first column, the first line is left alone and the
999rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001000region is reindented with respect to the (closest code or indenting
1001comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002
1003This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004control structures are introduced or removed, or to reformat code
1005using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006
1007If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001008the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001009used.
1010
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001011Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012is called! This function does not compute proper indentation from
1013scratch (that's impossible in Python), it merely adjusts the existing
1014indentation to be correct in context.
1015
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001016Warning: This function really has no idea what to do with
1017non-indenting comment lines, and shifts them as if they were indenting
1018comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020Special cases: whitespace is deleted from blank lines; continuation
1021lines are shifted by the same amount their initial line was shifted,
1022in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001025 (save-excursion
1026 (goto-char end) (beginning-of-line) (setq end (point-marker))
1027 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028 (let ((py-indent-offset (prefix-numeric-value
1029 (or indent-offset py-indent-offset)))
1030 (indents '(-1)) ; stack of active indent levels
1031 (target-column 0) ; column to which to indent
1032 (base-shifted-by 0) ; amount last base line was shifted
1033 (indent-base (if (looking-at "[ \t\n]")
1034 (py-compute-indentation)
1035 0))
1036 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001037 (while (< (point) end)
1038 (setq ci (current-indentation))
1039 ;; figure out appropriate target column
1040 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001041 ((or (eq (following-char) ?#) ; comment in column 1
1042 (looking-at "[ \t]*$")) ; entirely blank
1043 (setq target-column 0))
1044 ((py-continuation-line-p) ; shift relative to base line
1045 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001046 (t ; new base line
1047 (if (> ci (car indents)) ; going deeper; push it
1048 (setq indents (cons ci indents))
1049 ;; else we should have seen this indent before
1050 (setq indents (memq ci indents)) ; pop deeper indents
1051 (if (null indents)
1052 (error "Bad indentation in region, at line %d"
1053 (save-restriction
1054 (widen)
1055 (1+ (count-lines 1 (point)))))))
1056 (setq target-column (+ indent-base
1057 (* py-indent-offset
1058 (- (length indents) 2))))
1059 (setq base-shifted-by (- target-column ci))))
1060 ;; shift as needed
1061 (if (/= ci target-column)
1062 (progn
1063 (delete-horizontal-space)
1064 (indent-to target-column)))
1065 (forward-line 1))))
1066 (set-marker end nil))
1067
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001068
1069;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070(defun py-previous-statement (count)
1071 "Go to the start of previous Python statement.
1072If the statement at point is the i'th Python statement, goes to the
1073start of statement i-COUNT. If there is no such statement, goes to the
1074first statement. Returns count of statements left to move.
1075`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001076 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001077 (if (< count 0) (py-next-statement (- count))
1078 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001079 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001080 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001081 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001082 (> count 0)
1083 (zerop (forward-line -1))
1084 (py-goto-statement-at-or-above))
1085 (setq count (1- count)))
1086 (if (> count 0) (goto-char start)))
1087 count))
1088
1089(defun py-next-statement (count)
1090 "Go to the start of next Python statement.
1091If the statement at point is the i'th Python statement, goes to the
1092start of statement i+COUNT. If there is no such statement, goes to the
1093last statement. Returns count of statements left to move. `Statements'
1094do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001095 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001096 (if (< count 0) (py-previous-statement (- count))
1097 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001098 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001099 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001100 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001101 (> count 0)
1102 (py-goto-statement-below))
1103 (setq count (1- count)))
1104 (if (> count 0) (goto-char start)))
1105 count))
1106
1107(defun py-goto-block-up (&optional nomark)
1108 "Move up to start of current block.
1109Go to the statement that starts the smallest enclosing block; roughly
1110speaking, this will be the closest preceding statement that ends with a
1111colon and is indented less than the statement you started on. If
1112successful, also sets the mark to the starting point.
1113
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001114`\\[py-mark-block]' can be used afterward to mark the whole code
1115block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116
1117If called from a program, the mark will not be set if optional argument
1118NOMARK is not nil."
1119 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001120 (let ((start (point))
1121 (found nil)
1122 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001123 (py-goto-initial-line)
1124 ;; if on blank or non-indenting comment line, use the preceding stmt
1125 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1126 (progn
1127 (py-goto-statement-at-or-above)
1128 (setq found (py-statement-opens-block-p))))
1129 ;; search back for colon line indented less
1130 (setq initial-indent (current-indentation))
1131 (if (zerop initial-indent)
1132 ;; force fast exit
1133 (goto-char (point-min)))
1134 (while (not (or found (bobp)))
1135 (setq found
1136 (and
1137 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1138 (or (py-goto-initial-line) t) ; always true -- side effect
1139 (< (current-indentation) initial-indent)
1140 (py-statement-opens-block-p))))
1141 (if found
1142 (progn
1143 (or nomark (push-mark start))
1144 (back-to-indentation))
1145 (goto-char start)
1146 (error "Enclosing block not found"))))
1147
1148(defun beginning-of-python-def-or-class (&optional class)
1149 "Move point to start of def (or class, with prefix arg).
1150
1151Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001152arg, looks for a `class' instead. The docs assume the `def' case;
1153just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001154
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001155If point is in a def statement already, and after the `d', simply
1156moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001158Else (point is not in a def statement, or at or before the `d' of a
1159def statement), searches for the closest preceding def statement, and
1160leaves point at its start. If no such statement can be found, leaves
1161point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162
1163Returns t iff a def statement is found by these rules.
1164
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001165Note that doing this command repeatedly will take you closer to the
1166start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001167
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001168If you want to mark the current def/class, see
1169`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001170 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001171 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1172 (start-of-line (progn (beginning-of-line) (point)))
1173 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174 (if (or (/= start-of-stmt start-of-line)
1175 (not at-or-before-p))
1176 (end-of-line)) ; OK to match on this line
1177 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001178 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001179
1180(defun end-of-python-def-or-class (&optional class)
1181 "Move point beyond end of def (or class, with prefix arg) body.
1182
1183By default, looks for an appropriate `def'. If you supply a prefix arg,
1184looks for a `class' instead. The docs assume the `def' case; just
1185substitute `class' for `def' for the other case.
1186
1187If point is in a def statement already, this is the def we use.
1188
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001189Else if the def found by `\\[beginning-of-python-def-or-class]'
1190contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001191
1192Else we search forward for the closest following def, and use that.
1193
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001194If a def can be found by these rules, point is moved to the start of
1195the line immediately following the def block, and the position of the
1196start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001197
1198Else point is moved to the end of the buffer, and nil is returned.
1199
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001200Note that doing this command repeatedly will take you closer to the
1201end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001202
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001203If you want to mark the current def/class, see
1204`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001205 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001206 (let ((start (progn (py-goto-initial-line) (point)))
1207 (which (if class "class" "def"))
1208 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001209 ;; move point to start of appropriate def/class
1210 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1211 (setq state 'at-beginning)
1212 ;; else see if beginning-of-python-def-or-class hits container
1213 (if (and (beginning-of-python-def-or-class class)
1214 (progn (py-goto-beyond-block)
1215 (> (point) start)))
1216 (setq state 'at-end)
1217 ;; else search forward
1218 (goto-char start)
1219 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1220 (progn (setq state 'at-beginning)
1221 (beginning-of-line)))))
1222 (cond
1223 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1224 ((eq state 'at-end) t)
1225 ((eq state 'not-found) nil)
1226 (t (error "internal error in end-of-python-def-or-class")))))
1227
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001228
1229;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001230(defun py-mark-block (&optional extend just-move)
1231 "Mark following block of lines. With prefix arg, mark structure.
1232Easier to use than explain. It sets the region to an `interesting'
1233block of succeeding lines. If point is on a blank line, it goes down to
1234the next non-blank line. That will be the start of the region. The end
1235of the region depends on the kind of line at the start:
1236
1237 - If a comment, the region will include all succeeding comment lines up
1238 to (but not including) the next non-comment line (if any).
1239
1240 - Else if a prefix arg is given, and the line begins one of these
1241 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001242
1243 if elif else try except finally for while def class
1244
Barry Warsaw7ae77681994-12-12 20:38:05 +00001245 the region will be set to the body of the structure, including
1246 following blocks that `belong' to it, but excluding trailing blank
1247 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001248 and all (if any) of the following `except' and `finally' blocks
1249 that belong to the `try' structure will be in the region. Ditto
1250 for if/elif/else, for/else and while/else structures, and (a bit
1251 degenerate, since they're always one-block structures) def and
1252 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001253
1254 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001255 block (see list above), and the block is not a `one-liner' (i.e.,
1256 the statement ends with a colon, not with code), the region will
1257 include all succeeding lines up to (but not including) the next
1258 code statement (if any) that's indented no more than the starting
1259 line, except that trailing blank and comment lines are excluded.
1260 E.g., if the starting line begins a multi-statement `def'
1261 structure, the region will be set to the full function definition,
1262 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001263
1264 - Else the region will include all succeeding lines up to (but not
1265 including) the next blank line, or code or indenting-comment line
1266 indented strictly less than the starting line. Trailing indenting
1267 comment lines are included in this case, but not trailing blank
1268 lines.
1269
1270A msg identifying the location of the mark is displayed in the echo
1271area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1272
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001273If called from a program, optional argument EXTEND plays the role of
1274the prefix arg, and if optional argument JUST-MOVE is not nil, just
1275moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001276 (interactive "P") ; raw prefix arg
1277 (py-goto-initial-line)
1278 ;; skip over blank lines
1279 (while (and
1280 (looking-at "[ \t]*$") ; while blank line
1281 (not (eobp))) ; & somewhere to go
1282 (forward-line 1))
1283 (if (eobp)
1284 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001285 (let ((initial-pos (point))
1286 (initial-indent (current-indentation))
1287 last-pos ; position of last stmt in region
1288 (followers
1289 '((if elif else) (elif elif else) (else)
1290 (try except finally) (except except) (finally)
1291 (for else) (while else)
1292 (def) (class) ) )
1293 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001294
1295 (cond
1296 ;; if comment line, suck up the following comment lines
1297 ((looking-at "[ \t]*#")
1298 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1299 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1300 (setq last-pos (point)))
1301
1302 ;; else if line is a block line and EXTEND given, suck up
1303 ;; the whole structure
1304 ((and extend
1305 (setq first-symbol (py-suck-up-first-keyword) )
1306 (assq first-symbol followers))
1307 (while (and
1308 (or (py-goto-beyond-block) t) ; side effect
1309 (forward-line -1) ; side effect
1310 (setq last-pos (point)) ; side effect
1311 (py-goto-statement-below)
1312 (= (current-indentation) initial-indent)
1313 (setq next-symbol (py-suck-up-first-keyword))
1314 (memq next-symbol (cdr (assq first-symbol followers))))
1315 (setq first-symbol next-symbol)))
1316
1317 ;; else if line *opens* a block, search for next stmt indented <=
1318 ((py-statement-opens-block-p)
1319 (while (and
1320 (setq last-pos (point)) ; always true -- side effect
1321 (py-goto-statement-below)
1322 (> (current-indentation) initial-indent))
1323 nil))
1324
1325 ;; else plain code line; stop at next blank line, or stmt or
1326 ;; indenting comment line indented <
1327 (t
1328 (while (and
1329 (setq last-pos (point)) ; always true -- side effect
1330 (or (py-goto-beyond-final-line) t)
1331 (not (looking-at "[ \t]*$")) ; stop at blank line
1332 (or
1333 (>= (current-indentation) initial-indent)
1334 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1335 nil)))
1336
1337 ;; skip to end of last stmt
1338 (goto-char last-pos)
1339 (py-goto-beyond-final-line)
1340
1341 ;; set mark & display
1342 (if just-move
1343 () ; just return
1344 (push-mark (point) 'no-msg)
1345 (forward-line -1)
1346 (message "Mark set after: %s" (py-suck-up-leading-text))
1347 (goto-char initial-pos))))
1348
1349(defun mark-python-def-or-class (&optional class)
1350 "Set region to body of def (or class, with prefix arg) enclosing point.
1351Pushes the current mark, then point, on the mark ring (all language
1352modes do this, but although it's handy it's never documented ...).
1353
1354In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001355hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1356`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001357
1358And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359Turned out that was more confusing than useful: the `goto start' and
1360`goto end' commands are usually used to search through a file, and
1361people expect them to act a lot like `search backward' and `search
1362forward' string-search commands. But because Python `def' and `class'
1363can nest to arbitrary levels, finding the smallest def containing
1364point cannot be done via a simple backward search: the def containing
1365point may not be the closest preceding def, or even the closest
1366preceding def that's indented less. The fancy algorithm required is
1367appropriate for the usual uses of this `mark' command, but not for the
1368`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001370So the def marked by this command may not be the one either of the
1371`goto' commands find: If point is on a blank or non-indenting comment
1372line, moves back to start of the closest preceding code statement or
1373indenting comment line. If this is a `def' statement, that's the def
1374we use. Else searches for the smallest enclosing `def' block and uses
1375that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001377When an enclosing def is found: The mark is left immediately beyond
1378the last line of the def block. Point is left at the start of the
1379def, except that: if the def is preceded by a number of comment lines
1380followed by (at most) one optional blank line, point is left at the
1381start of the comments; else if the def is preceded by a blank line,
1382point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001383
1384The intent is to mark the containing def/class and its associated
1385documentation, to make moving and duplicating functions and classes
1386pleasant."
1387 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001388 (let ((start (point))
1389 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001390 (push-mark start)
1391 (if (not (py-go-up-tree-to-keyword which))
1392 (progn (goto-char start)
1393 (error "Enclosing %s not found" which))
1394 ;; else enclosing def/class found
1395 (setq start (point))
1396 (py-goto-beyond-block)
1397 (push-mark (point))
1398 (goto-char start)
1399 (if (zerop (forward-line -1)) ; if there is a preceding line
1400 (progn
1401 (if (looking-at "[ \t]*$") ; it's blank
1402 (setq start (point)) ; so reset start point
1403 (goto-char start)) ; else try again
1404 (if (zerop (forward-line -1))
1405 (if (looking-at "[ \t]*#") ; a comment
1406 ;; look back for non-comment line
1407 ;; tricky: note that the regexp matches a blank
1408 ;; line, cuz \n is in the 2nd character class
1409 (and
1410 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1411 (forward-line 1))
1412 ;; no comment, so go back
1413 (goto-char start))))))))
1414
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001415
1416;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001417
1418;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001419;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1420;; out of the right places, along with the keys they're on & current
1421;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422(defun py-dump-help-string (str)
1423 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001424 (let ((locals (buffer-local-variables))
1425 funckind funcname func funcdoc
1426 (start 0) mstart end
1427 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001428 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1429 (setq mstart (match-beginning 0) end (match-end 0)
1430 funckind (substring str (match-beginning 1) (match-end 1))
1431 funcname (substring str (match-beginning 2) (match-end 2))
1432 func (intern funcname))
1433 (princ (substitute-command-keys (substring str start mstart)))
1434 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001435 ((equal funckind "c") ; command
1436 (setq funcdoc (documentation func)
1437 keys (concat
1438 "Key(s): "
1439 (mapconcat 'key-description
1440 (where-is-internal func py-mode-map)
1441 ", "))))
1442 ((equal funckind "v") ; variable
1443 (setq funcdoc (substitute-command-keys
1444 (get func 'variable-documentation))
1445 keys (if (assq func locals)
1446 (concat
1447 "Local/Global values: "
1448 (prin1-to-string (symbol-value func))
1449 " / "
1450 (prin1-to-string (default-value func)))
1451 (concat
1452 "Value: "
1453 (prin1-to-string (symbol-value func))))))
1454 (t ; unexpected
1455 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001456 (princ (format "\n-> %s:\t%s\t%s\n\n"
1457 (if (equal funckind "c") "Command" "Variable")
1458 funcname keys))
1459 (princ funcdoc)
1460 (terpri)
1461 (setq start end))
1462 (princ (substitute-command-keys (substring str start))))
1463 (print-help-return-message)))
1464
1465(defun py-describe-mode ()
1466 "Dump long form of Python-mode docs."
1467 (interactive)
1468 (py-dump-help-string "Major mode for editing Python files.
1469Knows about Python indentation, tokens, comments and continuation lines.
1470Paragraphs are separated by blank lines only.
1471
1472Major sections below begin with the string `@'; specific function and
1473variable docs begin with `->'.
1474
1475@EXECUTING PYTHON CODE
1476
1477\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1478\\[py-execute-region]\tsends the current region
1479\\[py-shell]\tstarts a Python interpreter window; this will be used by
1480\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1481%c:py-execute-buffer
1482%c:py-execute-region
1483%c:py-shell
1484
1485@VARIABLES
1486
1487py-indent-offset\tindentation increment
1488py-block-comment-prefix\tcomment string used by py-comment-region
1489
1490py-python-command\tshell command to invoke Python interpreter
1491py-scroll-process-buffer\talways scroll Python process buffer
1492py-temp-directory\tdirectory used for temp files (if needed)
1493
1494py-beep-if-tab-change\tring the bell if tab-width is changed
1495%v:py-indent-offset
1496%v:py-block-comment-prefix
1497%v:py-python-command
1498%v:py-scroll-process-buffer
1499%v:py-temp-directory
1500%v:py-beep-if-tab-change
1501
1502@KINDS OF LINES
1503
1504Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001505preceding line ends with a backslash that's not part of a comment, or
1506the paren/bracket/brace nesting level at the start of the line is
1507non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001508
1509An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001510possibly blanks or tabs), a `comment line' (leftmost non-blank
1511character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001512
1513Comment Lines
1514
1515Although all comment lines are treated alike by Python, Python mode
1516recognizes two kinds that act differently with respect to indentation.
1517
1518An `indenting comment line' is a comment line with a blank, tab or
1519nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001520treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001521indenting comment line will be indented like the comment line. All
1522other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001523following the initial `#') are `non-indenting comment lines', and
1524their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001525
1526Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001527whenever possible. Non-indenting comment lines are useful in cases
1528like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001529
1530\ta = b # a very wordy single-line comment that ends up being
1531\t #... continued onto another line
1532
1533\tif a == b:
1534##\t\tprint 'panic!' # old code we've `commented out'
1535\t\treturn a
1536
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537Since the `#...' and `##' comment lines have a non-whitespace
1538character following the initial `#', Python mode ignores them when
1539computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540
1541Continuation Lines and Statements
1542
1543The Python-mode commands generally work on statements instead of on
1544individual lines, where a `statement' is a comment or blank line, or a
1545code line and all of its following continuation lines (if any)
1546considered as a single logical unit. The commands in this mode
1547generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001548statement containing point, even if point happens to be in the middle
1549of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001550
1551
1552@INDENTATION
1553
1554Primarily for entering new code:
1555\t\\[indent-for-tab-command]\t indent line appropriately
1556\t\\[py-newline-and-indent]\t insert newline, then indent
1557\t\\[py-delete-char]\t reduce indentation, or delete single character
1558
1559Primarily for reindenting existing code:
1560\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1561\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1562
1563\t\\[py-indent-region]\t reindent region to match its context
1564\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1565\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1566
1567Unlike most programming languages, Python uses indentation, and only
1568indentation, to specify block structure. Hence the indentation supplied
1569automatically by Python-mode is just an educated guess: only you know
1570the block structure you intend, so only you can supply correct
1571indentation.
1572
1573The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1574the indentation of preceding statements. E.g., assuming
1575py-indent-offset is 4, after you enter
1576\tif a > 0: \\[py-newline-and-indent]
1577the cursor will be moved to the position of the `_' (_ is not a
1578character in the file, it's just used here to indicate the location of
1579the cursor):
1580\tif a > 0:
1581\t _
1582If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1583to
1584\tif a > 0:
1585\t c = d
1586\t _
1587Python-mode cannot know whether that's what you intended, or whether
1588\tif a > 0:
1589\t c = d
1590\t_
1591was your intent. In general, Python-mode either reproduces the
1592indentation of the (closest code or indenting-comment) preceding
1593statement, or adds an extra py-indent-offset blanks if the preceding
1594statement has `:' as its last significant (non-whitespace and non-
1595comment) character. If the suggested indentation is too much, use
1596\\[py-delete-char] to reduce it.
1597
1598Continuation lines are given extra indentation. If you don't like the
1599suggested indentation, change it to something you do like, and Python-
1600mode will strive to indent later lines of the statement in the same way.
1601
1602If a line is a continuation line by virtue of being in an unclosed
1603paren/bracket/brace structure (`list', for short), the suggested
1604indentation depends on whether the current line contains the first item
1605in the list. If it does, it's indented py-indent-offset columns beyond
1606the indentation of the line containing the open bracket. If you don't
1607like that, change it by hand. The remaining items in the list will mimic
1608whatever indentation you give to the first item.
1609
1610If a line is a continuation line because the line preceding it ends with
1611a backslash, the third and following lines of the statement inherit their
1612indentation from the line preceding them. The indentation of the second
1613line in the statement depends on the form of the first (base) line: if
1614the base line is an assignment statement with anything more interesting
1615than the backslash following the leftmost assigning `=', the second line
1616is indented two columns beyond that `='. Else it's indented to two
1617columns beyond the leftmost solid chunk of non-whitespace characters on
1618the base line.
1619
1620Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1621repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1622structure you intend.
1623%c:indent-for-tab-command
1624%c:py-newline-and-indent
1625%c:py-delete-char
1626
1627
1628The next function may be handy when editing code you didn't write:
1629%c:py-guess-indent-offset
1630
1631
1632The remaining `indent' functions apply to a region of Python code. They
1633assume the block structure (equals indentation, in Python) of the region
1634is correct, and alter the indentation in various ways while preserving
1635the block structure:
1636%c:py-indent-region
1637%c:py-shift-region-left
1638%c:py-shift-region-right
1639
1640@MARKING & MANIPULATING REGIONS OF CODE
1641
1642\\[py-mark-block]\t mark block of lines
1643\\[mark-python-def-or-class]\t mark smallest enclosing def
1644\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1645\\[py-comment-region]\t comment out region of code
1646\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1647%c:py-mark-block
1648%c:mark-python-def-or-class
1649%c:py-comment-region
1650
1651@MOVING POINT
1652
1653\\[py-previous-statement]\t move to statement preceding point
1654\\[py-next-statement]\t move to statement following point
1655\\[py-goto-block-up]\t move up to start of current block
1656\\[beginning-of-python-def-or-class]\t move to start of def
1657\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1658\\[end-of-python-def-or-class]\t move to end of def
1659\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1660
1661The first two move to one statement beyond the statement that contains
1662point. A numeric prefix argument tells them to move that many
1663statements instead. Blank lines, comment lines, and continuation lines
1664do not count as `statements' for these commands. So, e.g., you can go
1665to the first code statement in a file by entering
1666\t\\[beginning-of-buffer]\t to move to the top of the file
1667\t\\[py-next-statement]\t to skip over initial comments and blank lines
1668Or do `\\[py-previous-statement]' with a huge prefix argument.
1669%c:py-previous-statement
1670%c:py-next-statement
1671%c:py-goto-block-up
1672%c:beginning-of-python-def-or-class
1673%c:end-of-python-def-or-class
1674
1675@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1676
1677`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1678
1679`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1680overall class and def structure of a module.
1681
1682`\\[back-to-indentation]' moves point to a line's first non-blank character.
1683
1684`\\[indent-relative]' is handy for creating odd indentation.
1685
1686@OTHER EMACS HINTS
1687
1688If you don't like the default value of a variable, change its value to
1689whatever you do like by putting a `setq' line in your .emacs file.
1690E.g., to set the indentation increment to 4, put this line in your
1691.emacs:
1692\t(setq py-indent-offset 4)
1693To see the value of a variable, do `\\[describe-variable]' and enter the variable
1694name at the prompt.
1695
1696When entering a key sequence like `C-c C-n', it is not necessary to
1697release the CONTROL key after doing the `C-c' part -- it suffices to
1698press the CONTROL key, press and release `c' (while still holding down
1699CONTROL), press and release `n' (while still holding down CONTROL), &
1700then release CONTROL.
1701
1702Entering Python mode calls with no arguments the value of the variable
1703`python-mode-hook', if that value exists and is not nil; for backward
1704compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1705the Elisp manual for details.
1706
1707Obscure: When python-mode is first loaded, it looks for all bindings
1708to newline-and-indent in the global keymap, and shadows them with
1709local bindings to py-newline-and-indent."))
1710
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001711
1712;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713(defvar py-parse-state-re
1714 (concat
1715 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1716 "\\|"
1717 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001718
Barry Warsaw7ae77681994-12-12 20:38:05 +00001719;; returns the parse state at point (see parse-partial-sexp docs)
1720(defun py-parse-state ()
1721 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001722 (let ((here (point))
1723 pps done)
1724 (while (not done)
1725 ;; back up to the first preceding line (if any; else start of
1726 ;; buffer) that begins with a popular Python keyword, or a
1727 ;; non- whitespace and non-comment character. These are good
1728 ;; places to start parsing to see whether where we started is
1729 ;; at a non-zero nesting level. It may be slow for people who
1730 ;; write huge code blocks or huge lists ... tough beans.
1731 (re-search-backward py-parse-state-re nil 'move)
1732 (beginning-of-line)
1733 (save-excursion
1734 (setq pps (parse-partial-sexp (point) here)))
1735 ;; make sure we don't land inside a triple-quoted string
1736 (setq done (or (not (nth 3 pps)) (bobp))))
1737 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738
1739;; if point is at a non-zero nesting level, returns the number of the
1740;; character that opens the smallest enclosing unclosed list; else
1741;; returns nil.
1742(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744 (if (zerop (car status))
1745 nil ; not in a nest
1746 (car (cdr status))))) ; char# of open bracket
1747
1748;; t iff preceding line ends with backslash that's not in a comment
1749(defun py-backslash-continuation-line-p ()
1750 (save-excursion
1751 (beginning-of-line)
1752 (and
1753 ;; use a cheap test first to avoid the regexp if possible
1754 ;; use 'eq' because char-after may return nil
1755 (eq (char-after (- (point) 2)) ?\\ )
1756 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001758 (looking-at py-continued-re))))
1759
1760;; t iff current line is a continuation line
1761(defun py-continuation-line-p ()
1762 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001763 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764 (or (py-backslash-continuation-line-p)
1765 (py-nesting-level))))
1766
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001767;; go to initial line of current statement; usually this is the line
1768;; we're on, but if we're on the 2nd or following lines of a
1769;; continuation block, we need to go up to the first line of the
1770;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001772;; Tricky: We want to avoid quadratic-time behavior for long continued
1773;; blocks, whether of the backslash or open-bracket varieties, or a
1774;; mix of the two. The following manages to do that in the usual
1775;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776(defun py-goto-initial-line ()
1777 (let ( open-bracket-pos )
1778 (while (py-continuation-line-p)
1779 (beginning-of-line)
1780 (if (py-backslash-continuation-line-p)
1781 (while (py-backslash-continuation-line-p)
1782 (forward-line -1))
1783 ;; else zip out of nested brackets/braces/parens
1784 (while (setq open-bracket-pos (py-nesting-level))
1785 (goto-char open-bracket-pos)))))
1786 (beginning-of-line))
1787
1788;; go to point right beyond final line of current statement; usually
1789;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790;; statement we need to skip over the continuation lines. Tricky:
1791;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792(defun py-goto-beyond-final-line ()
1793 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795 (while (and (py-continuation-line-p)
1796 (not (eobp)))
1797 ;; skip over the backslash flavor
1798 (while (and (py-backslash-continuation-line-p)
1799 (not (eobp)))
1800 (forward-line 1))
1801 ;; if in nest, zip to the end of the nest
1802 (setq state (py-parse-state))
1803 (if (and (not (zerop (car state)))
1804 (not (eobp)))
1805 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001806 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001807 ;; the 3rd argument should be plain 0
1808 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1809 nil state)
1810 (forward-line 1))))))
1811
1812;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001813;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001814(defun py-statement-opens-block-p ()
1815 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001816 (let ((start (point))
1817 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1818 (searching t)
1819 (answer nil)
1820 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001821 (goto-char start)
1822 (while searching
1823 ;; look for a colon with nothing after it except whitespace, and
1824 ;; maybe a comment
1825 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1826 finish t)
1827 (if (eq (point) finish) ; note: no `else' clause; just
1828 ; keep searching if we're not at
1829 ; the end yet
1830 ;; sure looks like it opens a block -- but it might
1831 ;; be in a comment
1832 (progn
1833 (setq searching nil) ; search is done either way
1834 (setq state (parse-partial-sexp start
1835 (match-beginning 0)))
1836 (setq answer (not (nth 4 state)))))
1837 ;; search failed: couldn't find another interesting colon
1838 (setq searching nil)))
1839 answer)))
1840
1841;; go to point right beyond final line of block begun by the current
1842;; line. This is the same as where py-goto-beyond-final-line goes
1843;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001844;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001845(defun py-goto-beyond-block ()
1846 (if (py-statement-opens-block-p)
1847 (py-mark-block nil 'just-move)
1848 (py-goto-beyond-final-line)))
1849
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001850;; go to start of first statement (not blank or comment or
1851;; continuation line) at or preceding point. returns t if there is
1852;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853(defun py-goto-statement-at-or-above ()
1854 (py-goto-initial-line)
1855 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001856 ;; skip back over blank & comment lines
1857 ;; note: will skip a blank or comment line that happens to be
1858 ;; a continuation line too
1859 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1860 (progn (py-goto-initial-line) t)
1861 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 t))
1863
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001864;; go to start of first statement (not blank or comment or
1865;; continuation line) following the statement containing point returns
1866;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001867(defun py-goto-statement-below ()
1868 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001870 (py-goto-beyond-final-line)
1871 (while (and
1872 (looking-at py-blank-or-comment-re)
1873 (not (eobp)))
1874 (forward-line 1))
1875 (if (eobp)
1876 (progn (goto-char start) nil)
1877 t)))
1878
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001879;; go to start of statement, at or preceding point, starting with
1880;; keyword KEY. Skips blank lines and non-indenting comments upward
1881;; first. If that statement starts with KEY, done, else go back to
1882;; first enclosing block starting with KEY. If successful, leaves
1883;; point at the start of the KEY line & returns t. Else leaves point
1884;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885(defun py-go-up-tree-to-keyword (key)
1886 ;; skip blanks and non-indenting #
1887 (py-goto-initial-line)
1888 (while (and
1889 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1890 (zerop (forward-line -1))) ; go back
1891 nil)
1892 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001893 (let* ((re (concat "[ \t]*" key "\\b"))
1894 (case-fold-search nil) ; let* so looking-at sees this
1895 (found (looking-at re))
1896 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001897 (while (not (or found dead))
1898 (condition-case nil ; in case no enclosing block
1899 (py-goto-block-up 'no-mark)
1900 (error (setq dead t)))
1901 (or dead (setq found (looking-at re))))
1902 (beginning-of-line)
1903 found))
1904
1905;; return string in buffer from start of indentation to end of line;
1906;; prefix "..." if leading whitespace was skipped
1907(defun py-suck-up-leading-text ()
1908 (save-excursion
1909 (back-to-indentation)
1910 (concat
1911 (if (bolp) "" "...")
1912 (buffer-substring (point) (progn (end-of-line) (point))))))
1913
1914;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1915;; as a Lisp symbol; return nil if none
1916(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001917 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1919 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1920 nil)))
1921
1922(defun py-make-temp-name ()
1923 (make-temp-name
1924 (concat (file-name-as-directory py-temp-directory) "python")))
1925
1926(defun py-delete-file-silently (fname)
1927 (condition-case nil
1928 (delete-file fname)
1929 (error nil)))
1930
1931(defun py-kill-emacs-hook ()
1932 ;; delete our temp files
1933 (while py-file-queue
1934 (py-delete-file-silently (car py-file-queue))
1935 (setq py-file-queue (cdr py-file-queue)))
1936 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1937 ;; run the hook we inherited, if any
1938 (and py-inherited-kill-emacs-hook
1939 (funcall py-inherited-kill-emacs-hook))))
1940
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001941;; make PROCESS's buffer visible, append STRING to it, and force
1942;; display; also make shell-mode believe the user typed this string,
1943;; so that kill-output-from-shell and show-output-from-shell work
1944;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001946 (let ((cbuf (current-buffer))
1947 (pbuf (process-buffer process))
1948 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949 (set-buffer pbuf)
1950 (goto-char (point-max))
1951 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001952 (if (not (or py-this-is-emacs-19-p
1953 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001954 (move-marker last-input-start (point))) ; muck w/ shell-mode
1955 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001956 (if (not (or py-this-is-emacs-19-p
1957 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958 (move-marker last-input-end (point))) ; muck w/ shell-mode
1959 (set-buffer cbuf))
1960 (sit-for 0))
1961
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001962(defun py-keep-region-active ()
1963 ;; do whatever is necessary to keep the region active in XEmacs.
1964 ;; Ignore byte-compiler warnings you might see. Also note that
1965 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1966 ;; require us to take explicit action.
1967 (and (boundp 'zmacs-region-stays)
1968 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001969
1970
Barry Warsaw850437a1995-03-08 21:50:28 +00001971(defconst py-version "$Revision$"
1972 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001973(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001974 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975
Barry Warsaw850437a1995-03-08 21:50:28 +00001976(defun py-version ()
1977 "Echo the current version of `python-mode' in the minibuffer."
1978 (interactive)
1979 (message "Using `python-mode' version %s" py-version)
1980 (py-keep-region-active))
1981
1982;; only works under Emacs 19
1983;(eval-when-compile
1984; (require 'reporter))
1985
1986(defun py-submit-bug-report (enhancement-p)
1987 "Submit via mail a bug report on `python-mode'.
1988With \\[universal-argument] just submit an enhancement request."
1989 (interactive
1990 (list (not (y-or-n-p
1991 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001992 (let ((reporter-prompt-for-summary-p (if enhancement-p
1993 "(Very) brief summary: "
1994 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001995 (require 'reporter)
1996 (reporter-submit-bug-report
1997 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001998 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001999 ;; varlist
2000 (if enhancement-p nil
2001 '(py-python-command
2002 py-indent-offset
2003 py-block-comment-prefix
2004 py-scroll-process-buffer
2005 py-temp-directory
2006 py-beep-if-tab-change))
2007 nil ;pre-hooks
2008 nil ;post-hooks
2009 "Dear Barry,") ;salutation
2010 (if enhancement-p nil
2011 (set-mark (point))
2012 (insert
2013"Please replace this text with a sufficiently large code sample\n\
2014and an exact recipe so that I can reproduce your problem. Failure\n\
2015to do so may mean a greater delay in fixing your bug.\n\n")
2016 (exchange-point-and-mark)
2017 (py-keep-region-active))))
2018
2019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020;; arrange to kill temp files when Emacs exists
2021(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2022 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2023 ;; have to trust that other people are as respectful of our hook
2024 ;; fiddling as we are of theirs
2025 (if (boundp 'py-inherited-kill-emacs-hook)
2026 ;; we were loaded before -- trust others not to have screwed us
2027 ;; in the meantime (no choice, really)
2028 nil
2029 ;; else arrange for our hook to run theirs
2030 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2031 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2032
2033
2034
2035(provide 'python-mode)
2036;;; python-mode.el ends here