blob: 31cd35251f14f778f4cdd3cc56fa8bc83b2533a8 [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))
41
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000042;; Here's a brief list of recent additions/improvements:
43;;
44;; - Wrapping and indentation within triple quote strings should work
45;; properly now.
46;; - `Standard' bug reporting mechanism (use C-c C-b)
47;; - py-mark-block was moved to C-c C-m
48;; - C-c C-v shows you the python-mode version
49;; - a basic python-font-lock-keywords has been added for Emacs 19
50;; font-lock colorizations.
51;; - proper interaction with pending-del and del-sel modes.
52;; - New py-electric-colon (:) command for improved outdenting. Also
53;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw03970731996-07-03 23:12:52 +000054;; - improved (I think) C-c > and C-c <
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000055
Barry Warsaw7b0f5681995-03-08 21:33:04 +000056;; Here's a brief to do list:
57;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000058;; - Better integration with gud-mode for debugging.
59;; - Rewrite according to GNU Emacs Lisp standards.
60;; - py-delete-char should obey numeric arguments.
61;; - even better support for outdenting. Guido suggests outdents of
62;; at least one level after a return, raise, break, or continue
63;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000064;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000065
Barry Warsaw7b0f5681995-03-08 21:33:04 +000066;; If you can think of more things you'd like to see, drop me a line.
67;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
68;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000069;; Note that I only test things on XEmacs. If you port stuff to FSF
70;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
71;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000072
Barry Warsaw7b0f5681995-03-08 21:33:04 +000073;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000074;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000075;; |Major mode for editing Python programs
76;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsaw7b0f5681995-03-08 21:33:04 +000078;;; Code:
79
80
81;; user definable variables
82;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000083
84(defvar py-python-command "python"
85 "*Shell command used to start Python interpreter.")
86
Barry Warsaw17914f41995-11-03 18:25:15 +000087(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000088 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000089Note that `\\[py-guess-indent-offset]' can usually guess a good value
90when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000091
Barry Warsaw095e9c61995-09-19 20:01:42 +000092(defvar py-align-multiline-strings-p t
93 "*Flag describing how multiline triple quoted strings are aligned.
94When this flag is non-nil, continuation lines are lined up under the
95preceding line's indentation. When this flag is nil, continuation
96lines are aligned to column zero.")
97
Barry Warsaw7ae77681994-12-12 20:38:05 +000098(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +000099 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000100This should follow the convention for non-indenting comment lines so
101that the indentation commands won't get confused (i.e., the string
102should be of the form `#x...' where `x' is not a blank or a tab, and
103`...' is arbitrary).")
104
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000105(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000106 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000107
Barry Warsaw6d627751996-03-06 18:41:38 +0000108When nil, all comment lines are skipped for indentation purposes, and
109in Emacs 19, a faster algorithm is used.
110
111When t, lines that begin with a single `#' are a hint to subsequent
112line indentation. If the previous line is such a comment line (as
113opposed to one that starts with `py-block-comment-prefix'), then it's
114indentation is used as a hint for this line's indentation. Lines that
115begin with `py-block-comment-prefix' are ignored for indentation
116purposes.
117
118When not nil or t, comment lines that begin with a `#' are used as
119indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000120
Barry Warsaw7ae77681994-12-12 20:38:05 +0000121(defvar py-scroll-process-buffer t
122 "*Scroll Python process buffer as output arrives.
123If nil, the Python process buffer acts, with respect to scrolling, like
124Shell-mode buffers normally act. This is surprisingly complicated and
125so won't be explained here; in fact, you can't get the whole story
126without studying the Emacs C code.
127
128If non-nil, the behavior is different in two respects (which are
129slightly inaccurate in the interest of brevity):
130
131 - If the buffer is in a window, and you left point at its end, the
132 window will scroll as new output arrives, and point will move to the
133 buffer's end, even if the window is not the selected window (that
134 being the one the cursor is in). The usual behavior for shell-mode
135 windows is not to scroll, and to leave point where it was, if the
136 buffer is in a window other than the selected window.
137
138 - If the buffer is not visible in any window, and you left point at
139 its end, the buffer will be popped into a window as soon as more
140 output arrives. This is handy if you have a long-running
141 computation and don't want to tie up screen area waiting for the
142 output. The usual behavior for a shell-mode buffer is to stay
143 invisible until you explicitly visit it.
144
145Note the `and if you left point at its end' clauses in both of the
146above: you can `turn off' the special behaviors while output is in
147progress, by visiting the Python buffer and moving point to anywhere
148besides the end. Then the buffer won't scroll, point will remain where
149you leave it, and if you hide the buffer it will stay hidden until you
150visit it again. You can enable and disable the special behaviors as
151often as you like, while output is in progress, by (respectively) moving
152point to, or away from, the end of the buffer.
153
154Warning: If you expect a large amount of output, you'll probably be
155happier setting this option to nil.
156
157Obscure: `End of buffer' above should really say `at or beyond the
158process mark', but if you know what that means you didn't need to be
159told <grin>.")
160
161(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000162 (let ((ok '(lambda (x)
163 (and x
164 (setq x (expand-file-name x)) ; always true
165 (file-directory-p x)
166 (file-writable-p x)
167 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000168 (or (funcall ok (getenv "TMPDIR"))
169 (funcall ok "/usr/tmp")
170 (funcall ok "/tmp")
171 (funcall ok ".")
172 (error
173 "Couldn't find a usable temp directory -- set py-temp-directory")))
174 "*Directory used for temp files created by a *Python* process.
175By default, the first directory from this list that exists and that you
176can write into: the value (if any) of the environment variable TMPDIR,
177/usr/tmp, /tmp, or the current directory.")
178
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000179(defvar py-beep-if-tab-change t
180 "*Ring the bell if tab-width is changed.
181If a comment of the form
182
183 \t# vi:set tabsize=<number>:
184
185is found before the first code line when the file is entered, and the
186current value of (the general Emacs variable) `tab-width' does not
187equal <number>, `tab-width' is set to <number>, a message saying so is
188displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
189the Emacs bell is also rung as a warning.")
190
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000191(defconst python-font-lock-keywords
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000192 (let* ((keywords '("access" "and" "break" "continue"
193 "del" "elif" "else:" "except"
194 "except:" "exec" "finally:" "for"
195 "from" "global" "if" "import"
196 "in" "is" "lambda" "not"
197 "or" "pass" "print" "raise"
198 "return" "try:" "while"
199 ))
200 (kwregex (mapconcat 'identity keywords "\\|")))
201 (list
202 ;; keywords not at beginning of line
203 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
204 ;; keywords at beginning of line. i don't think regexps are
205 ;; powerful enough to handle these two cases in one regexp.
206 ;; prove me wrong!
207 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
208 ;; classes
209 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
210 1 font-lock-type-face)
211 ;; functions
212 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
213 1 font-lock-function-name-face)
214 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000215 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000216
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000217
218;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
219;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
220
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000221(make-variable-buffer-local 'py-indent-offset)
222
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000223;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
224;; seems to be the standard way of checking this.
225;; BAW - This is *not* the right solution. When at all possible,
226;; instead of testing for the version of Emacs, use feature tests.
227
228(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
229(setq py-this-is-emacs-19-p
230 (and
231 (not py-this-is-lucid-emacs-p)
232 (string-match "^19\\." emacs-version)))
233
Barry Warsaw7ae77681994-12-12 20:38:05 +0000234;; have to bind py-file-queue before installing the kill-emacs hook
235(defvar py-file-queue nil
236 "Queue of Python temp files awaiting execution.
237Currently-active file is at the head of the list.")
238
239;; define a mode-specific abbrev table for those who use such things
240(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000241 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000242(define-abbrev-table 'python-mode-abbrev-table nil)
243
Barry Warsaw7ae77681994-12-12 20:38:05 +0000244(defvar python-mode-hook nil
245 "*Hook called by `python-mode'.")
246
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000247;; in previous version of python-mode.el, the hook was incorrectly
248;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249(and (fboundp 'make-obsolete-variable)
250 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
251
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000252(defvar py-mode-map ()
253 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000254
Barry Warsaw7ae77681994-12-12 20:38:05 +0000255(if py-mode-map
256 ()
257 (setq py-mode-map (make-sparse-keymap))
258
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000259 ;; shadow global bindings for newline-and-indent w/ the py- version.
260 ;; BAW - this is extremely bad form, but I'm not going to change it
261 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000262 (mapcar (function (lambda (key)
263 (define-key
264 py-mode-map key 'py-newline-and-indent)))
265 (where-is-internal 'newline-and-indent))
266
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000267 ;; BAW - you could do it this way, but its not considered proper
268 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269 (mapcar (function
270 (lambda (x)
271 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000272 '((":" . py-electric-colon)
273 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000274 ("\C-c|" . py-execute-region)
275 ("\C-c!" . py-shell)
276 ("\177" . py-delete-char)
277 ("\n" . py-newline-and-indent)
278 ("\C-c:" . py-guess-indent-offset)
279 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000280 ("\C-c\C-l" . py-shift-region-left)
281 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000282 ("\C-c<" . py-shift-region-left)
283 ("\C-c>" . py-shift-region-right)
284 ("\C-c\C-n" . py-next-statement)
285 ("\C-c\C-p" . py-previous-statement)
286 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000287 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000288 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000289 ("\C-c?" . py-describe-mode)
290 ("\C-c\C-hm" . py-describe-mode)
291 ("\e\C-a" . beginning-of-python-def-or-class)
292 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000293 ( "\e\C-h" . mark-python-def-or-class)))
294 ;; should do all keybindings this way
295 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
296 (define-key py-mode-map "\C-c\C-v" 'py-version)
297 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000298
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000299(defvar py-mode-syntax-table nil
300 "Syntax table used in `python-mode' buffers.")
301
Barry Warsaw7ae77681994-12-12 20:38:05 +0000302(if py-mode-syntax-table
303 ()
304 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000305 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000306 (mapcar (function
307 (lambda (x) (modify-syntax-entry
308 (car x) (cdr x) py-mode-syntax-table)))
309 '(( ?\( . "()" ) ( ?\) . ")(" )
310 ( ?\[ . "(]" ) ( ?\] . ")[" )
311 ( ?\{ . "(}" ) ( ?\} . "){" )
312 ;; fix operator symbols misassigned in the std table
313 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
314 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
315 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
316 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000317 ;; Guido and I disagree about this. Underscore should be
318 ;; symbol constituent by not word. For historical
319 ;; reasons, I leave it as is. -baw
320 ;;( ?\_ . "_" ) ; underscore is legit in symbols, but not words
321 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000322 ( ?\' . "\"") ; single quote is string quote
323 ( ?\" . "\"" ) ; double quote is string quote too
324 ( ?\` . "$") ; backquote is open and close paren
325 ( ?\# . "<") ; hash starts comment
326 ( ?\n . ">")))) ; newline ends comment
327
328(defconst py-stringlit-re
329 (concat
330 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
331 "\\|" ; or
332 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000333 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000334
335;; this is tricky because a trailing backslash does not mean
336;; continuation if it's in a comment
337(defconst py-continued-re
338 (concat
339 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
340 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000341 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000342
343(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000344 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000345
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000346(defconst py-outdent-re
347 (concat "\\(" (mapconcat 'identity
348 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000349 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000350 "finally:"
351 "elif\\s +.*:")
352 "\\|")
353 "\\)")
354 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000356(defconst py-no-outdent-re
357 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000358 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000359 "except\\(\\s +.*\\)?:"
360 "while\\s +.*:"
361 "for\\s +.*:"
362 "if\\s +.*:"
363 "elif\\s +.*:")
364 "\\|")
365 "\\)")
366 "Regexp matching lines to not outdent after.")
367
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000368
369;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000370(defun python-mode ()
371 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000372To submit a problem report, enter `\\[py-submit-bug-report]' from a
373`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
374documentation. To see what version of `python-mode' you are running,
375enter `\\[py-version]'.
376
377This mode knows about Python indentation, tokens, comments and
378continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000379
380COMMANDS
381\\{py-mode-map}
382VARIABLES
383
384py-indent-offset\tindentation increment
385py-block-comment-prefix\tcomment string used by py-comment-region
386py-python-command\tshell command to invoke Python interpreter
387py-scroll-process-buffer\talways scroll Python process buffer
388py-temp-directory\tdirectory used for temp files (if needed)
389py-beep-if-tab-change\tring the bell if tab-width is changed"
390 (interactive)
391 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000392 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393 (setq major-mode 'python-mode
394 mode-name "Python"
395 local-abbrev-table python-mode-abbrev-table)
396 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000397 ;; Emacs 19 requires this
398 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
399 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000400 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000401 (mapcar (function (lambda (x)
402 (make-local-variable (car x))
403 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000404 '((paragraph-separate . "^[ \t]*$")
405 (paragraph-start . "^[ \t]*$")
406 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000407 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000408 (comment-start-skip . "# *")
409 (comment-column . 40)
410 (indent-region-function . py-indent-region)
411 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000412 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000413 ;;
414 ;; not sure where the magic comment has to be; to save time
415 ;; searching for a rarity, we give up if it's not found prior to the
416 ;; first executable statement.
417 ;;
418 ;; BAW - on first glance, this seems like complete hackery. Why was
419 ;; this necessary, and is it still necessary?
420 (let ((case-fold-search nil)
421 (start (point))
422 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000423 (if (re-search-forward
424 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
425 (prog2 (py-next-statement 1) (point) (goto-char 1))
426 t)
427 (progn
428 (setq new-tab-width
429 (string-to-int
430 (buffer-substring (match-beginning 1) (match-end 1))))
431 (if (= tab-width new-tab-width)
432 nil
433 (setq tab-width new-tab-width)
434 (message "Caution: tab-width changed to %d" new-tab-width)
435 (if py-beep-if-tab-change (beep)))))
436 (goto-char start))
437
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000438 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000439 (if python-mode-hook
440 (run-hooks 'python-mode-hook)
441 (run-hooks 'py-mode-hook)))
442
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000443
Barry Warsaw826255b1996-03-22 16:09:34 +0000444(defun py-keep-region-active ()
445 ;; Do whatever is necessary to keep the region active in
446 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
447 ;; ignore byte-compiler warnings you might see.
448 (and (boundp 'zmacs-region-stays)
449 (setq zmacs-region-stays t)))
450
Barry Warsawb91b7431995-03-14 15:55:20 +0000451;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000452(defun py-outdent-p ()
453 ;; returns non-nil if the current line should outdent one level
454 (save-excursion
455 (and (progn (back-to-indentation)
456 (looking-at py-outdent-re))
457 (progn (backward-to-indentation 1)
458 (while (or (looking-at py-blank-or-comment-re)
459 (bobp))
460 (backward-to-indentation 1))
461 (not (looking-at py-no-outdent-re)))
462 )))
463
464
Barry Warsawb91b7431995-03-14 15:55:20 +0000465(defun py-electric-colon (arg)
466 "Insert a colon.
467In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000468argument is provided, that many colons are inserted non-electrically.
469Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000470 (interactive "P")
471 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000472 ;; are we in a string or comment?
473 (if (save-excursion
474 (let ((pps (parse-partial-sexp (save-excursion
475 (beginning-of-python-def-or-class)
476 (point))
477 (point))))
478 (not (or (nth 3 pps) (nth 4 pps)))))
479 (save-excursion
480 (let ((here (point))
481 (outdent 0)
482 (indent (py-compute-indentation)))
483 (if (and (not arg)
484 (py-outdent-p)
485 (= indent (save-excursion
486 (forward-line -1)
487 (py-compute-indentation)))
488 )
489 (setq outdent py-indent-offset))
490 ;; Don't indent, only outdent. This assumes that any lines that
491 ;; are already outdented relative to py-compute-indentation were
492 ;; put there on purpose. Its highly annoying to have `:' indent
493 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
494 ;; there a better way to determine this???
495 (if (< (current-indentation) indent) nil
496 (goto-char here)
497 (beginning-of-line)
498 (delete-horizontal-space)
499 (indent-to (- indent outdent))
500 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000501
502
Barry Warsaw7ae77681994-12-12 20:38:05 +0000503;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000504(defun py-shell ()
505 "Start an interactive Python interpreter in another window.
506This is like Shell mode, except that Python is running in the window
507instead of a shell. See the `Interactive Shell' and `Shell Mode'
508sections of the Emacs manual for details, especially for the key
509bindings active in the `*Python*' buffer.
510
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000511See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000512behavior in the process window.
513
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000514Warning: Don't use an interactive Python if you change sys.ps1 or
515sys.ps2 from their default values, or if you're running code that
516prints `>>> ' or `... ' at the start of a line. `python-mode' can't
517distinguish your output from Python's output, and assumes that `>>> '
518at the start of a line is a prompt from Python. Similarly, the Emacs
519Shell mode code assumes that both `>>> ' and `... ' at the start of a
520line are Python prompts. Bad things can happen if you fool either
521mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000522
523Warning: If you do any editing *in* the process buffer *while* the
524buffer is accepting output from Python, do NOT attempt to `undo' the
525changes. Some of the output (nowhere near the parts you changed!) may
526be lost if you do. This appears to be an Emacs bug, an unfortunate
527interaction between undo and process filters; the same problem exists in
528non-Python process buffers using the default (Emacs-supplied) process
529filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000530 ;; BAW - should undo be disabled in the python process buffer, if
531 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000532 (interactive)
533 (if py-this-is-emacs-19-p
534 (progn
535 (require 'comint)
536 (switch-to-buffer-other-window
537 (make-comint "Python" py-python-command)))
538 (progn
539 (require 'shell)
540 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000541 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000542 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000543 (make-local-variable 'shell-prompt-pattern)
544 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
545 (set-process-filter (get-buffer-process (current-buffer))
546 'py-process-filter)
547 (set-syntax-table py-mode-syntax-table))
548
549(defun py-execute-region (start end)
550 "Send the region between START and END to a Python interpreter.
551If there is a *Python* process it is used.
552
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000553Hint: If you want to execute part of a Python file several times
554\(e.g., perhaps you're developing a function and want to flesh it out
555a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
556the region of interest, and send the code to a *Python* process via
557`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000558
559Following are subtleties to note when using a *Python* process:
560
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000561If a *Python* process is used, the region is copied into a temporary
562file (in directory `py-temp-directory'), and an `execfile' command is
563sent to Python naming that file. If you send regions faster than
564Python can execute them, `python-mode' will save them into distinct
565temp files, and execute the next one in the queue the next time it
566sees a `>>> ' prompt from Python. Each time this happens, the process
567buffer is popped into a window (if it's not already in some window) so
568you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000569
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000570 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000571
572is inserted at the end.
573
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000574Caution: No more than 26 regions can be pending at any given time.
575This limit is (indirectly) inherited from libc's mktemp(3).
576`python-mode' does not try to protect you from exceeding the limit.
577It's extremely unlikely that you'll get anywhere close to the limit in
578practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000579
580See the `\\[py-shell]' docs for additional warnings."
581 (interactive "r")
582 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000583 (let ((pyproc (get-process "Python"))
584 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000585 (if (null pyproc)
586 (shell-command-on-region start end py-python-command)
587 ;; else feed it thru a temp file
588 (setq fname (py-make-temp-name))
589 (write-region start end fname nil 'no-msg)
590 (setq py-file-queue (append py-file-queue (list fname)))
591 (if (cdr py-file-queue)
592 (message "File %s queued for execution" fname)
593 ;; else
594 (py-execute-file pyproc fname)))))
595
596(defun py-execute-file (pyproc fname)
597 (py-append-to-process-buffer
598 pyproc
599 (format "## working on region in file %s ...\n" fname))
600 (process-send-string pyproc (format "execfile('%s')\n" fname)))
601
602(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000603 (let ((curbuf (current-buffer))
604 (pbuf (process-buffer pyproc))
605 (pmark (process-mark pyproc))
606 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000607
608 ;; make sure we switch to a different buffer at least once. if we
609 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000610 ;; window, and point is before the end, and lots of output is
611 ;; coming at a fast pace, then (a) simple cursor-movement commands
612 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
613 ;; to have a visible effect (the window just doesn't get updated,
614 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
615 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000616 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000617 ;; #b makes no sense to me at all. #a almost makes sense: unless
618 ;; we actually change buffers, set_buffer_internal in buffer.c
619 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
620 ;; seems to make the Emacs command loop reluctant to update the
621 ;; display. Perhaps the default process filter in process.c's
622 ;; read_process_output has update_mode_lines++ for a similar
623 ;; reason? beats me ...
624
625 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000626 (if (eq curbuf pbuf) ; mysterious ugly hack
627 (set-buffer (get-buffer-create "*scratch*")))
628
629 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000630 (let* ((start (point))
631 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000632 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000633 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000634 (goto-char pmark)
635 (insert string)
636 (move-marker pmark (point))
637 (setq file-finished
638 (and py-file-queue
639 (equal ">>> "
640 (buffer-substring
641 (prog2 (beginning-of-line) (point)
642 (goto-char pmark))
643 (point)))))
644 (if goback (goto-char start)
645 ;; else
646 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000647 (let* ((pop-up-windows t)
648 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000649 (set-window-point pwin (point)))))
650 (set-buffer curbuf)
651 (if file-finished
652 (progn
653 (py-delete-file-silently (car py-file-queue))
654 (setq py-file-queue (cdr py-file-queue))
655 (if py-file-queue
656 (py-execute-file pyproc (car py-file-queue)))))
657 (and goend
658 (progn (set-buffer pbuf)
659 (goto-char (point-max))))
660 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000661
662(defun py-execute-buffer ()
663 "Send the contents of the buffer to a Python interpreter.
664If there is a *Python* process buffer it is used. If a clipping
665restriction is in effect, only the accessible portion of the buffer is
666sent. A trailing newline will be supplied if needed.
667
668See the `\\[py-execute-region]' docs for an account of some subtleties."
669 (interactive)
670 (py-execute-region (point-min) (point-max)))
671
672
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000673
674;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000675(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000676 "Reduce indentation or delete character.
677If point is at the leftmost column, deletes the preceding newline.
678
679Else if point is at the leftmost non-blank character of a line that is
680neither a continuation line nor a non-indenting comment line, or if
681point is at the end of a blank line, reduces the indentation to match
682that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000684of where you are. With numeric count, outdents that many blocks (but
685not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000686
687Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000688needed so that only a single column position is deleted. Numeric
689argument delets that many characters."
690 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000691 (if (or (/= (current-indentation) (current-column))
692 (bolp)
693 (py-continuation-line-p)
694 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000695 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000696 ;; else indent the same as the colon line that opened the block
697
698 ;; force non-blank so py-goto-block-up doesn't ignore it
699 (insert-char ?* 1)
700 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000701 (let ((base-indent 0) ; indentation of base line
702 (base-text "") ; and text of base line
703 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000704 (save-excursion
705 (while (< 0 count)
706 (condition-case nil ; in case no enclosing block
707 (progn
708 (py-goto-block-up 'no-mark)
709 (setq base-indent (current-indentation)
710 base-text (py-suck-up-leading-text)
711 base-found-p t))
712 (error nil))
713 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000714 (delete-char 1) ; toss the dummy character
715 (delete-horizontal-space)
716 (indent-to base-indent)
717 (if base-found-p
718 (message "Closes block: %s" base-text)))))
719
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000720;; required for pending-del and delsel modes
721(put 'py-delete-char 'delete-selection 'supersede)
722(put 'py-delete-char 'pending-delete 'supersede)
723
Barry Warsaw7ae77681994-12-12 20:38:05 +0000724(defun py-indent-line ()
725 "Fix the indentation of the current line according to Python rules."
726 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000727 (let* ((ci (current-indentation))
728 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000729 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000730 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000731 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000732 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000733 (if (/= ci need)
734 (save-excursion
735 (beginning-of-line)
736 (delete-horizontal-space)
737 (indent-to need)))
738 (if move-to-indentation-p (back-to-indentation))))
739
740(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000741 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000742This is just `strives to' because correct indentation can't be computed
743from scratch for Python code. In general, deletes the whitespace before
744point, inserts a newline, and takes an educated guess as to how you want
745the new line indented."
746 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000747 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748 (if (< ci (current-column)) ; if point beyond indentation
749 (newline-and-indent)
750 ;; else try to act like newline-and-indent "normally" acts
751 (beginning-of-line)
752 (insert-char ?\n 1)
753 (move-to-column ci))))
754
755(defun py-compute-indentation ()
756 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000757 (let ((pps (parse-partial-sexp (save-excursion
758 (beginning-of-python-def-or-class)
759 (point))
760 (point))))
761 (beginning-of-line)
762 (cond
763 ;; are we inside a string or comment?
764 ((or (nth 3 pps) (nth 4 pps))
765 (save-excursion
766 (if (not py-align-multiline-strings-p) 0
767 ;; skip back over blank & non-indenting comment lines
768 ;; note: will skip a blank or non-indenting comment line
769 ;; that happens to be a continuation line too
770 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
771 (back-to-indentation)
772 (current-column))))
773 ;; are we on a continuation line?
774 ((py-continuation-line-p)
775 (let ((startpos (point))
776 (open-bracket-pos (py-nesting-level))
777 endpos searching found)
778 (if open-bracket-pos
779 (progn
780 ;; align with first item in list; else a normal
781 ;; indent beyond the line with the open bracket
782 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
783 ;; is the first list item on the same line?
784 (skip-chars-forward " \t")
785 (if (null (memq (following-char) '(?\n ?# ?\\)))
786 ; yes, so line up with it
787 (current-column)
788 ;; first list item on another line, or doesn't exist yet
789 (forward-line 1)
790 (while (and (< (point) startpos)
791 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
792 (forward-line 1))
793 (if (< (point) startpos)
794 ;; again mimic the first list item
795 (current-indentation)
796 ;; else they're about to enter the first item
797 (goto-char open-bracket-pos)
798 (+ (current-indentation) py-indent-offset))))
799
800 ;; else on backslash continuation line
801 (forward-line -1)
802 (if (py-continuation-line-p) ; on at least 3rd line in block
803 (current-indentation) ; so just continue the pattern
804 ;; else started on 2nd line in block, so indent more.
805 ;; if base line is an assignment with a start on a RHS,
806 ;; indent to 2 beyond the leftmost "="; else skip first
807 ;; chunk of non-whitespace characters on base line, + 1 more
808 ;; column
809 (end-of-line)
810 (setq endpos (point) searching t)
811 (back-to-indentation)
812 (setq startpos (point))
813 ;; look at all "=" from left to right, stopping at first
814 ;; one not nested in a list or string
815 (while searching
816 (skip-chars-forward "^=" endpos)
817 (if (= (point) endpos)
818 (setq searching nil)
819 (forward-char 1)
820 (setq state (parse-partial-sexp startpos (point)))
821 (if (and (zerop (car state)) ; not in a bracket
822 (null (nth 3 state))) ; & not in a string
823 (progn
824 (setq searching nil) ; done searching in any case
825 (setq found
826 (not (or
827 (eq (following-char) ?=)
828 (memq (char-after (- (point) 2))
829 '(?< ?> ?!)))))))))
830 (if (or (not found) ; not an assignment
831 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
832 (progn
833 (goto-char startpos)
834 (skip-chars-forward "^ \t\n")))
835 (1+ (current-column))))))
836
837 ;; not on a continuation line
838
839 ;; if at start of restriction, or on a non-indenting comment
840 ;; line, assume they intended whatever's there
841 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
842 (current-indentation))
843
844 ;; else indentation based on that of the statement that
845 ;; precedes us; use the first line of that statement to
846 ;; establish the base, in case the user forced a non-std
847 ;; indentation for the continuation lines (if any)
848 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000849 ;; skip back over blank & non-indenting comment lines note:
850 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000851 ;; happens to be a continuation line too. use fast Emacs 19
852 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000853 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000854 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000855 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000856 (let (done)
857 (while (not done)
858 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
859 nil 'move)
860 (setq done (or (eq py-honor-comment-indentation t)
861 (bobp)
862 (/= (following-char) ?#)
863 (not (zerop (current-column)))))
864 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000865 ;; if we landed inside a string, go to the beginning of that
866 ;; string. this handles triple quoted, multi-line spanning
867 ;; strings.
868 (py-goto-initial-line)
869 (if (py-statement-opens-block-p)
870 (+ (current-indentation) py-indent-offset)
871 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000872
873(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000874 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000875By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000876`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000878`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000879their own buffer-local copy), both those currently existing and those
880created later in the Emacs session.
881
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000882Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000883There's no excuse for such foolishness, but sometimes you have to deal
884with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000885`py-indent-offset' to what it thinks it was when they created the
886mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887
888Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889looking for a line that opens a block of code. `py-indent-offset' is
890set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000891statement following it. If the search doesn't succeed going forward,
892it's tried again going backward."
893 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000894 (let (new-value
895 (start (point))
896 restart
897 (found nil)
898 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000899 (py-goto-initial-line)
900 (while (not (or found (eobp)))
901 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
902 (progn
903 (setq restart (point))
904 (py-goto-initial-line)
905 (if (py-statement-opens-block-p)
906 (setq found t)
907 (goto-char restart)))))
908 (if found
909 ()
910 (goto-char start)
911 (py-goto-initial-line)
912 (while (not (or found (bobp)))
913 (setq found
914 (and
915 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
916 (or (py-goto-initial-line) t) ; always true -- side effect
917 (py-statement-opens-block-p)))))
918 (setq colon-indent (current-indentation)
919 found (and found (zerop (py-next-statement 1)))
920 new-value (- (current-indentation) colon-indent))
921 (goto-char start)
922 (if found
923 (progn
924 (funcall (if global 'kill-local-variable 'make-local-variable)
925 'py-indent-offset)
926 (setq py-indent-offset new-value)
927 (message "%s value of py-indent-offset set to %d"
928 (if global "Global" "Local")
929 py-indent-offset))
930 (error "Sorry, couldn't guess a value for py-indent-offset"))))
931
932(defun py-shift-region (start end count)
933 (save-excursion
934 (goto-char end) (beginning-of-line) (setq end (point))
935 (goto-char start) (beginning-of-line) (setq start (point))
936 (indent-rigidly start end count)))
937
938(defun py-shift-region-left (start end &optional count)
939 "Shift region of Python code to the left.
940The lines from the line containing the start of the current region up
941to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000942shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000943
944If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000945many columns. With no active region, outdent only the current line.
946You cannot outdent the region if any line is already at column zero."
947 (interactive
948 (let ((p (point))
949 (m (mark))
950 (arg current-prefix-arg))
951 (if m
952 (list (min p m) (max p m) arg)
953 (list p (save-excursion (forward-line 1) (point)) arg))))
954 ;; if any line is at column zero, don't shift the region
955 (save-excursion
956 (goto-char start)
957 (while (< (point) end)
958 (back-to-indentation)
959 (if (zerop (current-column))
960 (error "Region is at left edge."))
961 (forward-line 1)))
962 (py-shift-region start end (- (prefix-numeric-value
963 (or count py-indent-offset))))
964 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000965
966(defun py-shift-region-right (start end &optional count)
967 "Shift region of Python code to the right.
968The lines from the line containing the start of the current region up
969to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000970shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971
972If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000973many columns. With no active region, indent only the current line."
974 (interactive
975 (let ((p (point))
976 (m (mark))
977 (arg current-prefix-arg))
978 (if m
979 (list (min p m) (max p m) arg)
980 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000981 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000982 (or count py-indent-offset)))
983 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000984
985(defun py-indent-region (start end &optional indent-offset)
986 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000987
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988The lines from the line containing the start of the current region up
989to (but not including) the line containing the end of the region are
990reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000991character in the first column, the first line is left alone and the
992rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +0000993region is reindented with respect to the (closest code or indenting
994comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
996This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000997control structures are introduced or removed, or to reformat code
998using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999
1000If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001001the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002used.
1003
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005is called! This function does not compute proper indentation from
1006scratch (that's impossible in Python), it merely adjusts the existing
1007indentation to be correct in context.
1008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001009Warning: This function really has no idea what to do with
1010non-indenting comment lines, and shifts them as if they were indenting
1011comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001013Special cases: whitespace is deleted from blank lines; continuation
1014lines are shifted by the same amount their initial line was shifted,
1015in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018 (save-excursion
1019 (goto-char end) (beginning-of-line) (setq end (point-marker))
1020 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001021 (let ((py-indent-offset (prefix-numeric-value
1022 (or indent-offset py-indent-offset)))
1023 (indents '(-1)) ; stack of active indent levels
1024 (target-column 0) ; column to which to indent
1025 (base-shifted-by 0) ; amount last base line was shifted
1026 (indent-base (if (looking-at "[ \t\n]")
1027 (py-compute-indentation)
1028 0))
1029 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030 (while (< (point) end)
1031 (setq ci (current-indentation))
1032 ;; figure out appropriate target column
1033 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001034 ((or (eq (following-char) ?#) ; comment in column 1
1035 (looking-at "[ \t]*$")) ; entirely blank
1036 (setq target-column 0))
1037 ((py-continuation-line-p) ; shift relative to base line
1038 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001039 (t ; new base line
1040 (if (> ci (car indents)) ; going deeper; push it
1041 (setq indents (cons ci indents))
1042 ;; else we should have seen this indent before
1043 (setq indents (memq ci indents)) ; pop deeper indents
1044 (if (null indents)
1045 (error "Bad indentation in region, at line %d"
1046 (save-restriction
1047 (widen)
1048 (1+ (count-lines 1 (point)))))))
1049 (setq target-column (+ indent-base
1050 (* py-indent-offset
1051 (- (length indents) 2))))
1052 (setq base-shifted-by (- target-column ci))))
1053 ;; shift as needed
1054 (if (/= ci target-column)
1055 (progn
1056 (delete-horizontal-space)
1057 (indent-to target-column)))
1058 (forward-line 1))))
1059 (set-marker end nil))
1060
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001061
1062;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001063(defun py-previous-statement (count)
1064 "Go to the start of previous Python statement.
1065If the statement at point is the i'th Python statement, goes to the
1066start of statement i-COUNT. If there is no such statement, goes to the
1067first statement. Returns count of statements left to move.
1068`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (if (< count 0) (py-next-statement (- count))
1071 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001073 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001074 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075 (> count 0)
1076 (zerop (forward-line -1))
1077 (py-goto-statement-at-or-above))
1078 (setq count (1- count)))
1079 (if (> count 0) (goto-char start)))
1080 count))
1081
1082(defun py-next-statement (count)
1083 "Go to the start of next Python statement.
1084If the statement at point is the i'th Python statement, goes to the
1085start of statement i+COUNT. If there is no such statement, goes to the
1086last statement. Returns count of statements left to move. `Statements'
1087do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001088 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001089 (if (< count 0) (py-previous-statement (- count))
1090 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001091 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001093 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094 (> count 0)
1095 (py-goto-statement-below))
1096 (setq count (1- count)))
1097 (if (> count 0) (goto-char start)))
1098 count))
1099
1100(defun py-goto-block-up (&optional nomark)
1101 "Move up to start of current block.
1102Go to the statement that starts the smallest enclosing block; roughly
1103speaking, this will be the closest preceding statement that ends with a
1104colon and is indented less than the statement you started on. If
1105successful, also sets the mark to the starting point.
1106
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001107`\\[py-mark-block]' can be used afterward to mark the whole code
1108block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001109
1110If called from a program, the mark will not be set if optional argument
1111NOMARK is not nil."
1112 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001113 (let ((start (point))
1114 (found nil)
1115 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116 (py-goto-initial-line)
1117 ;; if on blank or non-indenting comment line, use the preceding stmt
1118 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1119 (progn
1120 (py-goto-statement-at-or-above)
1121 (setq found (py-statement-opens-block-p))))
1122 ;; search back for colon line indented less
1123 (setq initial-indent (current-indentation))
1124 (if (zerop initial-indent)
1125 ;; force fast exit
1126 (goto-char (point-min)))
1127 (while (not (or found (bobp)))
1128 (setq found
1129 (and
1130 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1131 (or (py-goto-initial-line) t) ; always true -- side effect
1132 (< (current-indentation) initial-indent)
1133 (py-statement-opens-block-p))))
1134 (if found
1135 (progn
1136 (or nomark (push-mark start))
1137 (back-to-indentation))
1138 (goto-char start)
1139 (error "Enclosing block not found"))))
1140
1141(defun beginning-of-python-def-or-class (&optional class)
1142 "Move point to start of def (or class, with prefix arg).
1143
1144Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001145arg, looks for a `class' instead. The docs assume the `def' case;
1146just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001147
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148If point is in a def statement already, and after the `d', simply
1149moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001151Else (point is not in a def statement, or at or before the `d' of a
1152def statement), searches for the closest preceding def statement, and
1153leaves point at its start. If no such statement can be found, leaves
1154point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001155
1156Returns t iff a def statement is found by these rules.
1157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001158Note that doing this command repeatedly will take you closer to the
1159start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001160
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161If you want to mark the current def/class, see
1162`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001163 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001164 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1165 (start-of-line (progn (beginning-of-line) (point)))
1166 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001167 (if (or (/= start-of-stmt start-of-line)
1168 (not at-or-before-p))
1169 (end-of-line)) ; OK to match on this line
1170 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001171 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001172
1173(defun end-of-python-def-or-class (&optional class)
1174 "Move point beyond end of def (or class, with prefix arg) body.
1175
1176By default, looks for an appropriate `def'. If you supply a prefix arg,
1177looks for a `class' instead. The docs assume the `def' case; just
1178substitute `class' for `def' for the other case.
1179
1180If point is in a def statement already, this is the def we use.
1181
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182Else if the def found by `\\[beginning-of-python-def-or-class]'
1183contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001184
1185Else we search forward for the closest following def, and use that.
1186
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001187If a def can be found by these rules, point is moved to the start of
1188the line immediately following the def block, and the position of the
1189start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
1191Else point is moved to the end of the buffer, and nil is returned.
1192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193Note that doing this command repeatedly will take you closer to the
1194end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001196If you want to mark the current def/class, see
1197`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001198 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199 (let ((start (progn (py-goto-initial-line) (point)))
1200 (which (if class "class" "def"))
1201 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001202 ;; move point to start of appropriate def/class
1203 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1204 (setq state 'at-beginning)
1205 ;; else see if beginning-of-python-def-or-class hits container
1206 (if (and (beginning-of-python-def-or-class class)
1207 (progn (py-goto-beyond-block)
1208 (> (point) start)))
1209 (setq state 'at-end)
1210 ;; else search forward
1211 (goto-char start)
1212 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1213 (progn (setq state 'at-beginning)
1214 (beginning-of-line)))))
1215 (cond
1216 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1217 ((eq state 'at-end) t)
1218 ((eq state 'not-found) nil)
1219 (t (error "internal error in end-of-python-def-or-class")))))
1220
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001221
1222;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001223(defun py-mark-block (&optional extend just-move)
1224 "Mark following block of lines. With prefix arg, mark structure.
1225Easier to use than explain. It sets the region to an `interesting'
1226block of succeeding lines. If point is on a blank line, it goes down to
1227the next non-blank line. That will be the start of the region. The end
1228of the region depends on the kind of line at the start:
1229
1230 - If a comment, the region will include all succeeding comment lines up
1231 to (but not including) the next non-comment line (if any).
1232
1233 - Else if a prefix arg is given, and the line begins one of these
1234 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001235
1236 if elif else try except finally for while def class
1237
Barry Warsaw7ae77681994-12-12 20:38:05 +00001238 the region will be set to the body of the structure, including
1239 following blocks that `belong' to it, but excluding trailing blank
1240 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001241 and all (if any) of the following `except' and `finally' blocks
1242 that belong to the `try' structure will be in the region. Ditto
1243 for if/elif/else, for/else and while/else structures, and (a bit
1244 degenerate, since they're always one-block structures) def and
1245 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001246
1247 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001248 block (see list above), and the block is not a `one-liner' (i.e.,
1249 the statement ends with a colon, not with code), the region will
1250 include all succeeding lines up to (but not including) the next
1251 code statement (if any) that's indented no more than the starting
1252 line, except that trailing blank and comment lines are excluded.
1253 E.g., if the starting line begins a multi-statement `def'
1254 structure, the region will be set to the full function definition,
1255 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001256
1257 - Else the region will include all succeeding lines up to (but not
1258 including) the next blank line, or code or indenting-comment line
1259 indented strictly less than the starting line. Trailing indenting
1260 comment lines are included in this case, but not trailing blank
1261 lines.
1262
1263A msg identifying the location of the mark is displayed in the echo
1264area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1265
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001266If called from a program, optional argument EXTEND plays the role of
1267the prefix arg, and if optional argument JUST-MOVE is not nil, just
1268moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001269 (interactive "P") ; raw prefix arg
1270 (py-goto-initial-line)
1271 ;; skip over blank lines
1272 (while (and
1273 (looking-at "[ \t]*$") ; while blank line
1274 (not (eobp))) ; & somewhere to go
1275 (forward-line 1))
1276 (if (eobp)
1277 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001278 (let ((initial-pos (point))
1279 (initial-indent (current-indentation))
1280 last-pos ; position of last stmt in region
1281 (followers
1282 '((if elif else) (elif elif else) (else)
1283 (try except finally) (except except) (finally)
1284 (for else) (while else)
1285 (def) (class) ) )
1286 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001287
1288 (cond
1289 ;; if comment line, suck up the following comment lines
1290 ((looking-at "[ \t]*#")
1291 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1292 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1293 (setq last-pos (point)))
1294
1295 ;; else if line is a block line and EXTEND given, suck up
1296 ;; the whole structure
1297 ((and extend
1298 (setq first-symbol (py-suck-up-first-keyword) )
1299 (assq first-symbol followers))
1300 (while (and
1301 (or (py-goto-beyond-block) t) ; side effect
1302 (forward-line -1) ; side effect
1303 (setq last-pos (point)) ; side effect
1304 (py-goto-statement-below)
1305 (= (current-indentation) initial-indent)
1306 (setq next-symbol (py-suck-up-first-keyword))
1307 (memq next-symbol (cdr (assq first-symbol followers))))
1308 (setq first-symbol next-symbol)))
1309
1310 ;; else if line *opens* a block, search for next stmt indented <=
1311 ((py-statement-opens-block-p)
1312 (while (and
1313 (setq last-pos (point)) ; always true -- side effect
1314 (py-goto-statement-below)
1315 (> (current-indentation) initial-indent))
1316 nil))
1317
1318 ;; else plain code line; stop at next blank line, or stmt or
1319 ;; indenting comment line indented <
1320 (t
1321 (while (and
1322 (setq last-pos (point)) ; always true -- side effect
1323 (or (py-goto-beyond-final-line) t)
1324 (not (looking-at "[ \t]*$")) ; stop at blank line
1325 (or
1326 (>= (current-indentation) initial-indent)
1327 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1328 nil)))
1329
1330 ;; skip to end of last stmt
1331 (goto-char last-pos)
1332 (py-goto-beyond-final-line)
1333
1334 ;; set mark & display
1335 (if just-move
1336 () ; just return
1337 (push-mark (point) 'no-msg)
1338 (forward-line -1)
1339 (message "Mark set after: %s" (py-suck-up-leading-text))
1340 (goto-char initial-pos))))
1341
1342(defun mark-python-def-or-class (&optional class)
1343 "Set region to body of def (or class, with prefix arg) enclosing point.
1344Pushes the current mark, then point, on the mark ring (all language
1345modes do this, but although it's handy it's never documented ...).
1346
1347In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1349`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001350
1351And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001352Turned out that was more confusing than useful: the `goto start' and
1353`goto end' commands are usually used to search through a file, and
1354people expect them to act a lot like `search backward' and `search
1355forward' string-search commands. But because Python `def' and `class'
1356can nest to arbitrary levels, finding the smallest def containing
1357point cannot be done via a simple backward search: the def containing
1358point may not be the closest preceding def, or even the closest
1359preceding def that's indented less. The fancy algorithm required is
1360appropriate for the usual uses of this `mark' command, but not for the
1361`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001362
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363So the def marked by this command may not be the one either of the
1364`goto' commands find: If point is on a blank or non-indenting comment
1365line, moves back to start of the closest preceding code statement or
1366indenting comment line. If this is a `def' statement, that's the def
1367we use. Else searches for the smallest enclosing `def' block and uses
1368that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001370When an enclosing def is found: The mark is left immediately beyond
1371the last line of the def block. Point is left at the start of the
1372def, except that: if the def is preceded by a number of comment lines
1373followed by (at most) one optional blank line, point is left at the
1374start of the comments; else if the def is preceded by a blank line,
1375point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376
1377The intent is to mark the containing def/class and its associated
1378documentation, to make moving and duplicating functions and classes
1379pleasant."
1380 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381 (let ((start (point))
1382 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001383 (push-mark start)
1384 (if (not (py-go-up-tree-to-keyword which))
1385 (progn (goto-char start)
1386 (error "Enclosing %s not found" which))
1387 ;; else enclosing def/class found
1388 (setq start (point))
1389 (py-goto-beyond-block)
1390 (push-mark (point))
1391 (goto-char start)
1392 (if (zerop (forward-line -1)) ; if there is a preceding line
1393 (progn
1394 (if (looking-at "[ \t]*$") ; it's blank
1395 (setq start (point)) ; so reset start point
1396 (goto-char start)) ; else try again
1397 (if (zerop (forward-line -1))
1398 (if (looking-at "[ \t]*#") ; a comment
1399 ;; look back for non-comment line
1400 ;; tricky: note that the regexp matches a blank
1401 ;; line, cuz \n is in the 2nd character class
1402 (and
1403 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1404 (forward-line 1))
1405 ;; no comment, so go back
1406 (goto-char start))))))))
1407
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001408
1409;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001410
1411;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001412;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1413;; out of the right places, along with the keys they're on & current
1414;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001415(defun py-dump-help-string (str)
1416 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001417 (let ((locals (buffer-local-variables))
1418 funckind funcname func funcdoc
1419 (start 0) mstart end
1420 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001421 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1422 (setq mstart (match-beginning 0) end (match-end 0)
1423 funckind (substring str (match-beginning 1) (match-end 1))
1424 funcname (substring str (match-beginning 2) (match-end 2))
1425 func (intern funcname))
1426 (princ (substitute-command-keys (substring str start mstart)))
1427 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001428 ((equal funckind "c") ; command
1429 (setq funcdoc (documentation func)
1430 keys (concat
1431 "Key(s): "
1432 (mapconcat 'key-description
1433 (where-is-internal func py-mode-map)
1434 ", "))))
1435 ((equal funckind "v") ; variable
1436 (setq funcdoc (substitute-command-keys
1437 (get func 'variable-documentation))
1438 keys (if (assq func locals)
1439 (concat
1440 "Local/Global values: "
1441 (prin1-to-string (symbol-value func))
1442 " / "
1443 (prin1-to-string (default-value func)))
1444 (concat
1445 "Value: "
1446 (prin1-to-string (symbol-value func))))))
1447 (t ; unexpected
1448 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449 (princ (format "\n-> %s:\t%s\t%s\n\n"
1450 (if (equal funckind "c") "Command" "Variable")
1451 funcname keys))
1452 (princ funcdoc)
1453 (terpri)
1454 (setq start end))
1455 (princ (substitute-command-keys (substring str start))))
1456 (print-help-return-message)))
1457
1458(defun py-describe-mode ()
1459 "Dump long form of Python-mode docs."
1460 (interactive)
1461 (py-dump-help-string "Major mode for editing Python files.
1462Knows about Python indentation, tokens, comments and continuation lines.
1463Paragraphs are separated by blank lines only.
1464
1465Major sections below begin with the string `@'; specific function and
1466variable docs begin with `->'.
1467
1468@EXECUTING PYTHON CODE
1469
1470\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1471\\[py-execute-region]\tsends the current region
1472\\[py-shell]\tstarts a Python interpreter window; this will be used by
1473\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1474%c:py-execute-buffer
1475%c:py-execute-region
1476%c:py-shell
1477
1478@VARIABLES
1479
1480py-indent-offset\tindentation increment
1481py-block-comment-prefix\tcomment string used by py-comment-region
1482
1483py-python-command\tshell command to invoke Python interpreter
1484py-scroll-process-buffer\talways scroll Python process buffer
1485py-temp-directory\tdirectory used for temp files (if needed)
1486
1487py-beep-if-tab-change\tring the bell if tab-width is changed
1488%v:py-indent-offset
1489%v:py-block-comment-prefix
1490%v:py-python-command
1491%v:py-scroll-process-buffer
1492%v:py-temp-directory
1493%v:py-beep-if-tab-change
1494
1495@KINDS OF LINES
1496
1497Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001498preceding line ends with a backslash that's not part of a comment, or
1499the paren/bracket/brace nesting level at the start of the line is
1500non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001501
1502An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503possibly blanks or tabs), a `comment line' (leftmost non-blank
1504character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001505
1506Comment Lines
1507
1508Although all comment lines are treated alike by Python, Python mode
1509recognizes two kinds that act differently with respect to indentation.
1510
1511An `indenting comment line' is a comment line with a blank, tab or
1512nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001513treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001514indenting comment line will be indented like the comment line. All
1515other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001516following the initial `#') are `non-indenting comment lines', and
1517their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001518
1519Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001520whenever possible. Non-indenting comment lines are useful in cases
1521like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001522
1523\ta = b # a very wordy single-line comment that ends up being
1524\t #... continued onto another line
1525
1526\tif a == b:
1527##\t\tprint 'panic!' # old code we've `commented out'
1528\t\treturn a
1529
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001530Since the `#...' and `##' comment lines have a non-whitespace
1531character following the initial `#', Python mode ignores them when
1532computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533
1534Continuation Lines and Statements
1535
1536The Python-mode commands generally work on statements instead of on
1537individual lines, where a `statement' is a comment or blank line, or a
1538code line and all of its following continuation lines (if any)
1539considered as a single logical unit. The commands in this mode
1540generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541statement containing point, even if point happens to be in the middle
1542of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001543
1544
1545@INDENTATION
1546
1547Primarily for entering new code:
1548\t\\[indent-for-tab-command]\t indent line appropriately
1549\t\\[py-newline-and-indent]\t insert newline, then indent
1550\t\\[py-delete-char]\t reduce indentation, or delete single character
1551
1552Primarily for reindenting existing code:
1553\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1554\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1555
1556\t\\[py-indent-region]\t reindent region to match its context
1557\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1558\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1559
1560Unlike most programming languages, Python uses indentation, and only
1561indentation, to specify block structure. Hence the indentation supplied
1562automatically by Python-mode is just an educated guess: only you know
1563the block structure you intend, so only you can supply correct
1564indentation.
1565
1566The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1567the indentation of preceding statements. E.g., assuming
1568py-indent-offset is 4, after you enter
1569\tif a > 0: \\[py-newline-and-indent]
1570the cursor will be moved to the position of the `_' (_ is not a
1571character in the file, it's just used here to indicate the location of
1572the cursor):
1573\tif a > 0:
1574\t _
1575If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1576to
1577\tif a > 0:
1578\t c = d
1579\t _
1580Python-mode cannot know whether that's what you intended, or whether
1581\tif a > 0:
1582\t c = d
1583\t_
1584was your intent. In general, Python-mode either reproduces the
1585indentation of the (closest code or indenting-comment) preceding
1586statement, or adds an extra py-indent-offset blanks if the preceding
1587statement has `:' as its last significant (non-whitespace and non-
1588comment) character. If the suggested indentation is too much, use
1589\\[py-delete-char] to reduce it.
1590
1591Continuation lines are given extra indentation. If you don't like the
1592suggested indentation, change it to something you do like, and Python-
1593mode will strive to indent later lines of the statement in the same way.
1594
1595If a line is a continuation line by virtue of being in an unclosed
1596paren/bracket/brace structure (`list', for short), the suggested
1597indentation depends on whether the current line contains the first item
1598in the list. If it does, it's indented py-indent-offset columns beyond
1599the indentation of the line containing the open bracket. If you don't
1600like that, change it by hand. The remaining items in the list will mimic
1601whatever indentation you give to the first item.
1602
1603If a line is a continuation line because the line preceding it ends with
1604a backslash, the third and following lines of the statement inherit their
1605indentation from the line preceding them. The indentation of the second
1606line in the statement depends on the form of the first (base) line: if
1607the base line is an assignment statement with anything more interesting
1608than the backslash following the leftmost assigning `=', the second line
1609is indented two columns beyond that `='. Else it's indented to two
1610columns beyond the leftmost solid chunk of non-whitespace characters on
1611the base line.
1612
1613Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1614repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1615structure you intend.
1616%c:indent-for-tab-command
1617%c:py-newline-and-indent
1618%c:py-delete-char
1619
1620
1621The next function may be handy when editing code you didn't write:
1622%c:py-guess-indent-offset
1623
1624
1625The remaining `indent' functions apply to a region of Python code. They
1626assume the block structure (equals indentation, in Python) of the region
1627is correct, and alter the indentation in various ways while preserving
1628the block structure:
1629%c:py-indent-region
1630%c:py-shift-region-left
1631%c:py-shift-region-right
1632
1633@MARKING & MANIPULATING REGIONS OF CODE
1634
1635\\[py-mark-block]\t mark block of lines
1636\\[mark-python-def-or-class]\t mark smallest enclosing def
1637\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1638\\[py-comment-region]\t comment out region of code
1639\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1640%c:py-mark-block
1641%c:mark-python-def-or-class
1642%c:py-comment-region
1643
1644@MOVING POINT
1645
1646\\[py-previous-statement]\t move to statement preceding point
1647\\[py-next-statement]\t move to statement following point
1648\\[py-goto-block-up]\t move up to start of current block
1649\\[beginning-of-python-def-or-class]\t move to start of def
1650\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1651\\[end-of-python-def-or-class]\t move to end of def
1652\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1653
1654The first two move to one statement beyond the statement that contains
1655point. A numeric prefix argument tells them to move that many
1656statements instead. Blank lines, comment lines, and continuation lines
1657do not count as `statements' for these commands. So, e.g., you can go
1658to the first code statement in a file by entering
1659\t\\[beginning-of-buffer]\t to move to the top of the file
1660\t\\[py-next-statement]\t to skip over initial comments and blank lines
1661Or do `\\[py-previous-statement]' with a huge prefix argument.
1662%c:py-previous-statement
1663%c:py-next-statement
1664%c:py-goto-block-up
1665%c:beginning-of-python-def-or-class
1666%c:end-of-python-def-or-class
1667
1668@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1669
1670`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1671
1672`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1673overall class and def structure of a module.
1674
1675`\\[back-to-indentation]' moves point to a line's first non-blank character.
1676
1677`\\[indent-relative]' is handy for creating odd indentation.
1678
1679@OTHER EMACS HINTS
1680
1681If you don't like the default value of a variable, change its value to
1682whatever you do like by putting a `setq' line in your .emacs file.
1683E.g., to set the indentation increment to 4, put this line in your
1684.emacs:
1685\t(setq py-indent-offset 4)
1686To see the value of a variable, do `\\[describe-variable]' and enter the variable
1687name at the prompt.
1688
1689When entering a key sequence like `C-c C-n', it is not necessary to
1690release the CONTROL key after doing the `C-c' part -- it suffices to
1691press the CONTROL key, press and release `c' (while still holding down
1692CONTROL), press and release `n' (while still holding down CONTROL), &
1693then release CONTROL.
1694
1695Entering Python mode calls with no arguments the value of the variable
1696`python-mode-hook', if that value exists and is not nil; for backward
1697compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1698the Elisp manual for details.
1699
1700Obscure: When python-mode is first loaded, it looks for all bindings
1701to newline-and-indent in the global keymap, and shadows them with
1702local bindings to py-newline-and-indent."))
1703
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001704
1705;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001706(defvar py-parse-state-re
1707 (concat
1708 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1709 "\\|"
1710 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001711
Barry Warsaw7ae77681994-12-12 20:38:05 +00001712;; returns the parse state at point (see parse-partial-sexp docs)
1713(defun py-parse-state ()
1714 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001715 (let ((here (point))
1716 pps done)
1717 (while (not done)
1718 ;; back up to the first preceding line (if any; else start of
1719 ;; buffer) that begins with a popular Python keyword, or a
1720 ;; non- whitespace and non-comment character. These are good
1721 ;; places to start parsing to see whether where we started is
1722 ;; at a non-zero nesting level. It may be slow for people who
1723 ;; write huge code blocks or huge lists ... tough beans.
1724 (re-search-backward py-parse-state-re nil 'move)
1725 (beginning-of-line)
1726 (save-excursion
1727 (setq pps (parse-partial-sexp (point) here)))
1728 ;; make sure we don't land inside a triple-quoted string
1729 (setq done (or (not (nth 3 pps)) (bobp))))
1730 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001731
1732;; if point is at a non-zero nesting level, returns the number of the
1733;; character that opens the smallest enclosing unclosed list; else
1734;; returns nil.
1735(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001736 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001737 (if (zerop (car status))
1738 nil ; not in a nest
1739 (car (cdr status))))) ; char# of open bracket
1740
1741;; t iff preceding line ends with backslash that's not in a comment
1742(defun py-backslash-continuation-line-p ()
1743 (save-excursion
1744 (beginning-of-line)
1745 (and
1746 ;; use a cheap test first to avoid the regexp if possible
1747 ;; use 'eq' because char-after may return nil
1748 (eq (char-after (- (point) 2)) ?\\ )
1749 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001750 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001751 (looking-at py-continued-re))))
1752
1753;; t iff current line is a continuation line
1754(defun py-continuation-line-p ()
1755 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757 (or (py-backslash-continuation-line-p)
1758 (py-nesting-level))))
1759
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001760;; go to initial line of current statement; usually this is the line
1761;; we're on, but if we're on the 2nd or following lines of a
1762;; continuation block, we need to go up to the first line of the
1763;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001765;; Tricky: We want to avoid quadratic-time behavior for long continued
1766;; blocks, whether of the backslash or open-bracket varieties, or a
1767;; mix of the two. The following manages to do that in the usual
1768;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001769(defun py-goto-initial-line ()
1770 (let ( open-bracket-pos )
1771 (while (py-continuation-line-p)
1772 (beginning-of-line)
1773 (if (py-backslash-continuation-line-p)
1774 (while (py-backslash-continuation-line-p)
1775 (forward-line -1))
1776 ;; else zip out of nested brackets/braces/parens
1777 (while (setq open-bracket-pos (py-nesting-level))
1778 (goto-char open-bracket-pos)))))
1779 (beginning-of-line))
1780
1781;; go to point right beyond final line of current statement; usually
1782;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001783;; statement we need to skip over the continuation lines. Tricky:
1784;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785(defun py-goto-beyond-final-line ()
1786 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001787 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001788 (while (and (py-continuation-line-p)
1789 (not (eobp)))
1790 ;; skip over the backslash flavor
1791 (while (and (py-backslash-continuation-line-p)
1792 (not (eobp)))
1793 (forward-line 1))
1794 ;; if in nest, zip to the end of the nest
1795 (setq state (py-parse-state))
1796 (if (and (not (zerop (car state)))
1797 (not (eobp)))
1798 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001799 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001800 ;; the 3rd argument should be plain 0
1801 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1802 nil state)
1803 (forward-line 1))))))
1804
1805;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001806;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001807(defun py-statement-opens-block-p ()
1808 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001809 (let ((start (point))
1810 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1811 (searching t)
1812 (answer nil)
1813 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001814 (goto-char start)
1815 (while searching
1816 ;; look for a colon with nothing after it except whitespace, and
1817 ;; maybe a comment
1818 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1819 finish t)
1820 (if (eq (point) finish) ; note: no `else' clause; just
1821 ; keep searching if we're not at
1822 ; the end yet
1823 ;; sure looks like it opens a block -- but it might
1824 ;; be in a comment
1825 (progn
1826 (setq searching nil) ; search is done either way
1827 (setq state (parse-partial-sexp start
1828 (match-beginning 0)))
1829 (setq answer (not (nth 4 state)))))
1830 ;; search failed: couldn't find another interesting colon
1831 (setq searching nil)))
1832 answer)))
1833
1834;; go to point right beyond final line of block begun by the current
1835;; line. This is the same as where py-goto-beyond-final-line goes
1836;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001838(defun py-goto-beyond-block ()
1839 (if (py-statement-opens-block-p)
1840 (py-mark-block nil 'just-move)
1841 (py-goto-beyond-final-line)))
1842
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843;; go to start of first statement (not blank or comment or
1844;; continuation line) at or preceding point. returns t if there is
1845;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846(defun py-goto-statement-at-or-above ()
1847 (py-goto-initial-line)
1848 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849 ;; skip back over blank & comment lines
1850 ;; note: will skip a blank or comment line that happens to be
1851 ;; a continuation line too
1852 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1853 (progn (py-goto-initial-line) t)
1854 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855 t))
1856
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857;; go to start of first statement (not blank or comment or
1858;; continuation line) following the statement containing point returns
1859;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860(defun py-goto-statement-below ()
1861 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 (py-goto-beyond-final-line)
1864 (while (and
1865 (looking-at py-blank-or-comment-re)
1866 (not (eobp)))
1867 (forward-line 1))
1868 (if (eobp)
1869 (progn (goto-char start) nil)
1870 t)))
1871
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872;; go to start of statement, at or preceding point, starting with
1873;; keyword KEY. Skips blank lines and non-indenting comments upward
1874;; first. If that statement starts with KEY, done, else go back to
1875;; first enclosing block starting with KEY. If successful, leaves
1876;; point at the start of the KEY line & returns t. Else leaves point
1877;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878(defun py-go-up-tree-to-keyword (key)
1879 ;; skip blanks and non-indenting #
1880 (py-goto-initial-line)
1881 (while (and
1882 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1883 (zerop (forward-line -1))) ; go back
1884 nil)
1885 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001886 (let* ((re (concat "[ \t]*" key "\\b"))
1887 (case-fold-search nil) ; let* so looking-at sees this
1888 (found (looking-at re))
1889 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001890 (while (not (or found dead))
1891 (condition-case nil ; in case no enclosing block
1892 (py-goto-block-up 'no-mark)
1893 (error (setq dead t)))
1894 (or dead (setq found (looking-at re))))
1895 (beginning-of-line)
1896 found))
1897
1898;; return string in buffer from start of indentation to end of line;
1899;; prefix "..." if leading whitespace was skipped
1900(defun py-suck-up-leading-text ()
1901 (save-excursion
1902 (back-to-indentation)
1903 (concat
1904 (if (bolp) "" "...")
1905 (buffer-substring (point) (progn (end-of-line) (point))))))
1906
1907;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1908;; as a Lisp symbol; return nil if none
1909(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001910 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001911 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1912 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1913 nil)))
1914
1915(defun py-make-temp-name ()
1916 (make-temp-name
1917 (concat (file-name-as-directory py-temp-directory) "python")))
1918
1919(defun py-delete-file-silently (fname)
1920 (condition-case nil
1921 (delete-file fname)
1922 (error nil)))
1923
1924(defun py-kill-emacs-hook ()
1925 ;; delete our temp files
1926 (while py-file-queue
1927 (py-delete-file-silently (car py-file-queue))
1928 (setq py-file-queue (cdr py-file-queue)))
1929 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1930 ;; run the hook we inherited, if any
1931 (and py-inherited-kill-emacs-hook
1932 (funcall py-inherited-kill-emacs-hook))))
1933
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001934;; make PROCESS's buffer visible, append STRING to it, and force
1935;; display; also make shell-mode believe the user typed this string,
1936;; so that kill-output-from-shell and show-output-from-shell work
1937;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001939 (let ((cbuf (current-buffer))
1940 (pbuf (process-buffer process))
1941 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001942 (set-buffer pbuf)
1943 (goto-char (point-max))
1944 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001945 (if (not (or py-this-is-emacs-19-p
1946 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001947 (move-marker last-input-start (point))) ; muck w/ shell-mode
1948 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001949 (if (not (or py-this-is-emacs-19-p
1950 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (move-marker last-input-end (point))) ; muck w/ shell-mode
1952 (set-buffer cbuf))
1953 (sit-for 0))
1954
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001955(defun py-keep-region-active ()
1956 ;; do whatever is necessary to keep the region active in XEmacs.
1957 ;; Ignore byte-compiler warnings you might see. Also note that
1958 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1959 ;; require us to take explicit action.
1960 (and (boundp 'zmacs-region-stays)
1961 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001962
1963
Barry Warsaw850437a1995-03-08 21:50:28 +00001964(defconst py-version "$Revision$"
1965 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001966(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001967 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968
Barry Warsaw850437a1995-03-08 21:50:28 +00001969(defun py-version ()
1970 "Echo the current version of `python-mode' in the minibuffer."
1971 (interactive)
1972 (message "Using `python-mode' version %s" py-version)
1973 (py-keep-region-active))
1974
1975;; only works under Emacs 19
1976;(eval-when-compile
1977; (require 'reporter))
1978
1979(defun py-submit-bug-report (enhancement-p)
1980 "Submit via mail a bug report on `python-mode'.
1981With \\[universal-argument] just submit an enhancement request."
1982 (interactive
1983 (list (not (y-or-n-p
1984 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001985 (let ((reporter-prompt-for-summary-p (if enhancement-p
1986 "(Very) brief summary: "
1987 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001988 (require 'reporter)
1989 (reporter-submit-bug-report
1990 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001991 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001992 ;; varlist
1993 (if enhancement-p nil
1994 '(py-python-command
1995 py-indent-offset
1996 py-block-comment-prefix
1997 py-scroll-process-buffer
1998 py-temp-directory
1999 py-beep-if-tab-change))
2000 nil ;pre-hooks
2001 nil ;post-hooks
2002 "Dear Barry,") ;salutation
2003 (if enhancement-p nil
2004 (set-mark (point))
2005 (insert
2006"Please replace this text with a sufficiently large code sample\n\
2007and an exact recipe so that I can reproduce your problem. Failure\n\
2008to do so may mean a greater delay in fixing your bug.\n\n")
2009 (exchange-point-and-mark)
2010 (py-keep-region-active))))
2011
2012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013;; arrange to kill temp files when Emacs exists
2014(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2015 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2016 ;; have to trust that other people are as respectful of our hook
2017 ;; fiddling as we are of theirs
2018 (if (boundp 'py-inherited-kill-emacs-hook)
2019 ;; we were loaded before -- trust others not to have screwed us
2020 ;; in the meantime (no choice, really)
2021 nil
2022 ;; else arrange for our hook to run theirs
2023 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2024 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2025
2026
2027
2028(provide 'python-mode)
2029;;; python-mode.el ends here