blob: 80cc0f5723fdbda26a6b322644902d85cfc7d3df [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)
Barry Warsaw71e315b1996-07-23 15:03:16 +0000966 (if (and (zerop (current-column))
967 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +0000968 (error "Region is at left edge."))
969 (forward-line 1)))
970 (py-shift-region start end (- (prefix-numeric-value
971 (or count py-indent-offset))))
972 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000973
974(defun py-shift-region-right (start end &optional count)
975 "Shift region of Python code to the right.
976The lines from the line containing the start of the current region up
977to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000978shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000979
980If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000981many columns. With no active region, indent only the current line."
982 (interactive
983 (let ((p (point))
984 (m (mark))
985 (arg current-prefix-arg))
986 (if m
987 (list (min p m) (max p m) arg)
988 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000989 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000990 (or count py-indent-offset)))
991 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992
993(defun py-indent-region (start end &optional indent-offset)
994 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000995
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996The lines from the line containing the start of the current region up
997to (but not including) the line containing the end of the region are
998reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000999character in the first column, the first line is left alone and the
1000rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001001region is reindented with respect to the (closest code or indenting
1002comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001003
1004This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001005control structures are introduced or removed, or to reformat code
1006using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001007
1008If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001009the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001010used.
1011
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013is called! This function does not compute proper indentation from
1014scratch (that's impossible in Python), it merely adjusts the existing
1015indentation to be correct in context.
1016
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017Warning: This function really has no idea what to do with
1018non-indenting comment lines, and shifts them as if they were indenting
1019comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001020
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001021Special cases: whitespace is deleted from blank lines; continuation
1022lines are shifted by the same amount their initial line was shifted,
1023in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001024initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001025 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001026 (save-excursion
1027 (goto-char end) (beginning-of-line) (setq end (point-marker))
1028 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001029 (let ((py-indent-offset (prefix-numeric-value
1030 (or indent-offset py-indent-offset)))
1031 (indents '(-1)) ; stack of active indent levels
1032 (target-column 0) ; column to which to indent
1033 (base-shifted-by 0) ; amount last base line was shifted
1034 (indent-base (if (looking-at "[ \t\n]")
1035 (py-compute-indentation)
1036 0))
1037 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001038 (while (< (point) end)
1039 (setq ci (current-indentation))
1040 ;; figure out appropriate target column
1041 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001042 ((or (eq (following-char) ?#) ; comment in column 1
1043 (looking-at "[ \t]*$")) ; entirely blank
1044 (setq target-column 0))
1045 ((py-continuation-line-p) ; shift relative to base line
1046 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001047 (t ; new base line
1048 (if (> ci (car indents)) ; going deeper; push it
1049 (setq indents (cons ci indents))
1050 ;; else we should have seen this indent before
1051 (setq indents (memq ci indents)) ; pop deeper indents
1052 (if (null indents)
1053 (error "Bad indentation in region, at line %d"
1054 (save-restriction
1055 (widen)
1056 (1+ (count-lines 1 (point)))))))
1057 (setq target-column (+ indent-base
1058 (* py-indent-offset
1059 (- (length indents) 2))))
1060 (setq base-shifted-by (- target-column ci))))
1061 ;; shift as needed
1062 (if (/= ci target-column)
1063 (progn
1064 (delete-horizontal-space)
1065 (indent-to target-column)))
1066 (forward-line 1))))
1067 (set-marker end nil))
1068
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069
1070;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001071(defun py-previous-statement (count)
1072 "Go to the start of previous Python statement.
1073If the statement at point is the i'th Python statement, goes to the
1074start of statement i-COUNT. If there is no such statement, goes to the
1075first statement. Returns count of statements left to move.
1076`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001077 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001078 (if (< count 0) (py-next-statement (- count))
1079 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001081 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001082 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001083 (> count 0)
1084 (zerop (forward-line -1))
1085 (py-goto-statement-at-or-above))
1086 (setq count (1- count)))
1087 (if (> count 0) (goto-char start)))
1088 count))
1089
1090(defun py-next-statement (count)
1091 "Go to the start of next Python statement.
1092If the statement at point is the i'th Python statement, goes to the
1093start of statement i+COUNT. If there is no such statement, goes to the
1094last statement. Returns count of statements left to move. `Statements'
1095do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001096 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097 (if (< count 0) (py-previous-statement (- count))
1098 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001099 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001101 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001102 (> count 0)
1103 (py-goto-statement-below))
1104 (setq count (1- count)))
1105 (if (> count 0) (goto-char start)))
1106 count))
1107
1108(defun py-goto-block-up (&optional nomark)
1109 "Move up to start of current block.
1110Go to the statement that starts the smallest enclosing block; roughly
1111speaking, this will be the closest preceding statement that ends with a
1112colon and is indented less than the statement you started on. If
1113successful, also sets the mark to the starting point.
1114
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001115`\\[py-mark-block]' can be used afterward to mark the whole code
1116block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001117
1118If called from a program, the mark will not be set if optional argument
1119NOMARK is not nil."
1120 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001121 (let ((start (point))
1122 (found nil)
1123 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001124 (py-goto-initial-line)
1125 ;; if on blank or non-indenting comment line, use the preceding stmt
1126 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1127 (progn
1128 (py-goto-statement-at-or-above)
1129 (setq found (py-statement-opens-block-p))))
1130 ;; search back for colon line indented less
1131 (setq initial-indent (current-indentation))
1132 (if (zerop initial-indent)
1133 ;; force fast exit
1134 (goto-char (point-min)))
1135 (while (not (or found (bobp)))
1136 (setq found
1137 (and
1138 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1139 (or (py-goto-initial-line) t) ; always true -- side effect
1140 (< (current-indentation) initial-indent)
1141 (py-statement-opens-block-p))))
1142 (if found
1143 (progn
1144 (or nomark (push-mark start))
1145 (back-to-indentation))
1146 (goto-char start)
1147 (error "Enclosing block not found"))))
1148
1149(defun beginning-of-python-def-or-class (&optional class)
1150 "Move point to start of def (or class, with prefix arg).
1151
1152Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001153arg, looks for a `class' instead. The docs assume the `def' case;
1154just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001155
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001156If point is in a def statement already, and after the `d', simply
1157moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001158
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001159Else (point is not in a def statement, or at or before the `d' of a
1160def statement), searches for the closest preceding def statement, and
1161leaves point at its start. If no such statement can be found, leaves
1162point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001163
1164Returns t iff a def statement is found by these rules.
1165
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001166Note that doing this command repeatedly will take you closer to the
1167start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001168
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001169If you want to mark the current def/class, see
1170`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001171 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001172 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1173 (start-of-line (progn (beginning-of-line) (point)))
1174 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001175 (if (or (/= start-of-stmt start-of-line)
1176 (not at-or-before-p))
1177 (end-of-line)) ; OK to match on this line
1178 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001179 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001180
1181(defun end-of-python-def-or-class (&optional class)
1182 "Move point beyond end of def (or class, with prefix arg) body.
1183
1184By default, looks for an appropriate `def'. If you supply a prefix arg,
1185looks for a `class' instead. The docs assume the `def' case; just
1186substitute `class' for `def' for the other case.
1187
1188If point is in a def statement already, this is the def we use.
1189
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001190Else if the def found by `\\[beginning-of-python-def-or-class]'
1191contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001192
1193Else we search forward for the closest following def, and use that.
1194
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001195If a def can be found by these rules, point is moved to the start of
1196the line immediately following the def block, and the position of the
1197start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001198
1199Else point is moved to the end of the buffer, and nil is returned.
1200
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001201Note that doing this command repeatedly will take you closer to the
1202end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001204If you want to mark the current def/class, see
1205`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001206 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207 (let ((start (progn (py-goto-initial-line) (point)))
1208 (which (if class "class" "def"))
1209 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001210 ;; move point to start of appropriate def/class
1211 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1212 (setq state 'at-beginning)
1213 ;; else see if beginning-of-python-def-or-class hits container
1214 (if (and (beginning-of-python-def-or-class class)
1215 (progn (py-goto-beyond-block)
1216 (> (point) start)))
1217 (setq state 'at-end)
1218 ;; else search forward
1219 (goto-char start)
1220 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1221 (progn (setq state 'at-beginning)
1222 (beginning-of-line)))))
1223 (cond
1224 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1225 ((eq state 'at-end) t)
1226 ((eq state 'not-found) nil)
1227 (t (error "internal error in end-of-python-def-or-class")))))
1228
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001229
1230;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001231(defun py-mark-block (&optional extend just-move)
1232 "Mark following block of lines. With prefix arg, mark structure.
1233Easier to use than explain. It sets the region to an `interesting'
1234block of succeeding lines. If point is on a blank line, it goes down to
1235the next non-blank line. That will be the start of the region. The end
1236of the region depends on the kind of line at the start:
1237
1238 - If a comment, the region will include all succeeding comment lines up
1239 to (but not including) the next non-comment line (if any).
1240
1241 - Else if a prefix arg is given, and the line begins one of these
1242 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001243
1244 if elif else try except finally for while def class
1245
Barry Warsaw7ae77681994-12-12 20:38:05 +00001246 the region will be set to the body of the structure, including
1247 following blocks that `belong' to it, but excluding trailing blank
1248 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001249 and all (if any) of the following `except' and `finally' blocks
1250 that belong to the `try' structure will be in the region. Ditto
1251 for if/elif/else, for/else and while/else structures, and (a bit
1252 degenerate, since they're always one-block structures) def and
1253 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001254
1255 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001256 block (see list above), and the block is not a `one-liner' (i.e.,
1257 the statement ends with a colon, not with code), the region will
1258 include all succeeding lines up to (but not including) the next
1259 code statement (if any) that's indented no more than the starting
1260 line, except that trailing blank and comment lines are excluded.
1261 E.g., if the starting line begins a multi-statement `def'
1262 structure, the region will be set to the full function definition,
1263 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001264
1265 - Else the region will include all succeeding lines up to (but not
1266 including) the next blank line, or code or indenting-comment line
1267 indented strictly less than the starting line. Trailing indenting
1268 comment lines are included in this case, but not trailing blank
1269 lines.
1270
1271A msg identifying the location of the mark is displayed in the echo
1272area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1273
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001274If called from a program, optional argument EXTEND plays the role of
1275the prefix arg, and if optional argument JUST-MOVE is not nil, just
1276moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277 (interactive "P") ; raw prefix arg
1278 (py-goto-initial-line)
1279 ;; skip over blank lines
1280 (while (and
1281 (looking-at "[ \t]*$") ; while blank line
1282 (not (eobp))) ; & somewhere to go
1283 (forward-line 1))
1284 (if (eobp)
1285 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001286 (let ((initial-pos (point))
1287 (initial-indent (current-indentation))
1288 last-pos ; position of last stmt in region
1289 (followers
1290 '((if elif else) (elif elif else) (else)
1291 (try except finally) (except except) (finally)
1292 (for else) (while else)
1293 (def) (class) ) )
1294 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001295
1296 (cond
1297 ;; if comment line, suck up the following comment lines
1298 ((looking-at "[ \t]*#")
1299 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1300 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1301 (setq last-pos (point)))
1302
1303 ;; else if line is a block line and EXTEND given, suck up
1304 ;; the whole structure
1305 ((and extend
1306 (setq first-symbol (py-suck-up-first-keyword) )
1307 (assq first-symbol followers))
1308 (while (and
1309 (or (py-goto-beyond-block) t) ; side effect
1310 (forward-line -1) ; side effect
1311 (setq last-pos (point)) ; side effect
1312 (py-goto-statement-below)
1313 (= (current-indentation) initial-indent)
1314 (setq next-symbol (py-suck-up-first-keyword))
1315 (memq next-symbol (cdr (assq first-symbol followers))))
1316 (setq first-symbol next-symbol)))
1317
1318 ;; else if line *opens* a block, search for next stmt indented <=
1319 ((py-statement-opens-block-p)
1320 (while (and
1321 (setq last-pos (point)) ; always true -- side effect
1322 (py-goto-statement-below)
1323 (> (current-indentation) initial-indent))
1324 nil))
1325
1326 ;; else plain code line; stop at next blank line, or stmt or
1327 ;; indenting comment line indented <
1328 (t
1329 (while (and
1330 (setq last-pos (point)) ; always true -- side effect
1331 (or (py-goto-beyond-final-line) t)
1332 (not (looking-at "[ \t]*$")) ; stop at blank line
1333 (or
1334 (>= (current-indentation) initial-indent)
1335 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1336 nil)))
1337
1338 ;; skip to end of last stmt
1339 (goto-char last-pos)
1340 (py-goto-beyond-final-line)
1341
1342 ;; set mark & display
1343 (if just-move
1344 () ; just return
1345 (push-mark (point) 'no-msg)
1346 (forward-line -1)
1347 (message "Mark set after: %s" (py-suck-up-leading-text))
1348 (goto-char initial-pos))))
1349
1350(defun mark-python-def-or-class (&optional class)
1351 "Set region to body of def (or class, with prefix arg) enclosing point.
1352Pushes the current mark, then point, on the mark ring (all language
1353modes do this, but although it's handy it's never documented ...).
1354
1355In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001356hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1357`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001358
1359And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360Turned out that was more confusing than useful: the `goto start' and
1361`goto end' commands are usually used to search through a file, and
1362people expect them to act a lot like `search backward' and `search
1363forward' string-search commands. But because Python `def' and `class'
1364can nest to arbitrary levels, finding the smallest def containing
1365point cannot be done via a simple backward search: the def containing
1366point may not be the closest preceding def, or even the closest
1367preceding def that's indented less. The fancy algorithm required is
1368appropriate for the usual uses of this `mark' command, but not for the
1369`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001370
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371So the def marked by this command may not be the one either of the
1372`goto' commands find: If point is on a blank or non-indenting comment
1373line, moves back to start of the closest preceding code statement or
1374indenting comment line. If this is a `def' statement, that's the def
1375we use. Else searches for the smallest enclosing `def' block and uses
1376that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001377
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001378When an enclosing def is found: The mark is left immediately beyond
1379the last line of the def block. Point is left at the start of the
1380def, except that: if the def is preceded by a number of comment lines
1381followed by (at most) one optional blank line, point is left at the
1382start of the comments; else if the def is preceded by a blank line,
1383point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384
1385The intent is to mark the containing def/class and its associated
1386documentation, to make moving and duplicating functions and classes
1387pleasant."
1388 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001389 (let ((start (point))
1390 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001391 (push-mark start)
1392 (if (not (py-go-up-tree-to-keyword which))
1393 (progn (goto-char start)
1394 (error "Enclosing %s not found" which))
1395 ;; else enclosing def/class found
1396 (setq start (point))
1397 (py-goto-beyond-block)
1398 (push-mark (point))
1399 (goto-char start)
1400 (if (zerop (forward-line -1)) ; if there is a preceding line
1401 (progn
1402 (if (looking-at "[ \t]*$") ; it's blank
1403 (setq start (point)) ; so reset start point
1404 (goto-char start)) ; else try again
1405 (if (zerop (forward-line -1))
1406 (if (looking-at "[ \t]*#") ; a comment
1407 ;; look back for non-comment line
1408 ;; tricky: note that the regexp matches a blank
1409 ;; line, cuz \n is in the 2nd character class
1410 (and
1411 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1412 (forward-line 1))
1413 ;; no comment, so go back
1414 (goto-char start))))))))
1415
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001416
1417;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418
1419;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001420;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1421;; out of the right places, along with the keys they're on & current
1422;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001423(defun py-dump-help-string (str)
1424 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001425 (let ((locals (buffer-local-variables))
1426 funckind funcname func funcdoc
1427 (start 0) mstart end
1428 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001429 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1430 (setq mstart (match-beginning 0) end (match-end 0)
1431 funckind (substring str (match-beginning 1) (match-end 1))
1432 funcname (substring str (match-beginning 2) (match-end 2))
1433 func (intern funcname))
1434 (princ (substitute-command-keys (substring str start mstart)))
1435 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001436 ((equal funckind "c") ; command
1437 (setq funcdoc (documentation func)
1438 keys (concat
1439 "Key(s): "
1440 (mapconcat 'key-description
1441 (where-is-internal func py-mode-map)
1442 ", "))))
1443 ((equal funckind "v") ; variable
1444 (setq funcdoc (substitute-command-keys
1445 (get func 'variable-documentation))
1446 keys (if (assq func locals)
1447 (concat
1448 "Local/Global values: "
1449 (prin1-to-string (symbol-value func))
1450 " / "
1451 (prin1-to-string (default-value func)))
1452 (concat
1453 "Value: "
1454 (prin1-to-string (symbol-value func))))))
1455 (t ; unexpected
1456 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001457 (princ (format "\n-> %s:\t%s\t%s\n\n"
1458 (if (equal funckind "c") "Command" "Variable")
1459 funcname keys))
1460 (princ funcdoc)
1461 (terpri)
1462 (setq start end))
1463 (princ (substitute-command-keys (substring str start))))
1464 (print-help-return-message)))
1465
1466(defun py-describe-mode ()
1467 "Dump long form of Python-mode docs."
1468 (interactive)
1469 (py-dump-help-string "Major mode for editing Python files.
1470Knows about Python indentation, tokens, comments and continuation lines.
1471Paragraphs are separated by blank lines only.
1472
1473Major sections below begin with the string `@'; specific function and
1474variable docs begin with `->'.
1475
1476@EXECUTING PYTHON CODE
1477
1478\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1479\\[py-execute-region]\tsends the current region
1480\\[py-shell]\tstarts a Python interpreter window; this will be used by
1481\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1482%c:py-execute-buffer
1483%c:py-execute-region
1484%c:py-shell
1485
1486@VARIABLES
1487
1488py-indent-offset\tindentation increment
1489py-block-comment-prefix\tcomment string used by py-comment-region
1490
1491py-python-command\tshell command to invoke Python interpreter
1492py-scroll-process-buffer\talways scroll Python process buffer
1493py-temp-directory\tdirectory used for temp files (if needed)
1494
1495py-beep-if-tab-change\tring the bell if tab-width is changed
1496%v:py-indent-offset
1497%v:py-block-comment-prefix
1498%v:py-python-command
1499%v:py-scroll-process-buffer
1500%v:py-temp-directory
1501%v:py-beep-if-tab-change
1502
1503@KINDS OF LINES
1504
1505Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001506preceding line ends with a backslash that's not part of a comment, or
1507the paren/bracket/brace nesting level at the start of the line is
1508non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001509
1510An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001511possibly blanks or tabs), a `comment line' (leftmost non-blank
1512character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001513
1514Comment Lines
1515
1516Although all comment lines are treated alike by Python, Python mode
1517recognizes two kinds that act differently with respect to indentation.
1518
1519An `indenting comment line' is a comment line with a blank, tab or
1520nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001522indenting comment line will be indented like the comment line. All
1523other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001524following the initial `#') are `non-indenting comment lines', and
1525their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001526
1527Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001528whenever possible. Non-indenting comment lines are useful in cases
1529like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001530
1531\ta = b # a very wordy single-line comment that ends up being
1532\t #... continued onto another line
1533
1534\tif a == b:
1535##\t\tprint 'panic!' # old code we've `commented out'
1536\t\treturn a
1537
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001538Since the `#...' and `##' comment lines have a non-whitespace
1539character following the initial `#', Python mode ignores them when
1540computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542Continuation Lines and Statements
1543
1544The Python-mode commands generally work on statements instead of on
1545individual lines, where a `statement' is a comment or blank line, or a
1546code line and all of its following continuation lines (if any)
1547considered as a single logical unit. The commands in this mode
1548generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001549statement containing point, even if point happens to be in the middle
1550of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001551
1552
1553@INDENTATION
1554
1555Primarily for entering new code:
1556\t\\[indent-for-tab-command]\t indent line appropriately
1557\t\\[py-newline-and-indent]\t insert newline, then indent
1558\t\\[py-delete-char]\t reduce indentation, or delete single character
1559
1560Primarily for reindenting existing code:
1561\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1562\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1563
1564\t\\[py-indent-region]\t reindent region to match its context
1565\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1566\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1567
1568Unlike most programming languages, Python uses indentation, and only
1569indentation, to specify block structure. Hence the indentation supplied
1570automatically by Python-mode is just an educated guess: only you know
1571the block structure you intend, so only you can supply correct
1572indentation.
1573
1574The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1575the indentation of preceding statements. E.g., assuming
1576py-indent-offset is 4, after you enter
1577\tif a > 0: \\[py-newline-and-indent]
1578the cursor will be moved to the position of the `_' (_ is not a
1579character in the file, it's just used here to indicate the location of
1580the cursor):
1581\tif a > 0:
1582\t _
1583If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1584to
1585\tif a > 0:
1586\t c = d
1587\t _
1588Python-mode cannot know whether that's what you intended, or whether
1589\tif a > 0:
1590\t c = d
1591\t_
1592was your intent. In general, Python-mode either reproduces the
1593indentation of the (closest code or indenting-comment) preceding
1594statement, or adds an extra py-indent-offset blanks if the preceding
1595statement has `:' as its last significant (non-whitespace and non-
1596comment) character. If the suggested indentation is too much, use
1597\\[py-delete-char] to reduce it.
1598
1599Continuation lines are given extra indentation. If you don't like the
1600suggested indentation, change it to something you do like, and Python-
1601mode will strive to indent later lines of the statement in the same way.
1602
1603If a line is a continuation line by virtue of being in an unclosed
1604paren/bracket/brace structure (`list', for short), the suggested
1605indentation depends on whether the current line contains the first item
1606in the list. If it does, it's indented py-indent-offset columns beyond
1607the indentation of the line containing the open bracket. If you don't
1608like that, change it by hand. The remaining items in the list will mimic
1609whatever indentation you give to the first item.
1610
1611If a line is a continuation line because the line preceding it ends with
1612a backslash, the third and following lines of the statement inherit their
1613indentation from the line preceding them. The indentation of the second
1614line in the statement depends on the form of the first (base) line: if
1615the base line is an assignment statement with anything more interesting
1616than the backslash following the leftmost assigning `=', the second line
1617is indented two columns beyond that `='. Else it's indented to two
1618columns beyond the leftmost solid chunk of non-whitespace characters on
1619the base line.
1620
1621Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1622repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1623structure you intend.
1624%c:indent-for-tab-command
1625%c:py-newline-and-indent
1626%c:py-delete-char
1627
1628
1629The next function may be handy when editing code you didn't write:
1630%c:py-guess-indent-offset
1631
1632
1633The remaining `indent' functions apply to a region of Python code. They
1634assume the block structure (equals indentation, in Python) of the region
1635is correct, and alter the indentation in various ways while preserving
1636the block structure:
1637%c:py-indent-region
1638%c:py-shift-region-left
1639%c:py-shift-region-right
1640
1641@MARKING & MANIPULATING REGIONS OF CODE
1642
1643\\[py-mark-block]\t mark block of lines
1644\\[mark-python-def-or-class]\t mark smallest enclosing def
1645\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1646\\[py-comment-region]\t comment out region of code
1647\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1648%c:py-mark-block
1649%c:mark-python-def-or-class
1650%c:py-comment-region
1651
1652@MOVING POINT
1653
1654\\[py-previous-statement]\t move to statement preceding point
1655\\[py-next-statement]\t move to statement following point
1656\\[py-goto-block-up]\t move up to start of current block
1657\\[beginning-of-python-def-or-class]\t move to start of def
1658\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1659\\[end-of-python-def-or-class]\t move to end of def
1660\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1661
1662The first two move to one statement beyond the statement that contains
1663point. A numeric prefix argument tells them to move that many
1664statements instead. Blank lines, comment lines, and continuation lines
1665do not count as `statements' for these commands. So, e.g., you can go
1666to the first code statement in a file by entering
1667\t\\[beginning-of-buffer]\t to move to the top of the file
1668\t\\[py-next-statement]\t to skip over initial comments and blank lines
1669Or do `\\[py-previous-statement]' with a huge prefix argument.
1670%c:py-previous-statement
1671%c:py-next-statement
1672%c:py-goto-block-up
1673%c:beginning-of-python-def-or-class
1674%c:end-of-python-def-or-class
1675
1676@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1677
1678`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1679
1680`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1681overall class and def structure of a module.
1682
1683`\\[back-to-indentation]' moves point to a line's first non-blank character.
1684
1685`\\[indent-relative]' is handy for creating odd indentation.
1686
1687@OTHER EMACS HINTS
1688
1689If you don't like the default value of a variable, change its value to
1690whatever you do like by putting a `setq' line in your .emacs file.
1691E.g., to set the indentation increment to 4, put this line in your
1692.emacs:
1693\t(setq py-indent-offset 4)
1694To see the value of a variable, do `\\[describe-variable]' and enter the variable
1695name at the prompt.
1696
1697When entering a key sequence like `C-c C-n', it is not necessary to
1698release the CONTROL key after doing the `C-c' part -- it suffices to
1699press the CONTROL key, press and release `c' (while still holding down
1700CONTROL), press and release `n' (while still holding down CONTROL), &
1701then release CONTROL.
1702
1703Entering Python mode calls with no arguments the value of the variable
1704`python-mode-hook', if that value exists and is not nil; for backward
1705compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1706the Elisp manual for details.
1707
1708Obscure: When python-mode is first loaded, it looks for all bindings
1709to newline-and-indent in the global keymap, and shadows them with
1710local bindings to py-newline-and-indent."))
1711
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712
1713;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001714(defvar py-parse-state-re
1715 (concat
1716 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1717 "\\|"
1718 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001719
Barry Warsaw7ae77681994-12-12 20:38:05 +00001720;; returns the parse state at point (see parse-partial-sexp docs)
1721(defun py-parse-state ()
1722 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001723 (let ((here (point))
1724 pps done)
1725 (while (not done)
1726 ;; back up to the first preceding line (if any; else start of
1727 ;; buffer) that begins with a popular Python keyword, or a
1728 ;; non- whitespace and non-comment character. These are good
1729 ;; places to start parsing to see whether where we started is
1730 ;; at a non-zero nesting level. It may be slow for people who
1731 ;; write huge code blocks or huge lists ... tough beans.
1732 (re-search-backward py-parse-state-re nil 'move)
1733 (beginning-of-line)
1734 (save-excursion
1735 (setq pps (parse-partial-sexp (point) here)))
1736 ;; make sure we don't land inside a triple-quoted string
1737 (setq done (or (not (nth 3 pps)) (bobp))))
1738 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739
1740;; if point is at a non-zero nesting level, returns the number of the
1741;; character that opens the smallest enclosing unclosed list; else
1742;; returns nil.
1743(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001744 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001745 (if (zerop (car status))
1746 nil ; not in a nest
1747 (car (cdr status))))) ; char# of open bracket
1748
1749;; t iff preceding line ends with backslash that's not in a comment
1750(defun py-backslash-continuation-line-p ()
1751 (save-excursion
1752 (beginning-of-line)
1753 (and
1754 ;; use a cheap test first to avoid the regexp if possible
1755 ;; use 'eq' because char-after may return nil
1756 (eq (char-after (- (point) 2)) ?\\ )
1757 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001758 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001759 (looking-at py-continued-re))))
1760
1761;; t iff current line is a continuation line
1762(defun py-continuation-line-p ()
1763 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001765 (or (py-backslash-continuation-line-p)
1766 (py-nesting-level))))
1767
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001768;; go to initial line of current statement; usually this is the line
1769;; we're on, but if we're on the 2nd or following lines of a
1770;; continuation block, we need to go up to the first line of the
1771;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001772;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773;; Tricky: We want to avoid quadratic-time behavior for long continued
1774;; blocks, whether of the backslash or open-bracket varieties, or a
1775;; mix of the two. The following manages to do that in the usual
1776;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001777(defun py-goto-initial-line ()
1778 (let ( open-bracket-pos )
1779 (while (py-continuation-line-p)
1780 (beginning-of-line)
1781 (if (py-backslash-continuation-line-p)
1782 (while (py-backslash-continuation-line-p)
1783 (forward-line -1))
1784 ;; else zip out of nested brackets/braces/parens
1785 (while (setq open-bracket-pos (py-nesting-level))
1786 (goto-char open-bracket-pos)))))
1787 (beginning-of-line))
1788
1789;; go to point right beyond final line of current statement; usually
1790;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001791;; statement we need to skip over the continuation lines. Tricky:
1792;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001793(defun py-goto-beyond-final-line ()
1794 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001795 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001796 (while (and (py-continuation-line-p)
1797 (not (eobp)))
1798 ;; skip over the backslash flavor
1799 (while (and (py-backslash-continuation-line-p)
1800 (not (eobp)))
1801 (forward-line 1))
1802 ;; if in nest, zip to the end of the nest
1803 (setq state (py-parse-state))
1804 (if (and (not (zerop (car state)))
1805 (not (eobp)))
1806 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001808 ;; the 3rd argument should be plain 0
1809 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1810 nil state)
1811 (forward-line 1))))))
1812
1813;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001814;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001815(defun py-statement-opens-block-p ()
1816 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001817 (let ((start (point))
1818 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1819 (searching t)
1820 (answer nil)
1821 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822 (goto-char start)
1823 (while searching
1824 ;; look for a colon with nothing after it except whitespace, and
1825 ;; maybe a comment
1826 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1827 finish t)
1828 (if (eq (point) finish) ; note: no `else' clause; just
1829 ; keep searching if we're not at
1830 ; the end yet
1831 ;; sure looks like it opens a block -- but it might
1832 ;; be in a comment
1833 (progn
1834 (setq searching nil) ; search is done either way
1835 (setq state (parse-partial-sexp start
1836 (match-beginning 0)))
1837 (setq answer (not (nth 4 state)))))
1838 ;; search failed: couldn't find another interesting colon
1839 (setq searching nil)))
1840 answer)))
1841
1842;; go to point right beyond final line of block begun by the current
1843;; line. This is the same as where py-goto-beyond-final-line goes
1844;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001845;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846(defun py-goto-beyond-block ()
1847 (if (py-statement-opens-block-p)
1848 (py-mark-block nil 'just-move)
1849 (py-goto-beyond-final-line)))
1850
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001851;; go to start of first statement (not blank or comment or
1852;; continuation line) at or preceding point. returns t if there is
1853;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854(defun py-goto-statement-at-or-above ()
1855 (py-goto-initial-line)
1856 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857 ;; skip back over blank & comment lines
1858 ;; note: will skip a blank or comment line that happens to be
1859 ;; a continuation line too
1860 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1861 (progn (py-goto-initial-line) t)
1862 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 t))
1864
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865;; go to start of first statement (not blank or comment or
1866;; continuation line) following the statement containing point returns
1867;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868(defun py-goto-statement-below ()
1869 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001870 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001871 (py-goto-beyond-final-line)
1872 (while (and
1873 (looking-at py-blank-or-comment-re)
1874 (not (eobp)))
1875 (forward-line 1))
1876 (if (eobp)
1877 (progn (goto-char start) nil)
1878 t)))
1879
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001880;; go to start of statement, at or preceding point, starting with
1881;; keyword KEY. Skips blank lines and non-indenting comments upward
1882;; first. If that statement starts with KEY, done, else go back to
1883;; first enclosing block starting with KEY. If successful, leaves
1884;; point at the start of the KEY line & returns t. Else leaves point
1885;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001886(defun py-go-up-tree-to-keyword (key)
1887 ;; skip blanks and non-indenting #
1888 (py-goto-initial-line)
1889 (while (and
1890 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1891 (zerop (forward-line -1))) ; go back
1892 nil)
1893 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001894 (let* ((re (concat "[ \t]*" key "\\b"))
1895 (case-fold-search nil) ; let* so looking-at sees this
1896 (found (looking-at re))
1897 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001898 (while (not (or found dead))
1899 (condition-case nil ; in case no enclosing block
1900 (py-goto-block-up 'no-mark)
1901 (error (setq dead t)))
1902 (or dead (setq found (looking-at re))))
1903 (beginning-of-line)
1904 found))
1905
1906;; return string in buffer from start of indentation to end of line;
1907;; prefix "..." if leading whitespace was skipped
1908(defun py-suck-up-leading-text ()
1909 (save-excursion
1910 (back-to-indentation)
1911 (concat
1912 (if (bolp) "" "...")
1913 (buffer-substring (point) (progn (end-of-line) (point))))))
1914
1915;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1916;; as a Lisp symbol; return nil if none
1917(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001919 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1920 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1921 nil)))
1922
1923(defun py-make-temp-name ()
1924 (make-temp-name
1925 (concat (file-name-as-directory py-temp-directory) "python")))
1926
1927(defun py-delete-file-silently (fname)
1928 (condition-case nil
1929 (delete-file fname)
1930 (error nil)))
1931
1932(defun py-kill-emacs-hook ()
1933 ;; delete our temp files
1934 (while py-file-queue
1935 (py-delete-file-silently (car py-file-queue))
1936 (setq py-file-queue (cdr py-file-queue)))
1937 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1938 ;; run the hook we inherited, if any
1939 (and py-inherited-kill-emacs-hook
1940 (funcall py-inherited-kill-emacs-hook))))
1941
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001942;; make PROCESS's buffer visible, append STRING to it, and force
1943;; display; also make shell-mode believe the user typed this string,
1944;; so that kill-output-from-shell and show-output-from-shell work
1945;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001946(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001947 (let ((cbuf (current-buffer))
1948 (pbuf (process-buffer process))
1949 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001950 (set-buffer pbuf)
1951 (goto-char (point-max))
1952 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001953 (if (not (or py-this-is-emacs-19-p
1954 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001955 (move-marker last-input-start (point))) ; muck w/ shell-mode
1956 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001957 (if (not (or py-this-is-emacs-19-p
1958 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001959 (move-marker last-input-end (point))) ; muck w/ shell-mode
1960 (set-buffer cbuf))
1961 (sit-for 0))
1962
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001963(defun py-keep-region-active ()
1964 ;; do whatever is necessary to keep the region active in XEmacs.
1965 ;; Ignore byte-compiler warnings you might see. Also note that
1966 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1967 ;; require us to take explicit action.
1968 (and (boundp 'zmacs-region-stays)
1969 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001970
1971
Barry Warsaw850437a1995-03-08 21:50:28 +00001972(defconst py-version "$Revision$"
1973 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001974(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001975 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001976
Barry Warsaw850437a1995-03-08 21:50:28 +00001977(defun py-version ()
1978 "Echo the current version of `python-mode' in the minibuffer."
1979 (interactive)
1980 (message "Using `python-mode' version %s" py-version)
1981 (py-keep-region-active))
1982
1983;; only works under Emacs 19
1984;(eval-when-compile
1985; (require 'reporter))
1986
1987(defun py-submit-bug-report (enhancement-p)
1988 "Submit via mail a bug report on `python-mode'.
1989With \\[universal-argument] just submit an enhancement request."
1990 (interactive
1991 (list (not (y-or-n-p
1992 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001993 (let ((reporter-prompt-for-summary-p (if enhancement-p
1994 "(Very) brief summary: "
1995 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001996 (require 'reporter)
1997 (reporter-submit-bug-report
1998 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001999 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002000 ;; varlist
2001 (if enhancement-p nil
2002 '(py-python-command
2003 py-indent-offset
2004 py-block-comment-prefix
2005 py-scroll-process-buffer
2006 py-temp-directory
2007 py-beep-if-tab-change))
2008 nil ;pre-hooks
2009 nil ;post-hooks
2010 "Dear Barry,") ;salutation
2011 (if enhancement-p nil
2012 (set-mark (point))
2013 (insert
2014"Please replace this text with a sufficiently large code sample\n\
2015and an exact recipe so that I can reproduce your problem. Failure\n\
2016to do so may mean a greater delay in fixing your bug.\n\n")
2017 (exchange-point-and-mark)
2018 (py-keep-region-active))))
2019
2020
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002021;; arrange to kill temp files when Emacs exists
2022(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2023 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2024 ;; have to trust that other people are as respectful of our hook
2025 ;; fiddling as we are of theirs
2026 (if (boundp 'py-inherited-kill-emacs-hook)
2027 ;; we were loaded before -- trust others not to have screwed us
2028 ;; in the meantime (no choice, really)
2029 nil
2030 ;; else arrange for our hook to run theirs
2031 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2032 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2033
2034
2035
2036(provide 'python-mode)
2037;;; python-mode.el ends here