blob: 7f59c3198ee73b9f37a1fe89ed0410f17cb6c517 [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 Warsaw4669d7e1996-03-22 16:13:24 +000028;; mode works exceedingly well, and I've simply been tweeking it as I
29;; go along. Ain't it wonderful that Python has a much more sane
30;; syntax than C? (or <shudder> C++?! :-).
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
32;; The following statements, placed in your .emacs file or
33;; site-init.el, will cause this file to be autoloaded, and
34;; python-mode invoked, when visiting .py files (assuming this file is
35;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000037;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;; (setq auto-mode-alist
39;; (cons '("\\.py$" . python-mode) auto-mode-alist))
40
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000041;; Here's a brief list of recent additions/improvements:
42;;
43;; - Wrapping and indentation within triple quote strings should work
44;; properly now.
45;; - `Standard' bug reporting mechanism (use C-c C-b)
46;; - py-mark-block was moved to C-c C-m
47;; - C-c C-v shows you the python-mode version
48;; - a basic python-font-lock-keywords has been added for Emacs 19
49;; font-lock colorizations.
50;; - proper interaction with pending-del and del-sel modes.
51;; - New py-electric-colon (:) command for improved outdenting. Also
52;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +000053;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000054
Barry Warsaw7b0f5681995-03-08 21:33:04 +000055;; Here's a brief to do list:
56;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000057;; - Better integration with gud-mode for debugging.
58;; - Rewrite according to GNU Emacs Lisp standards.
59;; - py-delete-char should obey numeric arguments.
60;; - even better support for outdenting. Guido suggests outdents of
61;; at least one level after a return, raise, break, or continue
62;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000063;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; If you can think of more things you'd like to see, drop me a line.
66;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
67;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000068;; Note that I only test things on XEmacs. If you port stuff to FSF
69;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
70;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsaw7b0f5681995-03-08 21:33:04 +000072;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000073;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000074;; |Major mode for editing Python programs
75;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000076
Barry Warsaw7b0f5681995-03-08 21:33:04 +000077;;; Code:
78
79
80;; user definable variables
81;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000082
83(defvar py-python-command "python"
84 "*Shell command used to start Python interpreter.")
85
Barry Warsaw17914f41995-11-03 18:25:15 +000086(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000087 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000088Note that `\\[py-guess-indent-offset]' can usually guess a good value
89when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000090
Barry Warsaw095e9c61995-09-19 20:01:42 +000091(defvar py-align-multiline-strings-p t
92 "*Flag describing how multiline triple quoted strings are aligned.
93When this flag is non-nil, continuation lines are lined up under the
94preceding line's indentation. When this flag is nil, continuation
95lines are aligned to column zero.")
96
Barry Warsaw7ae77681994-12-12 20:38:05 +000097(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +000098 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000099This should follow the convention for non-indenting comment lines so
100that the indentation commands won't get confused (i.e., the string
101should be of the form `#x...' where `x' is not a blank or a tab, and
102`...' is arbitrary).")
103
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000104(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000105 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000106
Barry Warsaw6d627751996-03-06 18:41:38 +0000107When nil, all comment lines are skipped for indentation purposes, and
108in Emacs 19, a faster algorithm is used.
109
110When t, lines that begin with a single `#' are a hint to subsequent
111line indentation. If the previous line is such a comment line (as
112opposed to one that starts with `py-block-comment-prefix'), then it's
113indentation is used as a hint for this line's indentation. Lines that
114begin with `py-block-comment-prefix' are ignored for indentation
115purposes.
116
117When not nil or t, comment lines that begin with a `#' are used as
118indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000119
Barry Warsaw7ae77681994-12-12 20:38:05 +0000120(defvar py-scroll-process-buffer t
121 "*Scroll Python process buffer as output arrives.
122If nil, the Python process buffer acts, with respect to scrolling, like
123Shell-mode buffers normally act. This is surprisingly complicated and
124so won't be explained here; in fact, you can't get the whole story
125without studying the Emacs C code.
126
127If non-nil, the behavior is different in two respects (which are
128slightly inaccurate in the interest of brevity):
129
130 - If the buffer is in a window, and you left point at its end, the
131 window will scroll as new output arrives, and point will move to the
132 buffer's end, even if the window is not the selected window (that
133 being the one the cursor is in). The usual behavior for shell-mode
134 windows is not to scroll, and to leave point where it was, if the
135 buffer is in a window other than the selected window.
136
137 - If the buffer is not visible in any window, and you left point at
138 its end, the buffer will be popped into a window as soon as more
139 output arrives. This is handy if you have a long-running
140 computation and don't want to tie up screen area waiting for the
141 output. The usual behavior for a shell-mode buffer is to stay
142 invisible until you explicitly visit it.
143
144Note the `and if you left point at its end' clauses in both of the
145above: you can `turn off' the special behaviors while output is in
146progress, by visiting the Python buffer and moving point to anywhere
147besides the end. Then the buffer won't scroll, point will remain where
148you leave it, and if you hide the buffer it will stay hidden until you
149visit it again. You can enable and disable the special behaviors as
150often as you like, while output is in progress, by (respectively) moving
151point to, or away from, the end of the buffer.
152
153Warning: If you expect a large amount of output, you'll probably be
154happier setting this option to nil.
155
156Obscure: `End of buffer' above should really say `at or beyond the
157process mark', but if you know what that means you didn't need to be
158told <grin>.")
159
160(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000161 (let ((ok '(lambda (x)
162 (and x
163 (setq x (expand-file-name x)) ; always true
164 (file-directory-p x)
165 (file-writable-p x)
166 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000167 (or (funcall ok (getenv "TMPDIR"))
168 (funcall ok "/usr/tmp")
169 (funcall ok "/tmp")
170 (funcall ok ".")
171 (error
172 "Couldn't find a usable temp directory -- set py-temp-directory")))
173 "*Directory used for temp files created by a *Python* process.
174By default, the first directory from this list that exists and that you
175can write into: the value (if any) of the environment variable TMPDIR,
176/usr/tmp, /tmp, or the current directory.")
177
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000178(defvar py-beep-if-tab-change t
179 "*Ring the bell if tab-width is changed.
180If a comment of the form
181
182 \t# vi:set tabsize=<number>:
183
184is found before the first code line when the file is entered, and the
185current value of (the general Emacs variable) `tab-width' does not
186equal <number>, `tab-width' is set to <number>, a message saying so is
187displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
188the Emacs bell is also rung as a warning.")
189
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000190(defconst python-font-lock-keywords
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000191 (let* ((keywords '("access" "and" "break" "continue"
192 "del" "elif" "else:" "except"
193 "except:" "exec" "finally:" "for"
194 "from" "global" "if" "import"
195 "in" "is" "lambda" "not"
196 "or" "pass" "print" "raise"
197 "return" "try:" "while"
198 ))
199 (kwregex (mapconcat 'identity keywords "\\|")))
200 (list
201 ;; keywords not at beginning of line
202 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
203 ;; keywords at beginning of line. i don't think regexps are
204 ;; powerful enough to handle these two cases in one regexp.
205 ;; prove me wrong!
206 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
207 ;; classes
208 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
209 1 font-lock-type-face)
210 ;; functions
211 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
212 1 font-lock-function-name-face)
213 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000214 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000215
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000216
217;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
218;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
219
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000220(make-variable-buffer-local 'py-indent-offset)
221
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000222;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
223;; seems to be the standard way of checking this.
224;; BAW - This is *not* the right solution. When at all possible,
225;; instead of testing for the version of Emacs, use feature tests.
226
227(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
228(setq py-this-is-emacs-19-p
229 (and
230 (not py-this-is-lucid-emacs-p)
231 (string-match "^19\\." emacs-version)))
232
Barry Warsaw7ae77681994-12-12 20:38:05 +0000233;; have to bind py-file-queue before installing the kill-emacs hook
234(defvar py-file-queue nil
235 "Queue of Python temp files awaiting execution.
236Currently-active file is at the head of the list.")
237
238;; define a mode-specific abbrev table for those who use such things
239(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000240 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000241(define-abbrev-table 'python-mode-abbrev-table nil)
242
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243(defvar python-mode-hook nil
244 "*Hook called by `python-mode'.")
245
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000246;; in previous version of python-mode.el, the hook was incorrectly
247;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000248(and (fboundp 'make-obsolete-variable)
249 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
250
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000251(defvar py-mode-map ()
252 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253
Barry Warsaw7ae77681994-12-12 20:38:05 +0000254(if py-mode-map
255 ()
256 (setq py-mode-map (make-sparse-keymap))
257
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000258 ;; shadow global bindings for newline-and-indent w/ the py- version.
259 ;; BAW - this is extremely bad form, but I'm not going to change it
260 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261 (mapcar (function (lambda (key)
262 (define-key
263 py-mode-map key 'py-newline-and-indent)))
264 (where-is-internal 'newline-and-indent))
265
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000266 ;; BAW - you could do it this way, but its not considered proper
267 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000268 (mapcar (function
269 (lambda (x)
270 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000271 '((":" . py-electric-colon)
272 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000273 ("\C-c|" . py-execute-region)
274 ("\C-c!" . py-shell)
275 ("\177" . py-delete-char)
276 ("\n" . py-newline-and-indent)
277 ("\C-c:" . py-guess-indent-offset)
278 ("\C-c\t" . py-indent-region)
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000279 ("\C-c\C-l" . py-outdent-left)
280 ("\C-c\C-r" . py-indent-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000281 ("\C-c<" . py-shift-region-left)
282 ("\C-c>" . py-shift-region-right)
283 ("\C-c\C-n" . py-next-statement)
284 ("\C-c\C-p" . py-previous-statement)
285 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000286 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000287 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000288 ("\C-c?" . py-describe-mode)
289 ("\C-c\C-hm" . py-describe-mode)
290 ("\e\C-a" . beginning-of-python-def-or-class)
291 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000292 ( "\e\C-h" . mark-python-def-or-class)))
293 ;; should do all keybindings this way
294 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
295 (define-key py-mode-map "\C-c\C-v" 'py-version)
296 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000297
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298(defvar py-mode-syntax-table nil
299 "Syntax table used in `python-mode' buffers.")
300
Barry Warsaw7ae77681994-12-12 20:38:05 +0000301(if py-mode-syntax-table
302 ()
303 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000304 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000305 (mapcar (function
306 (lambda (x) (modify-syntax-entry
307 (car x) (cdr x) py-mode-syntax-table)))
308 '(( ?\( . "()" ) ( ?\) . ")(" )
309 ( ?\[ . "(]" ) ( ?\] . ")[" )
310 ( ?\{ . "(}" ) ( ?\} . "){" )
311 ;; fix operator symbols misassigned in the std table
312 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
313 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
314 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
315 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw2bbe49b1995-10-18 14:41:12 +0000316 ( ?\_ . "_" ) ; underscore is legit in symbols, but not words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000317 ( ?\' . "\"") ; single quote is string quote
318 ( ?\" . "\"" ) ; double quote is string quote too
319 ( ?\` . "$") ; backquote is open and close paren
320 ( ?\# . "<") ; hash starts comment
321 ( ?\n . ">")))) ; newline ends comment
322
323(defconst py-stringlit-re
324 (concat
325 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
326 "\\|" ; or
327 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000328 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000329
330;; this is tricky because a trailing backslash does not mean
331;; continuation if it's in a comment
332(defconst py-continued-re
333 (concat
334 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
335 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000336 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000337
338(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000339 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000340
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000341(defconst py-outdent-re
342 (concat "\\(" (mapconcat 'identity
343 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000344 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000345 "finally:"
346 "elif\\s +.*:")
347 "\\|")
348 "\\)")
349 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000350
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000351(defconst py-no-outdent-re
352 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000353 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000354 "except\\(\\s +.*\\)?:"
355 "while\\s +.*:"
356 "for\\s +.*:"
357 "if\\s +.*:"
358 "elif\\s +.*:")
359 "\\|")
360 "\\)")
361 "Regexp matching lines to not outdent after.")
362
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000363
364;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365(defun python-mode ()
366 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000367To submit a problem report, enter `\\[py-submit-bug-report]' from a
368`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
369documentation. To see what version of `python-mode' you are running,
370enter `\\[py-version]'.
371
372This mode knows about Python indentation, tokens, comments and
373continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000374
375COMMANDS
376\\{py-mode-map}
377VARIABLES
378
379py-indent-offset\tindentation increment
380py-block-comment-prefix\tcomment string used by py-comment-region
381py-python-command\tshell command to invoke Python interpreter
382py-scroll-process-buffer\talways scroll Python process buffer
383py-temp-directory\tdirectory used for temp files (if needed)
384py-beep-if-tab-change\tring the bell if tab-width is changed"
385 (interactive)
386 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000388 (setq major-mode 'python-mode
389 mode-name "Python"
390 local-abbrev-table python-mode-abbrev-table)
391 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000392 ;; Emacs 19 requires this
393 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
394 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000395 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000396 (mapcar (function (lambda (x)
397 (make-local-variable (car x))
398 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399 '((paragraph-separate . "^[ \t]*$")
400 (paragraph-start . "^[ \t]*$")
401 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000402 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000403 (comment-start-skip . "# *")
404 (comment-column . 40)
405 (indent-region-function . py-indent-region)
406 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000407 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000408 ;;
409 ;; not sure where the magic comment has to be; to save time
410 ;; searching for a rarity, we give up if it's not found prior to the
411 ;; first executable statement.
412 ;;
413 ;; BAW - on first glance, this seems like complete hackery. Why was
414 ;; this necessary, and is it still necessary?
415 (let ((case-fold-search nil)
416 (start (point))
417 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000418 (if (re-search-forward
419 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
420 (prog2 (py-next-statement 1) (point) (goto-char 1))
421 t)
422 (progn
423 (setq new-tab-width
424 (string-to-int
425 (buffer-substring (match-beginning 1) (match-end 1))))
426 (if (= tab-width new-tab-width)
427 nil
428 (setq tab-width new-tab-width)
429 (message "Caution: tab-width changed to %d" new-tab-width)
430 (if py-beep-if-tab-change (beep)))))
431 (goto-char start))
432
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000433 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000434 (if python-mode-hook
435 (run-hooks 'python-mode-hook)
436 (run-hooks 'py-mode-hook)))
437
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000438
Barry Warsaw826255b1996-03-22 16:09:34 +0000439(defun py-keep-region-active ()
440 ;; Do whatever is necessary to keep the region active in
441 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
442 ;; ignore byte-compiler warnings you might see.
443 (and (boundp 'zmacs-region-stays)
444 (setq zmacs-region-stays t)))
445
Barry Warsawb91b7431995-03-14 15:55:20 +0000446;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000447(defun py-outdent-p ()
448 ;; returns non-nil if the current line should outdent one level
449 (save-excursion
450 (and (progn (back-to-indentation)
451 (looking-at py-outdent-re))
452 (progn (backward-to-indentation 1)
453 (while (or (looking-at py-blank-or-comment-re)
454 (bobp))
455 (backward-to-indentation 1))
456 (not (looking-at py-no-outdent-re)))
457 )))
458
459
Barry Warsawb91b7431995-03-14 15:55:20 +0000460(defun py-electric-colon (arg)
461 "Insert a colon.
462In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000463argument is provided, that many colons are inserted non-electrically.
464Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000465 (interactive "P")
466 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000467 ;; are we in a string or comment?
468 (if (save-excursion
469 (let ((pps (parse-partial-sexp (save-excursion
470 (beginning-of-python-def-or-class)
471 (point))
472 (point))))
473 (not (or (nth 3 pps) (nth 4 pps)))))
474 (save-excursion
475 (let ((here (point))
476 (outdent 0)
477 (indent (py-compute-indentation)))
478 (if (and (not arg)
479 (py-outdent-p)
480 (= indent (save-excursion
481 (forward-line -1)
482 (py-compute-indentation)))
483 )
484 (setq outdent py-indent-offset))
485 ;; Don't indent, only outdent. This assumes that any lines that
486 ;; are already outdented relative to py-compute-indentation were
487 ;; put there on purpose. Its highly annoying to have `:' indent
488 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
489 ;; there a better way to determine this???
490 (if (< (current-indentation) indent) nil
491 (goto-char here)
492 (beginning-of-line)
493 (delete-horizontal-space)
494 (indent-to (- indent outdent))
495 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000496
Barry Warsaw826255b1996-03-22 16:09:34 +0000497(defun py-indent-right (start end arg)
498 "Indent lines in the region by one `py-indent-offset' level.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000499With numeric arg, indent by that many levels. You cannot indent
500farther right than the distance the line would be indented by
Barry Warsaw826255b1996-03-22 16:09:34 +0000501\\[py-indent-line]. With no active region, indent only the
502current line."
503 (interactive
504 (let ((p (point))
Barry Warsaw5f204771996-03-25 21:24:26 +0000505 (m (mark))
506 (arg (prefix-numeric-value current-prefix-arg)))
507 (if m
508 (list (min p m) (max p m) arg)
509 (list p m arg))))
Barry Warsaw826255b1996-03-22 16:09:34 +0000510 (let ((pos (- (point-max) (point)))
511 (end (save-excursion
512 (goto-char (or end (1+ start)))
513 (and (not (bolp))
514 (forward-line 1))
515 (set-marker (make-marker) (point))))
516 col want indent)
517 (goto-char start)
518 (beginning-of-line)
519 (unwind-protect
520 (while (< (point) end)
521 (setq col (current-indentation)
522 want (* arg py-indent-offset)
523 indent (py-compute-indentation))
524 (if (<= (+ col want) indent)
525 (progn
526 (beginning-of-line)
527 (delete-horizontal-space)
528 (indent-to (+ col want))))
529 (forward-line 1))
530 (set-marker end nil))
531 (goto-char (- (point-max) pos))
532 (py-keep-region-active)))
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000533
Barry Warsaw826255b1996-03-22 16:09:34 +0000534(defun py-outdent-left (start end arg)
535 "Outdent lines in the region by one `py-indent-offset' level.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000536With numeric arg, outdent by that many levels. You cannot outdent
Barry Warsaw826255b1996-03-22 16:09:34 +0000537farther left than column zero. With no active region, outdent only
538the current line."
539 (interactive
540 (let ((p (point))
Barry Warsaw5f204771996-03-25 21:24:26 +0000541 (m (mark))
542 (arg (prefix-numeric-value current-prefix-arg)))
543 (if m
544 (list (min p m) (max p m) arg)
545 (list p m arg))))
Barry Warsaw826255b1996-03-22 16:09:34 +0000546 (let ((pos (- (point-max) (point)))
547 (end (save-excursion
548 (goto-char (or end (1+ start)))
549 (and (not (bolp))
550 (forward-line 1))
551 (set-marker (make-marker) (point))))
552 col want)
553 (goto-char start)
554 (beginning-of-line)
555 (unwind-protect
556 (while (< (point) end)
557 (setq col (current-indentation)
558 want (* arg py-indent-offset))
559 (if (<= 0 (- col want))
560 (progn
561 (beginning-of-line)
562 (delete-horizontal-space)
563 (indent-to (- col want))))
564 (forward-line 1))
565 (set-marker end nil))
566 (goto-char (- (point-max) pos))
567 (py-keep-region-active)))
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000568
Barry Warsawb91b7431995-03-14 15:55:20 +0000569
Barry Warsaw7ae77681994-12-12 20:38:05 +0000570;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000571(defun py-shell ()
572 "Start an interactive Python interpreter in another window.
573This is like Shell mode, except that Python is running in the window
574instead of a shell. See the `Interactive Shell' and `Shell Mode'
575sections of the Emacs manual for details, especially for the key
576bindings active in the `*Python*' buffer.
577
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000578See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000579behavior in the process window.
580
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000581Warning: Don't use an interactive Python if you change sys.ps1 or
582sys.ps2 from their default values, or if you're running code that
583prints `>>> ' or `... ' at the start of a line. `python-mode' can't
584distinguish your output from Python's output, and assumes that `>>> '
585at the start of a line is a prompt from Python. Similarly, the Emacs
586Shell mode code assumes that both `>>> ' and `... ' at the start of a
587line are Python prompts. Bad things can happen if you fool either
588mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000589
590Warning: If you do any editing *in* the process buffer *while* the
591buffer is accepting output from Python, do NOT attempt to `undo' the
592changes. Some of the output (nowhere near the parts you changed!) may
593be lost if you do. This appears to be an Emacs bug, an unfortunate
594interaction between undo and process filters; the same problem exists in
595non-Python process buffers using the default (Emacs-supplied) process
596filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000597 ;; BAW - should undo be disabled in the python process buffer, if
598 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000599 (interactive)
600 (if py-this-is-emacs-19-p
601 (progn
602 (require 'comint)
603 (switch-to-buffer-other-window
604 (make-comint "Python" py-python-command)))
605 (progn
606 (require 'shell)
607 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000608 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000609 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000610 (make-local-variable 'shell-prompt-pattern)
611 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
612 (set-process-filter (get-buffer-process (current-buffer))
613 'py-process-filter)
614 (set-syntax-table py-mode-syntax-table))
615
616(defun py-execute-region (start end)
617 "Send the region between START and END to a Python interpreter.
618If there is a *Python* process it is used.
619
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000620Hint: If you want to execute part of a Python file several times
621\(e.g., perhaps you're developing a function and want to flesh it out
622a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
623the region of interest, and send the code to a *Python* process via
624`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000625
626Following are subtleties to note when using a *Python* process:
627
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000628If a *Python* process is used, the region is copied into a temporary
629file (in directory `py-temp-directory'), and an `execfile' command is
630sent to Python naming that file. If you send regions faster than
631Python can execute them, `python-mode' will save them into distinct
632temp files, and execute the next one in the queue the next time it
633sees a `>>> ' prompt from Python. Each time this happens, the process
634buffer is popped into a window (if it's not already in some window) so
635you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000636
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000637 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000638
639is inserted at the end.
640
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000641Caution: No more than 26 regions can be pending at any given time.
642This limit is (indirectly) inherited from libc's mktemp(3).
643`python-mode' does not try to protect you from exceeding the limit.
644It's extremely unlikely that you'll get anywhere close to the limit in
645practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000646
647See the `\\[py-shell]' docs for additional warnings."
648 (interactive "r")
649 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000650 (let ((pyproc (get-process "Python"))
651 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000652 (if (null pyproc)
653 (shell-command-on-region start end py-python-command)
654 ;; else feed it thru a temp file
655 (setq fname (py-make-temp-name))
656 (write-region start end fname nil 'no-msg)
657 (setq py-file-queue (append py-file-queue (list fname)))
658 (if (cdr py-file-queue)
659 (message "File %s queued for execution" fname)
660 ;; else
661 (py-execute-file pyproc fname)))))
662
663(defun py-execute-file (pyproc fname)
664 (py-append-to-process-buffer
665 pyproc
666 (format "## working on region in file %s ...\n" fname))
667 (process-send-string pyproc (format "execfile('%s')\n" fname)))
668
669(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000670 (let ((curbuf (current-buffer))
671 (pbuf (process-buffer pyproc))
672 (pmark (process-mark pyproc))
673 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000674
675 ;; make sure we switch to a different buffer at least once. if we
676 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000677 ;; window, and point is before the end, and lots of output is
678 ;; coming at a fast pace, then (a) simple cursor-movement commands
679 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
680 ;; to have a visible effect (the window just doesn't get updated,
681 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
682 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000683 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000684 ;; #b makes no sense to me at all. #a almost makes sense: unless
685 ;; we actually change buffers, set_buffer_internal in buffer.c
686 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
687 ;; seems to make the Emacs command loop reluctant to update the
688 ;; display. Perhaps the default process filter in process.c's
689 ;; read_process_output has update_mode_lines++ for a similar
690 ;; reason? beats me ...
691
692 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000693 (if (eq curbuf pbuf) ; mysterious ugly hack
694 (set-buffer (get-buffer-create "*scratch*")))
695
696 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000697 (let* ((start (point))
698 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000699 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000700 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000701 (goto-char pmark)
702 (insert string)
703 (move-marker pmark (point))
704 (setq file-finished
705 (and py-file-queue
706 (equal ">>> "
707 (buffer-substring
708 (prog2 (beginning-of-line) (point)
709 (goto-char pmark))
710 (point)))))
711 (if goback (goto-char start)
712 ;; else
713 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000714 (let* ((pop-up-windows t)
715 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000716 (set-window-point pwin (point)))))
717 (set-buffer curbuf)
718 (if file-finished
719 (progn
720 (py-delete-file-silently (car py-file-queue))
721 (setq py-file-queue (cdr py-file-queue))
722 (if py-file-queue
723 (py-execute-file pyproc (car py-file-queue)))))
724 (and goend
725 (progn (set-buffer pbuf)
726 (goto-char (point-max))))
727 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000728
729(defun py-execute-buffer ()
730 "Send the contents of the buffer to a Python interpreter.
731If there is a *Python* process buffer it is used. If a clipping
732restriction is in effect, only the accessible portion of the buffer is
733sent. A trailing newline will be supplied if needed.
734
735See the `\\[py-execute-region]' docs for an account of some subtleties."
736 (interactive)
737 (py-execute-region (point-min) (point-max)))
738
739
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000740
741;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000742(defun py-delete-char ()
743 "Reduce indentation or delete character.
744If point is at the leftmost column, deletes the preceding newline.
745
746Else if point is at the leftmost non-blank character of a line that is
747neither a continuation line nor a non-indenting comment line, or if
748point is at the end of a blank line, reduces the indentation to match
749that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000750opened the block is displayed in the echo area to help you keep track
751of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000752
753Else the preceding character is deleted, converting a tab to spaces if
754needed so that only a single column position is deleted."
755 (interactive "*")
756 (if (or (/= (current-indentation) (current-column))
757 (bolp)
758 (py-continuation-line-p)
759 (looking-at "#[^ \t\n]")) ; non-indenting #
760 (backward-delete-char-untabify 1)
761 ;; else indent the same as the colon line that opened the block
762
763 ;; force non-blank so py-goto-block-up doesn't ignore it
764 (insert-char ?* 1)
765 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000766 (let ((base-indent 0) ; indentation of base line
767 (base-text "") ; and text of base line
768 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000769 (condition-case nil ; in case no enclosing block
770 (save-excursion
771 (py-goto-block-up 'no-mark)
772 (setq base-indent (current-indentation)
773 base-text (py-suck-up-leading-text)
774 base-found-p t))
775 (error nil))
776 (delete-char 1) ; toss the dummy character
777 (delete-horizontal-space)
778 (indent-to base-indent)
779 (if base-found-p
780 (message "Closes block: %s" base-text)))))
781
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000782;; required for pending-del and delsel modes
783(put 'py-delete-char 'delete-selection 'supersede)
784(put 'py-delete-char 'pending-delete 'supersede)
785
Barry Warsaw7ae77681994-12-12 20:38:05 +0000786(defun py-indent-line ()
787 "Fix the indentation of the current line according to Python rules."
788 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000789 (let* ((ci (current-indentation))
790 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000791 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000792 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000793 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000794 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000795 (if (/= ci need)
796 (save-excursion
797 (beginning-of-line)
798 (delete-horizontal-space)
799 (indent-to need)))
800 (if move-to-indentation-p (back-to-indentation))))
801
802(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000803 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000804This is just `strives to' because correct indentation can't be computed
805from scratch for Python code. In general, deletes the whitespace before
806point, inserts a newline, and takes an educated guess as to how you want
807the new line indented."
808 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000809 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000810 (if (< ci (current-column)) ; if point beyond indentation
811 (newline-and-indent)
812 ;; else try to act like newline-and-indent "normally" acts
813 (beginning-of-line)
814 (insert-char ?\n 1)
815 (move-to-column ci))))
816
817(defun py-compute-indentation ()
818 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000819 (let ((pps (parse-partial-sexp (save-excursion
820 (beginning-of-python-def-or-class)
821 (point))
822 (point))))
823 (beginning-of-line)
824 (cond
825 ;; are we inside a string or comment?
826 ((or (nth 3 pps) (nth 4 pps))
827 (save-excursion
828 (if (not py-align-multiline-strings-p) 0
829 ;; skip back over blank & non-indenting comment lines
830 ;; note: will skip a blank or non-indenting comment line
831 ;; that happens to be a continuation line too
832 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
833 (back-to-indentation)
834 (current-column))))
835 ;; are we on a continuation line?
836 ((py-continuation-line-p)
837 (let ((startpos (point))
838 (open-bracket-pos (py-nesting-level))
839 endpos searching found)
840 (if open-bracket-pos
841 (progn
842 ;; align with first item in list; else a normal
843 ;; indent beyond the line with the open bracket
844 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
845 ;; is the first list item on the same line?
846 (skip-chars-forward " \t")
847 (if (null (memq (following-char) '(?\n ?# ?\\)))
848 ; yes, so line up with it
849 (current-column)
850 ;; first list item on another line, or doesn't exist yet
851 (forward-line 1)
852 (while (and (< (point) startpos)
853 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
854 (forward-line 1))
855 (if (< (point) startpos)
856 ;; again mimic the first list item
857 (current-indentation)
858 ;; else they're about to enter the first item
859 (goto-char open-bracket-pos)
860 (+ (current-indentation) py-indent-offset))))
861
862 ;; else on backslash continuation line
863 (forward-line -1)
864 (if (py-continuation-line-p) ; on at least 3rd line in block
865 (current-indentation) ; so just continue the pattern
866 ;; else started on 2nd line in block, so indent more.
867 ;; if base line is an assignment with a start on a RHS,
868 ;; indent to 2 beyond the leftmost "="; else skip first
869 ;; chunk of non-whitespace characters on base line, + 1 more
870 ;; column
871 (end-of-line)
872 (setq endpos (point) searching t)
873 (back-to-indentation)
874 (setq startpos (point))
875 ;; look at all "=" from left to right, stopping at first
876 ;; one not nested in a list or string
877 (while searching
878 (skip-chars-forward "^=" endpos)
879 (if (= (point) endpos)
880 (setq searching nil)
881 (forward-char 1)
882 (setq state (parse-partial-sexp startpos (point)))
883 (if (and (zerop (car state)) ; not in a bracket
884 (null (nth 3 state))) ; & not in a string
885 (progn
886 (setq searching nil) ; done searching in any case
887 (setq found
888 (not (or
889 (eq (following-char) ?=)
890 (memq (char-after (- (point) 2))
891 '(?< ?> ?!)))))))))
892 (if (or (not found) ; not an assignment
893 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
894 (progn
895 (goto-char startpos)
896 (skip-chars-forward "^ \t\n")))
897 (1+ (current-column))))))
898
899 ;; not on a continuation line
900
901 ;; if at start of restriction, or on a non-indenting comment
902 ;; line, assume they intended whatever's there
903 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
904 (current-indentation))
905
906 ;; else indentation based on that of the statement that
907 ;; precedes us; use the first line of that statement to
908 ;; establish the base, in case the user forced a non-std
909 ;; indentation for the continuation lines (if any)
910 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000911 ;; skip back over blank & non-indenting comment lines note:
912 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000913 ;; happens to be a continuation line too. use fast Emacs 19
914 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000915 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000916 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000917 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000918 (let (done)
919 (while (not done)
920 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
921 nil 'move)
922 (setq done (or (eq py-honor-comment-indentation t)
923 (bobp)
924 (/= (following-char) ?#)
925 (not (zerop (current-column)))))
926 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000927 ;; if we landed inside a string, go to the beginning of that
928 ;; string. this handles triple quoted, multi-line spanning
929 ;; strings.
930 (py-goto-initial-line)
931 (if (py-statement-opens-block-p)
932 (+ (current-indentation) py-indent-offset)
933 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000934
935(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000936 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000937By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000938`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000939Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000940`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000941their own buffer-local copy), both those currently existing and those
942created later in the Emacs session.
943
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000944Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000945There's no excuse for such foolishness, but sometimes you have to deal
946with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000947`py-indent-offset' to what it thinks it was when they created the
948mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000949
950Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000951looking for a line that opens a block of code. `py-indent-offset' is
952set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000953statement following it. If the search doesn't succeed going forward,
954it's tried again going backward."
955 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000956 (let (new-value
957 (start (point))
958 restart
959 (found nil)
960 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000961 (py-goto-initial-line)
962 (while (not (or found (eobp)))
963 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
964 (progn
965 (setq restart (point))
966 (py-goto-initial-line)
967 (if (py-statement-opens-block-p)
968 (setq found t)
969 (goto-char restart)))))
970 (if found
971 ()
972 (goto-char start)
973 (py-goto-initial-line)
974 (while (not (or found (bobp)))
975 (setq found
976 (and
977 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
978 (or (py-goto-initial-line) t) ; always true -- side effect
979 (py-statement-opens-block-p)))))
980 (setq colon-indent (current-indentation)
981 found (and found (zerop (py-next-statement 1)))
982 new-value (- (current-indentation) colon-indent))
983 (goto-char start)
984 (if found
985 (progn
986 (funcall (if global 'kill-local-variable 'make-local-variable)
987 'py-indent-offset)
988 (setq py-indent-offset new-value)
989 (message "%s value of py-indent-offset set to %d"
990 (if global "Global" "Local")
991 py-indent-offset))
992 (error "Sorry, couldn't guess a value for py-indent-offset"))))
993
994(defun py-shift-region (start end count)
995 (save-excursion
996 (goto-char end) (beginning-of-line) (setq end (point))
997 (goto-char start) (beginning-of-line) (setq start (point))
998 (indent-rigidly start end count)))
999
1000(defun py-shift-region-left (start end &optional count)
1001 "Shift region of Python code to the left.
1002The lines from the line containing the start of the current region up
1003to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005
1006If a prefix argument is given, the region is instead shifted by that
1007many columns."
1008 (interactive "*r\nP") ; region; raw prefix arg
1009 (py-shift-region start end
1010 (- (prefix-numeric-value
1011 (or count py-indent-offset)))))
1012
1013(defun py-shift-region-right (start end &optional count)
1014 "Shift region of Python code to the right.
1015The lines from the line containing the start of the current region up
1016to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018
1019If a prefix argument is given, the region is instead shifted by that
1020many columns."
1021 (interactive "*r\nP") ; region; raw prefix arg
1022 (py-shift-region start end (prefix-numeric-value
1023 (or count py-indent-offset))))
1024
1025(defun py-indent-region (start end &optional indent-offset)
1026 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001027
Barry Warsaw7ae77681994-12-12 20:38:05 +00001028The lines from the line containing the start of the current region up
1029to (but not including) the line containing the end of the region are
1030reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001031character in the first column, the first line is left alone and the
1032rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001033region is reindented with respect to the (closest code or indenting
1034comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001035
1036This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001037control structures are introduced or removed, or to reformat code
1038using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001039
1040If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001041the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001042used.
1043
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001044Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001045is called! This function does not compute proper indentation from
1046scratch (that's impossible in Python), it merely adjusts the existing
1047indentation to be correct in context.
1048
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001049Warning: This function really has no idea what to do with
1050non-indenting comment lines, and shifts them as if they were indenting
1051comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001053Special cases: whitespace is deleted from blank lines; continuation
1054lines are shifted by the same amount their initial line was shifted,
1055in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001056initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001057 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001058 (save-excursion
1059 (goto-char end) (beginning-of-line) (setq end (point-marker))
1060 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001061 (let ((py-indent-offset (prefix-numeric-value
1062 (or indent-offset py-indent-offset)))
1063 (indents '(-1)) ; stack of active indent levels
1064 (target-column 0) ; column to which to indent
1065 (base-shifted-by 0) ; amount last base line was shifted
1066 (indent-base (if (looking-at "[ \t\n]")
1067 (py-compute-indentation)
1068 0))
1069 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (while (< (point) end)
1071 (setq ci (current-indentation))
1072 ;; figure out appropriate target column
1073 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001074 ((or (eq (following-char) ?#) ; comment in column 1
1075 (looking-at "[ \t]*$")) ; entirely blank
1076 (setq target-column 0))
1077 ((py-continuation-line-p) ; shift relative to base line
1078 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001079 (t ; new base line
1080 (if (> ci (car indents)) ; going deeper; push it
1081 (setq indents (cons ci indents))
1082 ;; else we should have seen this indent before
1083 (setq indents (memq ci indents)) ; pop deeper indents
1084 (if (null indents)
1085 (error "Bad indentation in region, at line %d"
1086 (save-restriction
1087 (widen)
1088 (1+ (count-lines 1 (point)))))))
1089 (setq target-column (+ indent-base
1090 (* py-indent-offset
1091 (- (length indents) 2))))
1092 (setq base-shifted-by (- target-column ci))))
1093 ;; shift as needed
1094 (if (/= ci target-column)
1095 (progn
1096 (delete-horizontal-space)
1097 (indent-to target-column)))
1098 (forward-line 1))))
1099 (set-marker end nil))
1100
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001101
1102;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001103(defun py-previous-statement (count)
1104 "Go to the start of previous Python statement.
1105If the statement at point is the i'th Python statement, goes to the
1106start of statement i-COUNT. If there is no such statement, goes to the
1107first statement. Returns count of statements left to move.
1108`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001109 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001110 (if (< count 0) (py-next-statement (- count))
1111 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001112 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001113 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001114 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115 (> count 0)
1116 (zerop (forward-line -1))
1117 (py-goto-statement-at-or-above))
1118 (setq count (1- count)))
1119 (if (> count 0) (goto-char start)))
1120 count))
1121
1122(defun py-next-statement (count)
1123 "Go to the start of next Python statement.
1124If the statement at point is the i'th Python statement, goes to the
1125start of statement i+COUNT. If there is no such statement, goes to the
1126last statement. Returns count of statements left to move. `Statements'
1127do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001128 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001129 (if (< count 0) (py-previous-statement (- count))
1130 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001131 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001132 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001133 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134 (> count 0)
1135 (py-goto-statement-below))
1136 (setq count (1- count)))
1137 (if (> count 0) (goto-char start)))
1138 count))
1139
1140(defun py-goto-block-up (&optional nomark)
1141 "Move up to start of current block.
1142Go to the statement that starts the smallest enclosing block; roughly
1143speaking, this will be the closest preceding statement that ends with a
1144colon and is indented less than the statement you started on. If
1145successful, also sets the mark to the starting point.
1146
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001147`\\[py-mark-block]' can be used afterward to mark the whole code
1148block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001149
1150If called from a program, the mark will not be set if optional argument
1151NOMARK is not nil."
1152 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001153 (let ((start (point))
1154 (found nil)
1155 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001156 (py-goto-initial-line)
1157 ;; if on blank or non-indenting comment line, use the preceding stmt
1158 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1159 (progn
1160 (py-goto-statement-at-or-above)
1161 (setq found (py-statement-opens-block-p))))
1162 ;; search back for colon line indented less
1163 (setq initial-indent (current-indentation))
1164 (if (zerop initial-indent)
1165 ;; force fast exit
1166 (goto-char (point-min)))
1167 (while (not (or found (bobp)))
1168 (setq found
1169 (and
1170 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1171 (or (py-goto-initial-line) t) ; always true -- side effect
1172 (< (current-indentation) initial-indent)
1173 (py-statement-opens-block-p))))
1174 (if found
1175 (progn
1176 (or nomark (push-mark start))
1177 (back-to-indentation))
1178 (goto-char start)
1179 (error "Enclosing block not found"))))
1180
1181(defun beginning-of-python-def-or-class (&optional class)
1182 "Move point to start of def (or class, with prefix arg).
1183
1184Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001185arg, looks for a `class' instead. The docs assume the `def' case;
1186just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001187
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001188If point is in a def statement already, and after the `d', simply
1189moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001191Else (point is not in a def statement, or at or before the `d' of a
1192def statement), searches for the closest preceding def statement, and
1193leaves point at its start. If no such statement can be found, leaves
1194point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195
1196Returns t iff a def statement is found by these rules.
1197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198Note that doing this command repeatedly will take you closer to the
1199start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001200
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001201If you want to mark the current def/class, see
1202`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001203 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001204 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1205 (start-of-line (progn (beginning-of-line) (point)))
1206 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001207 (if (or (/= start-of-stmt start-of-line)
1208 (not at-or-before-p))
1209 (end-of-line)) ; OK to match on this line
1210 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001211 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001212
1213(defun end-of-python-def-or-class (&optional class)
1214 "Move point beyond end of def (or class, with prefix arg) body.
1215
1216By default, looks for an appropriate `def'. If you supply a prefix arg,
1217looks for a `class' instead. The docs assume the `def' case; just
1218substitute `class' for `def' for the other case.
1219
1220If point is in a def statement already, this is the def we use.
1221
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001222Else if the def found by `\\[beginning-of-python-def-or-class]'
1223contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001224
1225Else we search forward for the closest following def, and use that.
1226
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001227If a def can be found by these rules, point is moved to the start of
1228the line immediately following the def block, and the position of the
1229start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001230
1231Else point is moved to the end of the buffer, and nil is returned.
1232
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001233Note that doing this command repeatedly will take you closer to the
1234end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001235
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001236If you want to mark the current def/class, see
1237`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001238 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001239 (let ((start (progn (py-goto-initial-line) (point)))
1240 (which (if class "class" "def"))
1241 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001242 ;; move point to start of appropriate def/class
1243 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1244 (setq state 'at-beginning)
1245 ;; else see if beginning-of-python-def-or-class hits container
1246 (if (and (beginning-of-python-def-or-class class)
1247 (progn (py-goto-beyond-block)
1248 (> (point) start)))
1249 (setq state 'at-end)
1250 ;; else search forward
1251 (goto-char start)
1252 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1253 (progn (setq state 'at-beginning)
1254 (beginning-of-line)))))
1255 (cond
1256 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1257 ((eq state 'at-end) t)
1258 ((eq state 'not-found) nil)
1259 (t (error "internal error in end-of-python-def-or-class")))))
1260
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001261
1262;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001263(defun py-mark-block (&optional extend just-move)
1264 "Mark following block of lines. With prefix arg, mark structure.
1265Easier to use than explain. It sets the region to an `interesting'
1266block of succeeding lines. If point is on a blank line, it goes down to
1267the next non-blank line. That will be the start of the region. The end
1268of the region depends on the kind of line at the start:
1269
1270 - If a comment, the region will include all succeeding comment lines up
1271 to (but not including) the next non-comment line (if any).
1272
1273 - Else if a prefix arg is given, and the line begins one of these
1274 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001275
1276 if elif else try except finally for while def class
1277
Barry Warsaw7ae77681994-12-12 20:38:05 +00001278 the region will be set to the body of the structure, including
1279 following blocks that `belong' to it, but excluding trailing blank
1280 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281 and all (if any) of the following `except' and `finally' blocks
1282 that belong to the `try' structure will be in the region. Ditto
1283 for if/elif/else, for/else and while/else structures, and (a bit
1284 degenerate, since they're always one-block structures) def and
1285 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001286
1287 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001288 block (see list above), and the block is not a `one-liner' (i.e.,
1289 the statement ends with a colon, not with code), the region will
1290 include all succeeding lines up to (but not including) the next
1291 code statement (if any) that's indented no more than the starting
1292 line, except that trailing blank and comment lines are excluded.
1293 E.g., if the starting line begins a multi-statement `def'
1294 structure, the region will be set to the full function definition,
1295 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296
1297 - Else the region will include all succeeding lines up to (but not
1298 including) the next blank line, or code or indenting-comment line
1299 indented strictly less than the starting line. Trailing indenting
1300 comment lines are included in this case, but not trailing blank
1301 lines.
1302
1303A msg identifying the location of the mark is displayed in the echo
1304area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1305
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001306If called from a program, optional argument EXTEND plays the role of
1307the prefix arg, and if optional argument JUST-MOVE is not nil, just
1308moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001309 (interactive "P") ; raw prefix arg
1310 (py-goto-initial-line)
1311 ;; skip over blank lines
1312 (while (and
1313 (looking-at "[ \t]*$") ; while blank line
1314 (not (eobp))) ; & somewhere to go
1315 (forward-line 1))
1316 (if (eobp)
1317 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001318 (let ((initial-pos (point))
1319 (initial-indent (current-indentation))
1320 last-pos ; position of last stmt in region
1321 (followers
1322 '((if elif else) (elif elif else) (else)
1323 (try except finally) (except except) (finally)
1324 (for else) (while else)
1325 (def) (class) ) )
1326 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001327
1328 (cond
1329 ;; if comment line, suck up the following comment lines
1330 ((looking-at "[ \t]*#")
1331 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1332 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1333 (setq last-pos (point)))
1334
1335 ;; else if line is a block line and EXTEND given, suck up
1336 ;; the whole structure
1337 ((and extend
1338 (setq first-symbol (py-suck-up-first-keyword) )
1339 (assq first-symbol followers))
1340 (while (and
1341 (or (py-goto-beyond-block) t) ; side effect
1342 (forward-line -1) ; side effect
1343 (setq last-pos (point)) ; side effect
1344 (py-goto-statement-below)
1345 (= (current-indentation) initial-indent)
1346 (setq next-symbol (py-suck-up-first-keyword))
1347 (memq next-symbol (cdr (assq first-symbol followers))))
1348 (setq first-symbol next-symbol)))
1349
1350 ;; else if line *opens* a block, search for next stmt indented <=
1351 ((py-statement-opens-block-p)
1352 (while (and
1353 (setq last-pos (point)) ; always true -- side effect
1354 (py-goto-statement-below)
1355 (> (current-indentation) initial-indent))
1356 nil))
1357
1358 ;; else plain code line; stop at next blank line, or stmt or
1359 ;; indenting comment line indented <
1360 (t
1361 (while (and
1362 (setq last-pos (point)) ; always true -- side effect
1363 (or (py-goto-beyond-final-line) t)
1364 (not (looking-at "[ \t]*$")) ; stop at blank line
1365 (or
1366 (>= (current-indentation) initial-indent)
1367 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1368 nil)))
1369
1370 ;; skip to end of last stmt
1371 (goto-char last-pos)
1372 (py-goto-beyond-final-line)
1373
1374 ;; set mark & display
1375 (if just-move
1376 () ; just return
1377 (push-mark (point) 'no-msg)
1378 (forward-line -1)
1379 (message "Mark set after: %s" (py-suck-up-leading-text))
1380 (goto-char initial-pos))))
1381
1382(defun mark-python-def-or-class (&optional class)
1383 "Set region to body of def (or class, with prefix arg) enclosing point.
1384Pushes the current mark, then point, on the mark ring (all language
1385modes do this, but although it's handy it's never documented ...).
1386
1387In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001388hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1389`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001390
1391And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392Turned out that was more confusing than useful: the `goto start' and
1393`goto end' commands are usually used to search through a file, and
1394people expect them to act a lot like `search backward' and `search
1395forward' string-search commands. But because Python `def' and `class'
1396can nest to arbitrary levels, finding the smallest def containing
1397point cannot be done via a simple backward search: the def containing
1398point may not be the closest preceding def, or even the closest
1399preceding def that's indented less. The fancy algorithm required is
1400appropriate for the usual uses of this `mark' command, but not for the
1401`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001402
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001403So the def marked by this command may not be the one either of the
1404`goto' commands find: If point is on a blank or non-indenting comment
1405line, moves back to start of the closest preceding code statement or
1406indenting comment line. If this is a `def' statement, that's the def
1407we use. Else searches for the smallest enclosing `def' block and uses
1408that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001409
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001410When an enclosing def is found: The mark is left immediately beyond
1411the last line of the def block. Point is left at the start of the
1412def, except that: if the def is preceded by a number of comment lines
1413followed by (at most) one optional blank line, point is left at the
1414start of the comments; else if the def is preceded by a blank line,
1415point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001416
1417The intent is to mark the containing def/class and its associated
1418documentation, to make moving and duplicating functions and classes
1419pleasant."
1420 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001421 (let ((start (point))
1422 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001423 (push-mark start)
1424 (if (not (py-go-up-tree-to-keyword which))
1425 (progn (goto-char start)
1426 (error "Enclosing %s not found" which))
1427 ;; else enclosing def/class found
1428 (setq start (point))
1429 (py-goto-beyond-block)
1430 (push-mark (point))
1431 (goto-char start)
1432 (if (zerop (forward-line -1)) ; if there is a preceding line
1433 (progn
1434 (if (looking-at "[ \t]*$") ; it's blank
1435 (setq start (point)) ; so reset start point
1436 (goto-char start)) ; else try again
1437 (if (zerop (forward-line -1))
1438 (if (looking-at "[ \t]*#") ; a comment
1439 ;; look back for non-comment line
1440 ;; tricky: note that the regexp matches a blank
1441 ;; line, cuz \n is in the 2nd character class
1442 (and
1443 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1444 (forward-line 1))
1445 ;; no comment, so go back
1446 (goto-char start))))))))
1447
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001448
1449;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001450
1451;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001452;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1453;; out of the right places, along with the keys they're on & current
1454;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455(defun py-dump-help-string (str)
1456 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457 (let ((locals (buffer-local-variables))
1458 funckind funcname func funcdoc
1459 (start 0) mstart end
1460 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1462 (setq mstart (match-beginning 0) end (match-end 0)
1463 funckind (substring str (match-beginning 1) (match-end 1))
1464 funcname (substring str (match-beginning 2) (match-end 2))
1465 func (intern funcname))
1466 (princ (substitute-command-keys (substring str start mstart)))
1467 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001468 ((equal funckind "c") ; command
1469 (setq funcdoc (documentation func)
1470 keys (concat
1471 "Key(s): "
1472 (mapconcat 'key-description
1473 (where-is-internal func py-mode-map)
1474 ", "))))
1475 ((equal funckind "v") ; variable
1476 (setq funcdoc (substitute-command-keys
1477 (get func 'variable-documentation))
1478 keys (if (assq func locals)
1479 (concat
1480 "Local/Global values: "
1481 (prin1-to-string (symbol-value func))
1482 " / "
1483 (prin1-to-string (default-value func)))
1484 (concat
1485 "Value: "
1486 (prin1-to-string (symbol-value func))))))
1487 (t ; unexpected
1488 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001489 (princ (format "\n-> %s:\t%s\t%s\n\n"
1490 (if (equal funckind "c") "Command" "Variable")
1491 funcname keys))
1492 (princ funcdoc)
1493 (terpri)
1494 (setq start end))
1495 (princ (substitute-command-keys (substring str start))))
1496 (print-help-return-message)))
1497
1498(defun py-describe-mode ()
1499 "Dump long form of Python-mode docs."
1500 (interactive)
1501 (py-dump-help-string "Major mode for editing Python files.
1502Knows about Python indentation, tokens, comments and continuation lines.
1503Paragraphs are separated by blank lines only.
1504
1505Major sections below begin with the string `@'; specific function and
1506variable docs begin with `->'.
1507
1508@EXECUTING PYTHON CODE
1509
1510\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1511\\[py-execute-region]\tsends the current region
1512\\[py-shell]\tstarts a Python interpreter window; this will be used by
1513\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1514%c:py-execute-buffer
1515%c:py-execute-region
1516%c:py-shell
1517
1518@VARIABLES
1519
1520py-indent-offset\tindentation increment
1521py-block-comment-prefix\tcomment string used by py-comment-region
1522
1523py-python-command\tshell command to invoke Python interpreter
1524py-scroll-process-buffer\talways scroll Python process buffer
1525py-temp-directory\tdirectory used for temp files (if needed)
1526
1527py-beep-if-tab-change\tring the bell if tab-width is changed
1528%v:py-indent-offset
1529%v:py-block-comment-prefix
1530%v:py-python-command
1531%v:py-scroll-process-buffer
1532%v:py-temp-directory
1533%v:py-beep-if-tab-change
1534
1535@KINDS OF LINES
1536
1537Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001538preceding line ends with a backslash that's not part of a comment, or
1539the paren/bracket/brace nesting level at the start of the line is
1540non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001543possibly blanks or tabs), a `comment line' (leftmost non-blank
1544character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
1546Comment Lines
1547
1548Although all comment lines are treated alike by Python, Python mode
1549recognizes two kinds that act differently with respect to indentation.
1550
1551An `indenting comment line' is a comment line with a blank, tab or
1552nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001554indenting comment line will be indented like the comment line. All
1555other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556following the initial `#') are `non-indenting comment lines', and
1557their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001558
1559Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560whenever possible. Non-indenting comment lines are useful in cases
1561like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001562
1563\ta = b # a very wordy single-line comment that ends up being
1564\t #... continued onto another line
1565
1566\tif a == b:
1567##\t\tprint 'panic!' # old code we've `commented out'
1568\t\treturn a
1569
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570Since the `#...' and `##' comment lines have a non-whitespace
1571character following the initial `#', Python mode ignores them when
1572computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573
1574Continuation Lines and Statements
1575
1576The Python-mode commands generally work on statements instead of on
1577individual lines, where a `statement' is a comment or blank line, or a
1578code line and all of its following continuation lines (if any)
1579considered as a single logical unit. The commands in this mode
1580generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001581statement containing point, even if point happens to be in the middle
1582of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001583
1584
1585@INDENTATION
1586
1587Primarily for entering new code:
1588\t\\[indent-for-tab-command]\t indent line appropriately
1589\t\\[py-newline-and-indent]\t insert newline, then indent
1590\t\\[py-delete-char]\t reduce indentation, or delete single character
1591
1592Primarily for reindenting existing code:
1593\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1594\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1595
1596\t\\[py-indent-region]\t reindent region to match its context
1597\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1598\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1599
1600Unlike most programming languages, Python uses indentation, and only
1601indentation, to specify block structure. Hence the indentation supplied
1602automatically by Python-mode is just an educated guess: only you know
1603the block structure you intend, so only you can supply correct
1604indentation.
1605
1606The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1607the indentation of preceding statements. E.g., assuming
1608py-indent-offset is 4, after you enter
1609\tif a > 0: \\[py-newline-and-indent]
1610the cursor will be moved to the position of the `_' (_ is not a
1611character in the file, it's just used here to indicate the location of
1612the cursor):
1613\tif a > 0:
1614\t _
1615If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1616to
1617\tif a > 0:
1618\t c = d
1619\t _
1620Python-mode cannot know whether that's what you intended, or whether
1621\tif a > 0:
1622\t c = d
1623\t_
1624was your intent. In general, Python-mode either reproduces the
1625indentation of the (closest code or indenting-comment) preceding
1626statement, or adds an extra py-indent-offset blanks if the preceding
1627statement has `:' as its last significant (non-whitespace and non-
1628comment) character. If the suggested indentation is too much, use
1629\\[py-delete-char] to reduce it.
1630
1631Continuation lines are given extra indentation. If you don't like the
1632suggested indentation, change it to something you do like, and Python-
1633mode will strive to indent later lines of the statement in the same way.
1634
1635If a line is a continuation line by virtue of being in an unclosed
1636paren/bracket/brace structure (`list', for short), the suggested
1637indentation depends on whether the current line contains the first item
1638in the list. If it does, it's indented py-indent-offset columns beyond
1639the indentation of the line containing the open bracket. If you don't
1640like that, change it by hand. The remaining items in the list will mimic
1641whatever indentation you give to the first item.
1642
1643If a line is a continuation line because the line preceding it ends with
1644a backslash, the third and following lines of the statement inherit their
1645indentation from the line preceding them. The indentation of the second
1646line in the statement depends on the form of the first (base) line: if
1647the base line is an assignment statement with anything more interesting
1648than the backslash following the leftmost assigning `=', the second line
1649is indented two columns beyond that `='. Else it's indented to two
1650columns beyond the leftmost solid chunk of non-whitespace characters on
1651the base line.
1652
1653Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1654repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1655structure you intend.
1656%c:indent-for-tab-command
1657%c:py-newline-and-indent
1658%c:py-delete-char
1659
1660
1661The next function may be handy when editing code you didn't write:
1662%c:py-guess-indent-offset
1663
1664
1665The remaining `indent' functions apply to a region of Python code. They
1666assume the block structure (equals indentation, in Python) of the region
1667is correct, and alter the indentation in various ways while preserving
1668the block structure:
1669%c:py-indent-region
1670%c:py-shift-region-left
1671%c:py-shift-region-right
1672
1673@MARKING & MANIPULATING REGIONS OF CODE
1674
1675\\[py-mark-block]\t mark block of lines
1676\\[mark-python-def-or-class]\t mark smallest enclosing def
1677\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1678\\[py-comment-region]\t comment out region of code
1679\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1680%c:py-mark-block
1681%c:mark-python-def-or-class
1682%c:py-comment-region
1683
1684@MOVING POINT
1685
1686\\[py-previous-statement]\t move to statement preceding point
1687\\[py-next-statement]\t move to statement following point
1688\\[py-goto-block-up]\t move up to start of current block
1689\\[beginning-of-python-def-or-class]\t move to start of def
1690\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1691\\[end-of-python-def-or-class]\t move to end of def
1692\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1693
1694The first two move to one statement beyond the statement that contains
1695point. A numeric prefix argument tells them to move that many
1696statements instead. Blank lines, comment lines, and continuation lines
1697do not count as `statements' for these commands. So, e.g., you can go
1698to the first code statement in a file by entering
1699\t\\[beginning-of-buffer]\t to move to the top of the file
1700\t\\[py-next-statement]\t to skip over initial comments and blank lines
1701Or do `\\[py-previous-statement]' with a huge prefix argument.
1702%c:py-previous-statement
1703%c:py-next-statement
1704%c:py-goto-block-up
1705%c:beginning-of-python-def-or-class
1706%c:end-of-python-def-or-class
1707
1708@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1709
1710`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1711
1712`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1713overall class and def structure of a module.
1714
1715`\\[back-to-indentation]' moves point to a line's first non-blank character.
1716
1717`\\[indent-relative]' is handy for creating odd indentation.
1718
1719@OTHER EMACS HINTS
1720
1721If you don't like the default value of a variable, change its value to
1722whatever you do like by putting a `setq' line in your .emacs file.
1723E.g., to set the indentation increment to 4, put this line in your
1724.emacs:
1725\t(setq py-indent-offset 4)
1726To see the value of a variable, do `\\[describe-variable]' and enter the variable
1727name at the prompt.
1728
1729When entering a key sequence like `C-c C-n', it is not necessary to
1730release the CONTROL key after doing the `C-c' part -- it suffices to
1731press the CONTROL key, press and release `c' (while still holding down
1732CONTROL), press and release `n' (while still holding down CONTROL), &
1733then release CONTROL.
1734
1735Entering Python mode calls with no arguments the value of the variable
1736`python-mode-hook', if that value exists and is not nil; for backward
1737compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1738the Elisp manual for details.
1739
1740Obscure: When python-mode is first loaded, it looks for all bindings
1741to newline-and-indent in the global keymap, and shadows them with
1742local bindings to py-newline-and-indent."))
1743
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001744
1745;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746(defvar py-parse-state-re
1747 (concat
1748 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1749 "\\|"
1750 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752;; returns the parse state at point (see parse-partial-sexp docs)
1753(defun py-parse-state ()
1754 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 ;; back up to the first preceding line (if any; else start of
1757 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001758 ;; whitespace and non-comment character. These are good places
1759 ;; to start parsing to see whether where we started is at a
1760 ;; non-zero nesting level. It may be slow for people who write
1761 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762 (re-search-backward py-parse-state-re nil 'move)
1763 (beginning-of-line)
1764 (parse-partial-sexp (point) here))))
1765
1766;; if point is at a non-zero nesting level, returns the number of the
1767;; character that opens the smallest enclosing unclosed list; else
1768;; returns nil.
1769(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771 (if (zerop (car status))
1772 nil ; not in a nest
1773 (car (cdr status))))) ; char# of open bracket
1774
1775;; t iff preceding line ends with backslash that's not in a comment
1776(defun py-backslash-continuation-line-p ()
1777 (save-excursion
1778 (beginning-of-line)
1779 (and
1780 ;; use a cheap test first to avoid the regexp if possible
1781 ;; use 'eq' because char-after may return nil
1782 (eq (char-after (- (point) 2)) ?\\ )
1783 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785 (looking-at py-continued-re))))
1786
1787;; t iff current line is a continuation line
1788(defun py-continuation-line-p ()
1789 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791 (or (py-backslash-continuation-line-p)
1792 (py-nesting-level))))
1793
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794;; go to initial line of current statement; usually this is the line
1795;; we're on, but if we're on the 2nd or following lines of a
1796;; continuation block, we need to go up to the first line of the
1797;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001798;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001799;; Tricky: We want to avoid quadratic-time behavior for long continued
1800;; blocks, whether of the backslash or open-bracket varieties, or a
1801;; mix of the two. The following manages to do that in the usual
1802;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001803(defun py-goto-initial-line ()
1804 (let ( open-bracket-pos )
1805 (while (py-continuation-line-p)
1806 (beginning-of-line)
1807 (if (py-backslash-continuation-line-p)
1808 (while (py-backslash-continuation-line-p)
1809 (forward-line -1))
1810 ;; else zip out of nested brackets/braces/parens
1811 (while (setq open-bracket-pos (py-nesting-level))
1812 (goto-char open-bracket-pos)))))
1813 (beginning-of-line))
1814
1815;; go to point right beyond final line of current statement; usually
1816;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001817;; statement we need to skip over the continuation lines. Tricky:
1818;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001819(defun py-goto-beyond-final-line ()
1820 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822 (while (and (py-continuation-line-p)
1823 (not (eobp)))
1824 ;; skip over the backslash flavor
1825 (while (and (py-backslash-continuation-line-p)
1826 (not (eobp)))
1827 (forward-line 1))
1828 ;; if in nest, zip to the end of the nest
1829 (setq state (py-parse-state))
1830 (if (and (not (zerop (car state)))
1831 (not (eobp)))
1832 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834 ;; the 3rd argument should be plain 0
1835 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1836 nil state)
1837 (forward-line 1))))))
1838
1839;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001841(defun py-statement-opens-block-p ()
1842 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843 (let ((start (point))
1844 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1845 (searching t)
1846 (answer nil)
1847 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848 (goto-char start)
1849 (while searching
1850 ;; look for a colon with nothing after it except whitespace, and
1851 ;; maybe a comment
1852 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1853 finish t)
1854 (if (eq (point) finish) ; note: no `else' clause; just
1855 ; keep searching if we're not at
1856 ; the end yet
1857 ;; sure looks like it opens a block -- but it might
1858 ;; be in a comment
1859 (progn
1860 (setq searching nil) ; search is done either way
1861 (setq state (parse-partial-sexp start
1862 (match-beginning 0)))
1863 (setq answer (not (nth 4 state)))))
1864 ;; search failed: couldn't find another interesting colon
1865 (setq searching nil)))
1866 answer)))
1867
1868;; go to point right beyond final line of block begun by the current
1869;; line. This is the same as where py-goto-beyond-final-line goes
1870;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001872(defun py-goto-beyond-block ()
1873 (if (py-statement-opens-block-p)
1874 (py-mark-block nil 'just-move)
1875 (py-goto-beyond-final-line)))
1876
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877;; go to start of first statement (not blank or comment or
1878;; continuation line) at or preceding point. returns t if there is
1879;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880(defun py-goto-statement-at-or-above ()
1881 (py-goto-initial-line)
1882 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001883 ;; skip back over blank & comment lines
1884 ;; note: will skip a blank or comment line that happens to be
1885 ;; a continuation line too
1886 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1887 (progn (py-goto-initial-line) t)
1888 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889 t))
1890
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001891;; go to start of first statement (not blank or comment or
1892;; continuation line) following the statement containing point returns
1893;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001894(defun py-goto-statement-below ()
1895 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001897 (py-goto-beyond-final-line)
1898 (while (and
1899 (looking-at py-blank-or-comment-re)
1900 (not (eobp)))
1901 (forward-line 1))
1902 (if (eobp)
1903 (progn (goto-char start) nil)
1904 t)))
1905
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001906;; go to start of statement, at or preceding point, starting with
1907;; keyword KEY. Skips blank lines and non-indenting comments upward
1908;; first. If that statement starts with KEY, done, else go back to
1909;; first enclosing block starting with KEY. If successful, leaves
1910;; point at the start of the KEY line & returns t. Else leaves point
1911;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001912(defun py-go-up-tree-to-keyword (key)
1913 ;; skip blanks and non-indenting #
1914 (py-goto-initial-line)
1915 (while (and
1916 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1917 (zerop (forward-line -1))) ; go back
1918 nil)
1919 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001920 (let* ((re (concat "[ \t]*" key "\\b"))
1921 (case-fold-search nil) ; let* so looking-at sees this
1922 (found (looking-at re))
1923 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001924 (while (not (or found dead))
1925 (condition-case nil ; in case no enclosing block
1926 (py-goto-block-up 'no-mark)
1927 (error (setq dead t)))
1928 (or dead (setq found (looking-at re))))
1929 (beginning-of-line)
1930 found))
1931
1932;; return string in buffer from start of indentation to end of line;
1933;; prefix "..." if leading whitespace was skipped
1934(defun py-suck-up-leading-text ()
1935 (save-excursion
1936 (back-to-indentation)
1937 (concat
1938 (if (bolp) "" "...")
1939 (buffer-substring (point) (progn (end-of-line) (point))))))
1940
1941;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1942;; as a Lisp symbol; return nil if none
1943(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001944 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1946 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1947 nil)))
1948
1949(defun py-make-temp-name ()
1950 (make-temp-name
1951 (concat (file-name-as-directory py-temp-directory) "python")))
1952
1953(defun py-delete-file-silently (fname)
1954 (condition-case nil
1955 (delete-file fname)
1956 (error nil)))
1957
1958(defun py-kill-emacs-hook ()
1959 ;; delete our temp files
1960 (while py-file-queue
1961 (py-delete-file-silently (car py-file-queue))
1962 (setq py-file-queue (cdr py-file-queue)))
1963 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1964 ;; run the hook we inherited, if any
1965 (and py-inherited-kill-emacs-hook
1966 (funcall py-inherited-kill-emacs-hook))))
1967
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968;; make PROCESS's buffer visible, append STRING to it, and force
1969;; display; also make shell-mode believe the user typed this string,
1970;; so that kill-output-from-shell and show-output-from-shell work
1971;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001972(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001973 (let ((cbuf (current-buffer))
1974 (pbuf (process-buffer process))
1975 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001976 (set-buffer pbuf)
1977 (goto-char (point-max))
1978 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001979 (if (not (or py-this-is-emacs-19-p
1980 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981 (move-marker last-input-start (point))) ; muck w/ shell-mode
1982 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001983 (if (not (or py-this-is-emacs-19-p
1984 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001985 (move-marker last-input-end (point))) ; muck w/ shell-mode
1986 (set-buffer cbuf))
1987 (sit-for 0))
1988
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001989(defun py-keep-region-active ()
1990 ;; do whatever is necessary to keep the region active in XEmacs.
1991 ;; Ignore byte-compiler warnings you might see. Also note that
1992 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1993 ;; require us to take explicit action.
1994 (and (boundp 'zmacs-region-stays)
1995 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996
1997
Barry Warsaw850437a1995-03-08 21:50:28 +00001998(defconst py-version "$Revision$"
1999 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002000(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002001 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002
Barry Warsaw850437a1995-03-08 21:50:28 +00002003(defun py-version ()
2004 "Echo the current version of `python-mode' in the minibuffer."
2005 (interactive)
2006 (message "Using `python-mode' version %s" py-version)
2007 (py-keep-region-active))
2008
2009;; only works under Emacs 19
2010;(eval-when-compile
2011; (require 'reporter))
2012
2013(defun py-submit-bug-report (enhancement-p)
2014 "Submit via mail a bug report on `python-mode'.
2015With \\[universal-argument] just submit an enhancement request."
2016 (interactive
2017 (list (not (y-or-n-p
2018 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002019 (let ((reporter-prompt-for-summary-p (if enhancement-p
2020 "(Very) brief summary: "
2021 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002022 (require 'reporter)
2023 (reporter-submit-bug-report
2024 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002025 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002026 ;; varlist
2027 (if enhancement-p nil
2028 '(py-python-command
2029 py-indent-offset
2030 py-block-comment-prefix
2031 py-scroll-process-buffer
2032 py-temp-directory
2033 py-beep-if-tab-change))
2034 nil ;pre-hooks
2035 nil ;post-hooks
2036 "Dear Barry,") ;salutation
2037 (if enhancement-p nil
2038 (set-mark (point))
2039 (insert
2040"Please replace this text with a sufficiently large code sample\n\
2041and an exact recipe so that I can reproduce your problem. Failure\n\
2042to do so may mean a greater delay in fixing your bug.\n\n")
2043 (exchange-point-and-mark)
2044 (py-keep-region-active))))
2045
2046
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002047;; arrange to kill temp files when Emacs exists
2048(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2049 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2050 ;; have to trust that other people are as respectful of our hook
2051 ;; fiddling as we are of theirs
2052 (if (boundp 'py-inherited-kill-emacs-hook)
2053 ;; we were loaded before -- trust others not to have screwed us
2054 ;; in the meantime (no choice, really)
2055 nil
2056 ;; else arrange for our hook to run theirs
2057 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2058 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2059
2060
2061
2062(provide 'python-mode)
2063;;; python-mode.el ends here