blob: a4b5b4e41090f34ec33a8d58beb72af870f0ff18 [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 Warsawdea4a291996-07-03 22:59:12 +0000279 ("\C-c\C-l" . py-shift-region-left)
280 ("\C-c\C-r" . py-shift-region-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
497
Barry Warsaw7ae77681994-12-12 20:38:05 +0000498;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000499(defun py-shell ()
500 "Start an interactive Python interpreter in another window.
501This is like Shell mode, except that Python is running in the window
502instead of a shell. See the `Interactive Shell' and `Shell Mode'
503sections of the Emacs manual for details, especially for the key
504bindings active in the `*Python*' buffer.
505
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000506See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000507behavior in the process window.
508
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000509Warning: Don't use an interactive Python if you change sys.ps1 or
510sys.ps2 from their default values, or if you're running code that
511prints `>>> ' or `... ' at the start of a line. `python-mode' can't
512distinguish your output from Python's output, and assumes that `>>> '
513at the start of a line is a prompt from Python. Similarly, the Emacs
514Shell mode code assumes that both `>>> ' and `... ' at the start of a
515line are Python prompts. Bad things can happen if you fool either
516mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000517
518Warning: If you do any editing *in* the process buffer *while* the
519buffer is accepting output from Python, do NOT attempt to `undo' the
520changes. Some of the output (nowhere near the parts you changed!) may
521be lost if you do. This appears to be an Emacs bug, an unfortunate
522interaction between undo and process filters; the same problem exists in
523non-Python process buffers using the default (Emacs-supplied) process
524filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000525 ;; BAW - should undo be disabled in the python process buffer, if
526 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000527 (interactive)
528 (if py-this-is-emacs-19-p
529 (progn
530 (require 'comint)
531 (switch-to-buffer-other-window
532 (make-comint "Python" py-python-command)))
533 (progn
534 (require 'shell)
535 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000536 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000537 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000538 (make-local-variable 'shell-prompt-pattern)
539 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
540 (set-process-filter (get-buffer-process (current-buffer))
541 'py-process-filter)
542 (set-syntax-table py-mode-syntax-table))
543
544(defun py-execute-region (start end)
545 "Send the region between START and END to a Python interpreter.
546If there is a *Python* process it is used.
547
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000548Hint: If you want to execute part of a Python file several times
549\(e.g., perhaps you're developing a function and want to flesh it out
550a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
551the region of interest, and send the code to a *Python* process via
552`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000553
554Following are subtleties to note when using a *Python* process:
555
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000556If a *Python* process is used, the region is copied into a temporary
557file (in directory `py-temp-directory'), and an `execfile' command is
558sent to Python naming that file. If you send regions faster than
559Python can execute them, `python-mode' will save them into distinct
560temp files, and execute the next one in the queue the next time it
561sees a `>>> ' prompt from Python. Each time this happens, the process
562buffer is popped into a window (if it's not already in some window) so
563you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000565 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000566
567is inserted at the end.
568
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000569Caution: No more than 26 regions can be pending at any given time.
570This limit is (indirectly) inherited from libc's mktemp(3).
571`python-mode' does not try to protect you from exceeding the limit.
572It's extremely unlikely that you'll get anywhere close to the limit in
573practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000574
575See the `\\[py-shell]' docs for additional warnings."
576 (interactive "r")
577 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000578 (let ((pyproc (get-process "Python"))
579 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000580 (if (null pyproc)
581 (shell-command-on-region start end py-python-command)
582 ;; else feed it thru a temp file
583 (setq fname (py-make-temp-name))
584 (write-region start end fname nil 'no-msg)
585 (setq py-file-queue (append py-file-queue (list fname)))
586 (if (cdr py-file-queue)
587 (message "File %s queued for execution" fname)
588 ;; else
589 (py-execute-file pyproc fname)))))
590
591(defun py-execute-file (pyproc fname)
592 (py-append-to-process-buffer
593 pyproc
594 (format "## working on region in file %s ...\n" fname))
595 (process-send-string pyproc (format "execfile('%s')\n" fname)))
596
597(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000598 (let ((curbuf (current-buffer))
599 (pbuf (process-buffer pyproc))
600 (pmark (process-mark pyproc))
601 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000602
603 ;; make sure we switch to a different buffer at least once. if we
604 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000605 ;; window, and point is before the end, and lots of output is
606 ;; coming at a fast pace, then (a) simple cursor-movement commands
607 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
608 ;; to have a visible effect (the window just doesn't get updated,
609 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
610 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000611 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000612 ;; #b makes no sense to me at all. #a almost makes sense: unless
613 ;; we actually change buffers, set_buffer_internal in buffer.c
614 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
615 ;; seems to make the Emacs command loop reluctant to update the
616 ;; display. Perhaps the default process filter in process.c's
617 ;; read_process_output has update_mode_lines++ for a similar
618 ;; reason? beats me ...
619
620 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000621 (if (eq curbuf pbuf) ; mysterious ugly hack
622 (set-buffer (get-buffer-create "*scratch*")))
623
624 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000625 (let* ((start (point))
626 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000627 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000628 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000629 (goto-char pmark)
630 (insert string)
631 (move-marker pmark (point))
632 (setq file-finished
633 (and py-file-queue
634 (equal ">>> "
635 (buffer-substring
636 (prog2 (beginning-of-line) (point)
637 (goto-char pmark))
638 (point)))))
639 (if goback (goto-char start)
640 ;; else
641 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000642 (let* ((pop-up-windows t)
643 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000644 (set-window-point pwin (point)))))
645 (set-buffer curbuf)
646 (if file-finished
647 (progn
648 (py-delete-file-silently (car py-file-queue))
649 (setq py-file-queue (cdr py-file-queue))
650 (if py-file-queue
651 (py-execute-file pyproc (car py-file-queue)))))
652 (and goend
653 (progn (set-buffer pbuf)
654 (goto-char (point-max))))
655 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000656
657(defun py-execute-buffer ()
658 "Send the contents of the buffer to a Python interpreter.
659If there is a *Python* process buffer it is used. If a clipping
660restriction is in effect, only the accessible portion of the buffer is
661sent. A trailing newline will be supplied if needed.
662
663See the `\\[py-execute-region]' docs for an account of some subtleties."
664 (interactive)
665 (py-execute-region (point-min) (point-max)))
666
667
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000668
669;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000670(defun py-delete-char ()
671 "Reduce indentation or delete character.
672If point is at the leftmost column, deletes the preceding newline.
673
674Else if point is at the leftmost non-blank character of a line that is
675neither a continuation line nor a non-indenting comment line, or if
676point is at the end of a blank line, reduces the indentation to match
677that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000678opened the block is displayed in the echo area to help you keep track
679of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000680
681Else the preceding character is deleted, converting a tab to spaces if
682needed so that only a single column position is deleted."
683 (interactive "*")
684 (if (or (/= (current-indentation) (current-column))
685 (bolp)
686 (py-continuation-line-p)
687 (looking-at "#[^ \t\n]")) ; non-indenting #
688 (backward-delete-char-untabify 1)
689 ;; else indent the same as the colon line that opened the block
690
691 ;; force non-blank so py-goto-block-up doesn't ignore it
692 (insert-char ?* 1)
693 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000694 (let ((base-indent 0) ; indentation of base line
695 (base-text "") ; and text of base line
696 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000697 (condition-case nil ; in case no enclosing block
698 (save-excursion
699 (py-goto-block-up 'no-mark)
700 (setq base-indent (current-indentation)
701 base-text (py-suck-up-leading-text)
702 base-found-p t))
703 (error nil))
704 (delete-char 1) ; toss the dummy character
705 (delete-horizontal-space)
706 (indent-to base-indent)
707 (if base-found-p
708 (message "Closes block: %s" base-text)))))
709
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000710;; required for pending-del and delsel modes
711(put 'py-delete-char 'delete-selection 'supersede)
712(put 'py-delete-char 'pending-delete 'supersede)
713
Barry Warsaw7ae77681994-12-12 20:38:05 +0000714(defun py-indent-line ()
715 "Fix the indentation of the current line according to Python rules."
716 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000717 (let* ((ci (current-indentation))
718 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000719 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000720 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000721 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000722 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000723 (if (/= ci need)
724 (save-excursion
725 (beginning-of-line)
726 (delete-horizontal-space)
727 (indent-to need)))
728 (if move-to-indentation-p (back-to-indentation))))
729
730(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000731 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000732This is just `strives to' because correct indentation can't be computed
733from scratch for Python code. In general, deletes the whitespace before
734point, inserts a newline, and takes an educated guess as to how you want
735the new line indented."
736 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000737 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738 (if (< ci (current-column)) ; if point beyond indentation
739 (newline-and-indent)
740 ;; else try to act like newline-and-indent "normally" acts
741 (beginning-of-line)
742 (insert-char ?\n 1)
743 (move-to-column ci))))
744
745(defun py-compute-indentation ()
746 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000747 (let ((pps (parse-partial-sexp (save-excursion
748 (beginning-of-python-def-or-class)
749 (point))
750 (point))))
751 (beginning-of-line)
752 (cond
753 ;; are we inside a string or comment?
754 ((or (nth 3 pps) (nth 4 pps))
755 (save-excursion
756 (if (not py-align-multiline-strings-p) 0
757 ;; skip back over blank & non-indenting comment lines
758 ;; note: will skip a blank or non-indenting comment line
759 ;; that happens to be a continuation line too
760 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
761 (back-to-indentation)
762 (current-column))))
763 ;; are we on a continuation line?
764 ((py-continuation-line-p)
765 (let ((startpos (point))
766 (open-bracket-pos (py-nesting-level))
767 endpos searching found)
768 (if open-bracket-pos
769 (progn
770 ;; align with first item in list; else a normal
771 ;; indent beyond the line with the open bracket
772 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
773 ;; is the first list item on the same line?
774 (skip-chars-forward " \t")
775 (if (null (memq (following-char) '(?\n ?# ?\\)))
776 ; yes, so line up with it
777 (current-column)
778 ;; first list item on another line, or doesn't exist yet
779 (forward-line 1)
780 (while (and (< (point) startpos)
781 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
782 (forward-line 1))
783 (if (< (point) startpos)
784 ;; again mimic the first list item
785 (current-indentation)
786 ;; else they're about to enter the first item
787 (goto-char open-bracket-pos)
788 (+ (current-indentation) py-indent-offset))))
789
790 ;; else on backslash continuation line
791 (forward-line -1)
792 (if (py-continuation-line-p) ; on at least 3rd line in block
793 (current-indentation) ; so just continue the pattern
794 ;; else started on 2nd line in block, so indent more.
795 ;; if base line is an assignment with a start on a RHS,
796 ;; indent to 2 beyond the leftmost "="; else skip first
797 ;; chunk of non-whitespace characters on base line, + 1 more
798 ;; column
799 (end-of-line)
800 (setq endpos (point) searching t)
801 (back-to-indentation)
802 (setq startpos (point))
803 ;; look at all "=" from left to right, stopping at first
804 ;; one not nested in a list or string
805 (while searching
806 (skip-chars-forward "^=" endpos)
807 (if (= (point) endpos)
808 (setq searching nil)
809 (forward-char 1)
810 (setq state (parse-partial-sexp startpos (point)))
811 (if (and (zerop (car state)) ; not in a bracket
812 (null (nth 3 state))) ; & not in a string
813 (progn
814 (setq searching nil) ; done searching in any case
815 (setq found
816 (not (or
817 (eq (following-char) ?=)
818 (memq (char-after (- (point) 2))
819 '(?< ?> ?!)))))))))
820 (if (or (not found) ; not an assignment
821 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
822 (progn
823 (goto-char startpos)
824 (skip-chars-forward "^ \t\n")))
825 (1+ (current-column))))))
826
827 ;; not on a continuation line
828
829 ;; if at start of restriction, or on a non-indenting comment
830 ;; line, assume they intended whatever's there
831 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
832 (current-indentation))
833
834 ;; else indentation based on that of the statement that
835 ;; precedes us; use the first line of that statement to
836 ;; establish the base, in case the user forced a non-std
837 ;; indentation for the continuation lines (if any)
838 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000839 ;; skip back over blank & non-indenting comment lines note:
840 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000841 ;; happens to be a continuation line too. use fast Emacs 19
842 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000843 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000844 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000845 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000846 (let (done)
847 (while (not done)
848 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
849 nil 'move)
850 (setq done (or (eq py-honor-comment-indentation t)
851 (bobp)
852 (/= (following-char) ?#)
853 (not (zerop (current-column)))))
854 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000855 ;; if we landed inside a string, go to the beginning of that
856 ;; string. this handles triple quoted, multi-line spanning
857 ;; strings.
858 (py-goto-initial-line)
859 (if (py-statement-opens-block-p)
860 (+ (current-indentation) py-indent-offset)
861 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000862
863(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000864 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000865By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000866`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000867Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000868`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000869their own buffer-local copy), both those currently existing and those
870created later in the Emacs session.
871
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000872Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000873There's no excuse for such foolishness, but sometimes you have to deal
874with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000875`py-indent-offset' to what it thinks it was when they created the
876mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877
878Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000879looking for a line that opens a block of code. `py-indent-offset' is
880set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000881statement following it. If the search doesn't succeed going forward,
882it's tried again going backward."
883 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000884 (let (new-value
885 (start (point))
886 restart
887 (found nil)
888 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000889 (py-goto-initial-line)
890 (while (not (or found (eobp)))
891 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
892 (progn
893 (setq restart (point))
894 (py-goto-initial-line)
895 (if (py-statement-opens-block-p)
896 (setq found t)
897 (goto-char restart)))))
898 (if found
899 ()
900 (goto-char start)
901 (py-goto-initial-line)
902 (while (not (or found (bobp)))
903 (setq found
904 (and
905 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
906 (or (py-goto-initial-line) t) ; always true -- side effect
907 (py-statement-opens-block-p)))))
908 (setq colon-indent (current-indentation)
909 found (and found (zerop (py-next-statement 1)))
910 new-value (- (current-indentation) colon-indent))
911 (goto-char start)
912 (if found
913 (progn
914 (funcall (if global 'kill-local-variable 'make-local-variable)
915 'py-indent-offset)
916 (setq py-indent-offset new-value)
917 (message "%s value of py-indent-offset set to %d"
918 (if global "Global" "Local")
919 py-indent-offset))
920 (error "Sorry, couldn't guess a value for py-indent-offset"))))
921
922(defun py-shift-region (start end count)
923 (save-excursion
924 (goto-char end) (beginning-of-line) (setq end (point))
925 (goto-char start) (beginning-of-line) (setq start (point))
926 (indent-rigidly start end count)))
927
928(defun py-shift-region-left (start end &optional count)
929 "Shift region of Python code to the left.
930The lines from the line containing the start of the current region up
931to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000932shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000933
934If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000935many columns. With no active region, outdent only the current line.
936You cannot outdent the region if any line is already at column zero."
937 (interactive
938 (let ((p (point))
939 (m (mark))
940 (arg current-prefix-arg))
941 (if m
942 (list (min p m) (max p m) arg)
943 (list p (save-excursion (forward-line 1) (point)) arg))))
944 ;; if any line is at column zero, don't shift the region
945 (save-excursion
946 (goto-char start)
947 (while (< (point) end)
948 (back-to-indentation)
949 (if (zerop (current-column))
950 (error "Region is at left edge."))
951 (forward-line 1)))
952 (py-shift-region start end (- (prefix-numeric-value
953 (or count py-indent-offset))))
954 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000955
956(defun py-shift-region-right (start end &optional count)
957 "Shift region of Python code to the right.
958The lines from the line containing the start of the current region up
959to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000960shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000961
962If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000963many columns. With no active region, indent only the current line."
964 (interactive
965 (let ((p (point))
966 (m (mark))
967 (arg current-prefix-arg))
968 (if m
969 (list (min p m) (max p m) arg)
970 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000972 (or count py-indent-offset)))
973 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000974
975(defun py-indent-region (start end &optional indent-offset)
976 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000977
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978The lines from the line containing the start of the current region up
979to (but not including) the line containing the end of the region are
980reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981character in the first column, the first line is left alone and the
982rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +0000983region is reindented with respect to the (closest code or indenting
984comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000985
986This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000987control structures are introduced or removed, or to reformat code
988using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000989
990If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000991the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992used.
993
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995is called! This function does not compute proper indentation from
996scratch (that's impossible in Python), it merely adjusts the existing
997indentation to be correct in context.
998
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000999Warning: This function really has no idea what to do with
1000non-indenting comment lines, and shifts them as if they were indenting
1001comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001003Special cases: whitespace is deleted from blank lines; continuation
1004lines are shifted by the same amount their initial line was shifted,
1005in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008 (save-excursion
1009 (goto-char end) (beginning-of-line) (setq end (point-marker))
1010 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001011 (let ((py-indent-offset (prefix-numeric-value
1012 (or indent-offset py-indent-offset)))
1013 (indents '(-1)) ; stack of active indent levels
1014 (target-column 0) ; column to which to indent
1015 (base-shifted-by 0) ; amount last base line was shifted
1016 (indent-base (if (looking-at "[ \t\n]")
1017 (py-compute-indentation)
1018 0))
1019 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001020 (while (< (point) end)
1021 (setq ci (current-indentation))
1022 ;; figure out appropriate target column
1023 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024 ((or (eq (following-char) ?#) ; comment in column 1
1025 (looking-at "[ \t]*$")) ; entirely blank
1026 (setq target-column 0))
1027 ((py-continuation-line-p) ; shift relative to base line
1028 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029 (t ; new base line
1030 (if (> ci (car indents)) ; going deeper; push it
1031 (setq indents (cons ci indents))
1032 ;; else we should have seen this indent before
1033 (setq indents (memq ci indents)) ; pop deeper indents
1034 (if (null indents)
1035 (error "Bad indentation in region, at line %d"
1036 (save-restriction
1037 (widen)
1038 (1+ (count-lines 1 (point)))))))
1039 (setq target-column (+ indent-base
1040 (* py-indent-offset
1041 (- (length indents) 2))))
1042 (setq base-shifted-by (- target-column ci))))
1043 ;; shift as needed
1044 (if (/= ci target-column)
1045 (progn
1046 (delete-horizontal-space)
1047 (indent-to target-column)))
1048 (forward-line 1))))
1049 (set-marker end nil))
1050
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001051
1052;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001053(defun py-previous-statement (count)
1054 "Go to the start of previous Python statement.
1055If the statement at point is the i'th Python statement, goes to the
1056start of statement i-COUNT. If there is no such statement, goes to the
1057first statement. Returns count of statements left to move.
1058`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001059 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001060 (if (< count 0) (py-next-statement (- count))
1061 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001062 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001063 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001064 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001065 (> count 0)
1066 (zerop (forward-line -1))
1067 (py-goto-statement-at-or-above))
1068 (setq count (1- count)))
1069 (if (> count 0) (goto-char start)))
1070 count))
1071
1072(defun py-next-statement (count)
1073 "Go to the start of next Python statement.
1074If the statement at point is the i'th Python statement, goes to the
1075start of statement i+COUNT. If there is no such statement, goes to the
1076last statement. Returns count of statements left to move. `Statements'
1077do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001079 (if (< count 0) (py-previous-statement (- count))
1080 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001081 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001082 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 (> count 0)
1085 (py-goto-statement-below))
1086 (setq count (1- count)))
1087 (if (> count 0) (goto-char start)))
1088 count))
1089
1090(defun py-goto-block-up (&optional nomark)
1091 "Move up to start of current block.
1092Go to the statement that starts the smallest enclosing block; roughly
1093speaking, this will be the closest preceding statement that ends with a
1094colon and is indented less than the statement you started on. If
1095successful, also sets the mark to the starting point.
1096
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001097`\\[py-mark-block]' can be used afterward to mark the whole code
1098block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001099
1100If called from a program, the mark will not be set if optional argument
1101NOMARK is not nil."
1102 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001103 (let ((start (point))
1104 (found nil)
1105 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001106 (py-goto-initial-line)
1107 ;; if on blank or non-indenting comment line, use the preceding stmt
1108 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1109 (progn
1110 (py-goto-statement-at-or-above)
1111 (setq found (py-statement-opens-block-p))))
1112 ;; search back for colon line indented less
1113 (setq initial-indent (current-indentation))
1114 (if (zerop initial-indent)
1115 ;; force fast exit
1116 (goto-char (point-min)))
1117 (while (not (or found (bobp)))
1118 (setq found
1119 (and
1120 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1121 (or (py-goto-initial-line) t) ; always true -- side effect
1122 (< (current-indentation) initial-indent)
1123 (py-statement-opens-block-p))))
1124 (if found
1125 (progn
1126 (or nomark (push-mark start))
1127 (back-to-indentation))
1128 (goto-char start)
1129 (error "Enclosing block not found"))))
1130
1131(defun beginning-of-python-def-or-class (&optional class)
1132 "Move point to start of def (or class, with prefix arg).
1133
1134Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001135arg, looks for a `class' instead. The docs assume the `def' case;
1136just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001137
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001138If point is in a def statement already, and after the `d', simply
1139moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001140
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001141Else (point is not in a def statement, or at or before the `d' of a
1142def statement), searches for the closest preceding def statement, and
1143leaves point at its start. If no such statement can be found, leaves
1144point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001145
1146Returns t iff a def statement is found by these rules.
1147
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148Note that doing this command repeatedly will take you closer to the
1149start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001151If you want to mark the current def/class, see
1152`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001153 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001154 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1155 (start-of-line (progn (beginning-of-line) (point)))
1156 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001157 (if (or (/= start-of-stmt start-of-line)
1158 (not at-or-before-p))
1159 (end-of-line)) ; OK to match on this line
1160 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001161 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162
1163(defun end-of-python-def-or-class (&optional class)
1164 "Move point beyond end of def (or class, with prefix arg) body.
1165
1166By default, looks for an appropriate `def'. If you supply a prefix arg,
1167looks for a `class' instead. The docs assume the `def' case; just
1168substitute `class' for `def' for the other case.
1169
1170If point is in a def statement already, this is the def we use.
1171
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001172Else if the def found by `\\[beginning-of-python-def-or-class]'
1173contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174
1175Else we search forward for the closest following def, and use that.
1176
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001177If a def can be found by these rules, point is moved to the start of
1178the line immediately following the def block, and the position of the
1179start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001180
1181Else point is moved to the end of the buffer, and nil is returned.
1182
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001183Note that doing this command repeatedly will take you closer to the
1184end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001185
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001186If you want to mark the current def/class, see
1187`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001188 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001189 (let ((start (progn (py-goto-initial-line) (point)))
1190 (which (if class "class" "def"))
1191 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001192 ;; move point to start of appropriate def/class
1193 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1194 (setq state 'at-beginning)
1195 ;; else see if beginning-of-python-def-or-class hits container
1196 (if (and (beginning-of-python-def-or-class class)
1197 (progn (py-goto-beyond-block)
1198 (> (point) start)))
1199 (setq state 'at-end)
1200 ;; else search forward
1201 (goto-char start)
1202 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1203 (progn (setq state 'at-beginning)
1204 (beginning-of-line)))))
1205 (cond
1206 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1207 ((eq state 'at-end) t)
1208 ((eq state 'not-found) nil)
1209 (t (error "internal error in end-of-python-def-or-class")))))
1210
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001211
1212;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001213(defun py-mark-block (&optional extend just-move)
1214 "Mark following block of lines. With prefix arg, mark structure.
1215Easier to use than explain. It sets the region to an `interesting'
1216block of succeeding lines. If point is on a blank line, it goes down to
1217the next non-blank line. That will be the start of the region. The end
1218of the region depends on the kind of line at the start:
1219
1220 - If a comment, the region will include all succeeding comment lines up
1221 to (but not including) the next non-comment line (if any).
1222
1223 - Else if a prefix arg is given, and the line begins one of these
1224 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001225
1226 if elif else try except finally for while def class
1227
Barry Warsaw7ae77681994-12-12 20:38:05 +00001228 the region will be set to the body of the structure, including
1229 following blocks that `belong' to it, but excluding trailing blank
1230 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001231 and all (if any) of the following `except' and `finally' blocks
1232 that belong to the `try' structure will be in the region. Ditto
1233 for if/elif/else, for/else and while/else structures, and (a bit
1234 degenerate, since they're always one-block structures) def and
1235 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001236
1237 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001238 block (see list above), and the block is not a `one-liner' (i.e.,
1239 the statement ends with a colon, not with code), the region will
1240 include all succeeding lines up to (but not including) the next
1241 code statement (if any) that's indented no more than the starting
1242 line, except that trailing blank and comment lines are excluded.
1243 E.g., if the starting line begins a multi-statement `def'
1244 structure, the region will be set to the full function definition,
1245 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001246
1247 - Else the region will include all succeeding lines up to (but not
1248 including) the next blank line, or code or indenting-comment line
1249 indented strictly less than the starting line. Trailing indenting
1250 comment lines are included in this case, but not trailing blank
1251 lines.
1252
1253A msg identifying the location of the mark is displayed in the echo
1254area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1255
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001256If called from a program, optional argument EXTEND plays the role of
1257the prefix arg, and if optional argument JUST-MOVE is not nil, just
1258moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001259 (interactive "P") ; raw prefix arg
1260 (py-goto-initial-line)
1261 ;; skip over blank lines
1262 (while (and
1263 (looking-at "[ \t]*$") ; while blank line
1264 (not (eobp))) ; & somewhere to go
1265 (forward-line 1))
1266 (if (eobp)
1267 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001268 (let ((initial-pos (point))
1269 (initial-indent (current-indentation))
1270 last-pos ; position of last stmt in region
1271 (followers
1272 '((if elif else) (elif elif else) (else)
1273 (try except finally) (except except) (finally)
1274 (for else) (while else)
1275 (def) (class) ) )
1276 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277
1278 (cond
1279 ;; if comment line, suck up the following comment lines
1280 ((looking-at "[ \t]*#")
1281 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1282 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1283 (setq last-pos (point)))
1284
1285 ;; else if line is a block line and EXTEND given, suck up
1286 ;; the whole structure
1287 ((and extend
1288 (setq first-symbol (py-suck-up-first-keyword) )
1289 (assq first-symbol followers))
1290 (while (and
1291 (or (py-goto-beyond-block) t) ; side effect
1292 (forward-line -1) ; side effect
1293 (setq last-pos (point)) ; side effect
1294 (py-goto-statement-below)
1295 (= (current-indentation) initial-indent)
1296 (setq next-symbol (py-suck-up-first-keyword))
1297 (memq next-symbol (cdr (assq first-symbol followers))))
1298 (setq first-symbol next-symbol)))
1299
1300 ;; else if line *opens* a block, search for next stmt indented <=
1301 ((py-statement-opens-block-p)
1302 (while (and
1303 (setq last-pos (point)) ; always true -- side effect
1304 (py-goto-statement-below)
1305 (> (current-indentation) initial-indent))
1306 nil))
1307
1308 ;; else plain code line; stop at next blank line, or stmt or
1309 ;; indenting comment line indented <
1310 (t
1311 (while (and
1312 (setq last-pos (point)) ; always true -- side effect
1313 (or (py-goto-beyond-final-line) t)
1314 (not (looking-at "[ \t]*$")) ; stop at blank line
1315 (or
1316 (>= (current-indentation) initial-indent)
1317 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1318 nil)))
1319
1320 ;; skip to end of last stmt
1321 (goto-char last-pos)
1322 (py-goto-beyond-final-line)
1323
1324 ;; set mark & display
1325 (if just-move
1326 () ; just return
1327 (push-mark (point) 'no-msg)
1328 (forward-line -1)
1329 (message "Mark set after: %s" (py-suck-up-leading-text))
1330 (goto-char initial-pos))))
1331
1332(defun mark-python-def-or-class (&optional class)
1333 "Set region to body of def (or class, with prefix arg) enclosing point.
1334Pushes the current mark, then point, on the mark ring (all language
1335modes do this, but although it's handy it's never documented ...).
1336
1337In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001338hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1339`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340
1341And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001342Turned out that was more confusing than useful: the `goto start' and
1343`goto end' commands are usually used to search through a file, and
1344people expect them to act a lot like `search backward' and `search
1345forward' string-search commands. But because Python `def' and `class'
1346can nest to arbitrary levels, finding the smallest def containing
1347point cannot be done via a simple backward search: the def containing
1348point may not be the closest preceding def, or even the closest
1349preceding def that's indented less. The fancy algorithm required is
1350appropriate for the usual uses of this `mark' command, but not for the
1351`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001353So the def marked by this command may not be the one either of the
1354`goto' commands find: If point is on a blank or non-indenting comment
1355line, moves back to start of the closest preceding code statement or
1356indenting comment line. If this is a `def' statement, that's the def
1357we use. Else searches for the smallest enclosing `def' block and uses
1358that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001359
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360When an enclosing def is found: The mark is left immediately beyond
1361the last line of the def block. Point is left at the start of the
1362def, except that: if the def is preceded by a number of comment lines
1363followed by (at most) one optional blank line, point is left at the
1364start of the comments; else if the def is preceded by a blank line,
1365point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001366
1367The intent is to mark the containing def/class and its associated
1368documentation, to make moving and duplicating functions and classes
1369pleasant."
1370 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371 (let ((start (point))
1372 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373 (push-mark start)
1374 (if (not (py-go-up-tree-to-keyword which))
1375 (progn (goto-char start)
1376 (error "Enclosing %s not found" which))
1377 ;; else enclosing def/class found
1378 (setq start (point))
1379 (py-goto-beyond-block)
1380 (push-mark (point))
1381 (goto-char start)
1382 (if (zerop (forward-line -1)) ; if there is a preceding line
1383 (progn
1384 (if (looking-at "[ \t]*$") ; it's blank
1385 (setq start (point)) ; so reset start point
1386 (goto-char start)) ; else try again
1387 (if (zerop (forward-line -1))
1388 (if (looking-at "[ \t]*#") ; a comment
1389 ;; look back for non-comment line
1390 ;; tricky: note that the regexp matches a blank
1391 ;; line, cuz \n is in the 2nd character class
1392 (and
1393 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1394 (forward-line 1))
1395 ;; no comment, so go back
1396 (goto-char start))))))))
1397
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001398
1399;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001400
1401;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001402;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1403;; out of the right places, along with the keys they're on & current
1404;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001405(defun py-dump-help-string (str)
1406 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001407 (let ((locals (buffer-local-variables))
1408 funckind funcname func funcdoc
1409 (start 0) mstart end
1410 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001411 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1412 (setq mstart (match-beginning 0) end (match-end 0)
1413 funckind (substring str (match-beginning 1) (match-end 1))
1414 funcname (substring str (match-beginning 2) (match-end 2))
1415 func (intern funcname))
1416 (princ (substitute-command-keys (substring str start mstart)))
1417 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001418 ((equal funckind "c") ; command
1419 (setq funcdoc (documentation func)
1420 keys (concat
1421 "Key(s): "
1422 (mapconcat 'key-description
1423 (where-is-internal func py-mode-map)
1424 ", "))))
1425 ((equal funckind "v") ; variable
1426 (setq funcdoc (substitute-command-keys
1427 (get func 'variable-documentation))
1428 keys (if (assq func locals)
1429 (concat
1430 "Local/Global values: "
1431 (prin1-to-string (symbol-value func))
1432 " / "
1433 (prin1-to-string (default-value func)))
1434 (concat
1435 "Value: "
1436 (prin1-to-string (symbol-value func))))))
1437 (t ; unexpected
1438 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001439 (princ (format "\n-> %s:\t%s\t%s\n\n"
1440 (if (equal funckind "c") "Command" "Variable")
1441 funcname keys))
1442 (princ funcdoc)
1443 (terpri)
1444 (setq start end))
1445 (princ (substitute-command-keys (substring str start))))
1446 (print-help-return-message)))
1447
1448(defun py-describe-mode ()
1449 "Dump long form of Python-mode docs."
1450 (interactive)
1451 (py-dump-help-string "Major mode for editing Python files.
1452Knows about Python indentation, tokens, comments and continuation lines.
1453Paragraphs are separated by blank lines only.
1454
1455Major sections below begin with the string `@'; specific function and
1456variable docs begin with `->'.
1457
1458@EXECUTING PYTHON CODE
1459
1460\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1461\\[py-execute-region]\tsends the current region
1462\\[py-shell]\tstarts a Python interpreter window; this will be used by
1463\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1464%c:py-execute-buffer
1465%c:py-execute-region
1466%c:py-shell
1467
1468@VARIABLES
1469
1470py-indent-offset\tindentation increment
1471py-block-comment-prefix\tcomment string used by py-comment-region
1472
1473py-python-command\tshell command to invoke Python interpreter
1474py-scroll-process-buffer\talways scroll Python process buffer
1475py-temp-directory\tdirectory used for temp files (if needed)
1476
1477py-beep-if-tab-change\tring the bell if tab-width is changed
1478%v:py-indent-offset
1479%v:py-block-comment-prefix
1480%v:py-python-command
1481%v:py-scroll-process-buffer
1482%v:py-temp-directory
1483%v:py-beep-if-tab-change
1484
1485@KINDS OF LINES
1486
1487Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001488preceding line ends with a backslash that's not part of a comment, or
1489the paren/bracket/brace nesting level at the start of the line is
1490non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491
1492An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001493possibly blanks or tabs), a `comment line' (leftmost non-blank
1494character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001495
1496Comment Lines
1497
1498Although all comment lines are treated alike by Python, Python mode
1499recognizes two kinds that act differently with respect to indentation.
1500
1501An `indenting comment line' is a comment line with a blank, tab or
1502nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001504indenting comment line will be indented like the comment line. All
1505other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001506following the initial `#') are `non-indenting comment lines', and
1507their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001508
1509Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001510whenever possible. Non-indenting comment lines are useful in cases
1511like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001512
1513\ta = b # a very wordy single-line comment that ends up being
1514\t #... continued onto another line
1515
1516\tif a == b:
1517##\t\tprint 'panic!' # old code we've `commented out'
1518\t\treturn a
1519
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001520Since the `#...' and `##' comment lines have a non-whitespace
1521character following the initial `#', Python mode ignores them when
1522computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001523
1524Continuation Lines and Statements
1525
1526The Python-mode commands generally work on statements instead of on
1527individual lines, where a `statement' is a comment or blank line, or a
1528code line and all of its following continuation lines (if any)
1529considered as a single logical unit. The commands in this mode
1530generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531statement containing point, even if point happens to be in the middle
1532of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533
1534
1535@INDENTATION
1536
1537Primarily for entering new code:
1538\t\\[indent-for-tab-command]\t indent line appropriately
1539\t\\[py-newline-and-indent]\t insert newline, then indent
1540\t\\[py-delete-char]\t reduce indentation, or delete single character
1541
1542Primarily for reindenting existing code:
1543\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1544\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1545
1546\t\\[py-indent-region]\t reindent region to match its context
1547\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1548\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1549
1550Unlike most programming languages, Python uses indentation, and only
1551indentation, to specify block structure. Hence the indentation supplied
1552automatically by Python-mode is just an educated guess: only you know
1553the block structure you intend, so only you can supply correct
1554indentation.
1555
1556The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1557the indentation of preceding statements. E.g., assuming
1558py-indent-offset is 4, after you enter
1559\tif a > 0: \\[py-newline-and-indent]
1560the cursor will be moved to the position of the `_' (_ is not a
1561character in the file, it's just used here to indicate the location of
1562the cursor):
1563\tif a > 0:
1564\t _
1565If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1566to
1567\tif a > 0:
1568\t c = d
1569\t _
1570Python-mode cannot know whether that's what you intended, or whether
1571\tif a > 0:
1572\t c = d
1573\t_
1574was your intent. In general, Python-mode either reproduces the
1575indentation of the (closest code or indenting-comment) preceding
1576statement, or adds an extra py-indent-offset blanks if the preceding
1577statement has `:' as its last significant (non-whitespace and non-
1578comment) character. If the suggested indentation is too much, use
1579\\[py-delete-char] to reduce it.
1580
1581Continuation lines are given extra indentation. If you don't like the
1582suggested indentation, change it to something you do like, and Python-
1583mode will strive to indent later lines of the statement in the same way.
1584
1585If a line is a continuation line by virtue of being in an unclosed
1586paren/bracket/brace structure (`list', for short), the suggested
1587indentation depends on whether the current line contains the first item
1588in the list. If it does, it's indented py-indent-offset columns beyond
1589the indentation of the line containing the open bracket. If you don't
1590like that, change it by hand. The remaining items in the list will mimic
1591whatever indentation you give to the first item.
1592
1593If a line is a continuation line because the line preceding it ends with
1594a backslash, the third and following lines of the statement inherit their
1595indentation from the line preceding them. The indentation of the second
1596line in the statement depends on the form of the first (base) line: if
1597the base line is an assignment statement with anything more interesting
1598than the backslash following the leftmost assigning `=', the second line
1599is indented two columns beyond that `='. Else it's indented to two
1600columns beyond the leftmost solid chunk of non-whitespace characters on
1601the base line.
1602
1603Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1604repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1605structure you intend.
1606%c:indent-for-tab-command
1607%c:py-newline-and-indent
1608%c:py-delete-char
1609
1610
1611The next function may be handy when editing code you didn't write:
1612%c:py-guess-indent-offset
1613
1614
1615The remaining `indent' functions apply to a region of Python code. They
1616assume the block structure (equals indentation, in Python) of the region
1617is correct, and alter the indentation in various ways while preserving
1618the block structure:
1619%c:py-indent-region
1620%c:py-shift-region-left
1621%c:py-shift-region-right
1622
1623@MARKING & MANIPULATING REGIONS OF CODE
1624
1625\\[py-mark-block]\t mark block of lines
1626\\[mark-python-def-or-class]\t mark smallest enclosing def
1627\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1628\\[py-comment-region]\t comment out region of code
1629\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1630%c:py-mark-block
1631%c:mark-python-def-or-class
1632%c:py-comment-region
1633
1634@MOVING POINT
1635
1636\\[py-previous-statement]\t move to statement preceding point
1637\\[py-next-statement]\t move to statement following point
1638\\[py-goto-block-up]\t move up to start of current block
1639\\[beginning-of-python-def-or-class]\t move to start of def
1640\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1641\\[end-of-python-def-or-class]\t move to end of def
1642\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1643
1644The first two move to one statement beyond the statement that contains
1645point. A numeric prefix argument tells them to move that many
1646statements instead. Blank lines, comment lines, and continuation lines
1647do not count as `statements' for these commands. So, e.g., you can go
1648to the first code statement in a file by entering
1649\t\\[beginning-of-buffer]\t to move to the top of the file
1650\t\\[py-next-statement]\t to skip over initial comments and blank lines
1651Or do `\\[py-previous-statement]' with a huge prefix argument.
1652%c:py-previous-statement
1653%c:py-next-statement
1654%c:py-goto-block-up
1655%c:beginning-of-python-def-or-class
1656%c:end-of-python-def-or-class
1657
1658@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1659
1660`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1661
1662`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1663overall class and def structure of a module.
1664
1665`\\[back-to-indentation]' moves point to a line's first non-blank character.
1666
1667`\\[indent-relative]' is handy for creating odd indentation.
1668
1669@OTHER EMACS HINTS
1670
1671If you don't like the default value of a variable, change its value to
1672whatever you do like by putting a `setq' line in your .emacs file.
1673E.g., to set the indentation increment to 4, put this line in your
1674.emacs:
1675\t(setq py-indent-offset 4)
1676To see the value of a variable, do `\\[describe-variable]' and enter the variable
1677name at the prompt.
1678
1679When entering a key sequence like `C-c C-n', it is not necessary to
1680release the CONTROL key after doing the `C-c' part -- it suffices to
1681press the CONTROL key, press and release `c' (while still holding down
1682CONTROL), press and release `n' (while still holding down CONTROL), &
1683then release CONTROL.
1684
1685Entering Python mode calls with no arguments the value of the variable
1686`python-mode-hook', if that value exists and is not nil; for backward
1687compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1688the Elisp manual for details.
1689
1690Obscure: When python-mode is first loaded, it looks for all bindings
1691to newline-and-indent in the global keymap, and shadows them with
1692local bindings to py-newline-and-indent."))
1693
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001694
1695;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001696(defvar py-parse-state-re
1697 (concat
1698 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1699 "\\|"
1700 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001701
Barry Warsaw7ae77681994-12-12 20:38:05 +00001702;; returns the parse state at point (see parse-partial-sexp docs)
1703(defun py-parse-state ()
1704 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001705 (let ((here (point))
1706 pps done)
1707 (while (not done)
1708 ;; back up to the first preceding line (if any; else start of
1709 ;; buffer) that begins with a popular Python keyword, or a
1710 ;; non- whitespace and non-comment character. These are good
1711 ;; places to start parsing to see whether where we started is
1712 ;; at a non-zero nesting level. It may be slow for people who
1713 ;; write huge code blocks or huge lists ... tough beans.
1714 (re-search-backward py-parse-state-re nil 'move)
1715 (beginning-of-line)
1716 (save-excursion
1717 (setq pps (parse-partial-sexp (point) here)))
1718 ;; make sure we don't land inside a triple-quoted string
1719 (setq done (or (not (nth 3 pps)) (bobp))))
1720 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001721
1722;; if point is at a non-zero nesting level, returns the number of the
1723;; character that opens the smallest enclosing unclosed list; else
1724;; returns nil.
1725(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001726 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727 (if (zerop (car status))
1728 nil ; not in a nest
1729 (car (cdr status))))) ; char# of open bracket
1730
1731;; t iff preceding line ends with backslash that's not in a comment
1732(defun py-backslash-continuation-line-p ()
1733 (save-excursion
1734 (beginning-of-line)
1735 (and
1736 ;; use a cheap test first to avoid the regexp if possible
1737 ;; use 'eq' because char-after may return nil
1738 (eq (char-after (- (point) 2)) ?\\ )
1739 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001740 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001741 (looking-at py-continued-re))))
1742
1743;; t iff current line is a continuation line
1744(defun py-continuation-line-p ()
1745 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001746 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001747 (or (py-backslash-continuation-line-p)
1748 (py-nesting-level))))
1749
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001750;; go to initial line of current statement; usually this is the line
1751;; we're on, but if we're on the 2nd or following lines of a
1752;; continuation block, we need to go up to the first line of the
1753;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755;; Tricky: We want to avoid quadratic-time behavior for long continued
1756;; blocks, whether of the backslash or open-bracket varieties, or a
1757;; mix of the two. The following manages to do that in the usual
1758;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001759(defun py-goto-initial-line ()
1760 (let ( open-bracket-pos )
1761 (while (py-continuation-line-p)
1762 (beginning-of-line)
1763 (if (py-backslash-continuation-line-p)
1764 (while (py-backslash-continuation-line-p)
1765 (forward-line -1))
1766 ;; else zip out of nested brackets/braces/parens
1767 (while (setq open-bracket-pos (py-nesting-level))
1768 (goto-char open-bracket-pos)))))
1769 (beginning-of-line))
1770
1771;; go to point right beyond final line of current statement; usually
1772;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773;; statement we need to skip over the continuation lines. Tricky:
1774;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001775(defun py-goto-beyond-final-line ()
1776 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778 (while (and (py-continuation-line-p)
1779 (not (eobp)))
1780 ;; skip over the backslash flavor
1781 (while (and (py-backslash-continuation-line-p)
1782 (not (eobp)))
1783 (forward-line 1))
1784 ;; if in nest, zip to the end of the nest
1785 (setq state (py-parse-state))
1786 (if (and (not (zerop (car state)))
1787 (not (eobp)))
1788 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001790 ;; the 3rd argument should be plain 0
1791 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1792 nil state)
1793 (forward-line 1))))))
1794
1795;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001796;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797(defun py-statement-opens-block-p ()
1798 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001799 (let ((start (point))
1800 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1801 (searching t)
1802 (answer nil)
1803 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001804 (goto-char start)
1805 (while searching
1806 ;; look for a colon with nothing after it except whitespace, and
1807 ;; maybe a comment
1808 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1809 finish t)
1810 (if (eq (point) finish) ; note: no `else' clause; just
1811 ; keep searching if we're not at
1812 ; the end yet
1813 ;; sure looks like it opens a block -- but it might
1814 ;; be in a comment
1815 (progn
1816 (setq searching nil) ; search is done either way
1817 (setq state (parse-partial-sexp start
1818 (match-beginning 0)))
1819 (setq answer (not (nth 4 state)))))
1820 ;; search failed: couldn't find another interesting colon
1821 (setq searching nil)))
1822 answer)))
1823
1824;; go to point right beyond final line of block begun by the current
1825;; line. This is the same as where py-goto-beyond-final-line goes
1826;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828(defun py-goto-beyond-block ()
1829 (if (py-statement-opens-block-p)
1830 (py-mark-block nil 'just-move)
1831 (py-goto-beyond-final-line)))
1832
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833;; go to start of first statement (not blank or comment or
1834;; continuation line) at or preceding point. returns t if there is
1835;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001836(defun py-goto-statement-at-or-above ()
1837 (py-goto-initial-line)
1838 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001839 ;; skip back over blank & comment lines
1840 ;; note: will skip a blank or comment line that happens to be
1841 ;; a continuation line too
1842 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1843 (progn (py-goto-initial-line) t)
1844 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001845 t))
1846
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847;; go to start of first statement (not blank or comment or
1848;; continuation line) following the statement containing point returns
1849;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850(defun py-goto-statement-below ()
1851 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853 (py-goto-beyond-final-line)
1854 (while (and
1855 (looking-at py-blank-or-comment-re)
1856 (not (eobp)))
1857 (forward-line 1))
1858 (if (eobp)
1859 (progn (goto-char start) nil)
1860 t)))
1861
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862;; go to start of statement, at or preceding point, starting with
1863;; keyword KEY. Skips blank lines and non-indenting comments upward
1864;; first. If that statement starts with KEY, done, else go back to
1865;; first enclosing block starting with KEY. If successful, leaves
1866;; point at the start of the KEY line & returns t. Else leaves point
1867;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868(defun py-go-up-tree-to-keyword (key)
1869 ;; skip blanks and non-indenting #
1870 (py-goto-initial-line)
1871 (while (and
1872 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1873 (zerop (forward-line -1))) ; go back
1874 nil)
1875 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001876 (let* ((re (concat "[ \t]*" key "\\b"))
1877 (case-fold-search nil) ; let* so looking-at sees this
1878 (found (looking-at re))
1879 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880 (while (not (or found dead))
1881 (condition-case nil ; in case no enclosing block
1882 (py-goto-block-up 'no-mark)
1883 (error (setq dead t)))
1884 (or dead (setq found (looking-at re))))
1885 (beginning-of-line)
1886 found))
1887
1888;; return string in buffer from start of indentation to end of line;
1889;; prefix "..." if leading whitespace was skipped
1890(defun py-suck-up-leading-text ()
1891 (save-excursion
1892 (back-to-indentation)
1893 (concat
1894 (if (bolp) "" "...")
1895 (buffer-substring (point) (progn (end-of-line) (point))))))
1896
1897;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1898;; as a Lisp symbol; return nil if none
1899(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001901 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1902 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1903 nil)))
1904
1905(defun py-make-temp-name ()
1906 (make-temp-name
1907 (concat (file-name-as-directory py-temp-directory) "python")))
1908
1909(defun py-delete-file-silently (fname)
1910 (condition-case nil
1911 (delete-file fname)
1912 (error nil)))
1913
1914(defun py-kill-emacs-hook ()
1915 ;; delete our temp files
1916 (while py-file-queue
1917 (py-delete-file-silently (car py-file-queue))
1918 (setq py-file-queue (cdr py-file-queue)))
1919 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1920 ;; run the hook we inherited, if any
1921 (and py-inherited-kill-emacs-hook
1922 (funcall py-inherited-kill-emacs-hook))))
1923
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924;; make PROCESS's buffer visible, append STRING to it, and force
1925;; display; also make shell-mode believe the user typed this string,
1926;; so that kill-output-from-shell and show-output-from-shell work
1927;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001928(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929 (let ((cbuf (current-buffer))
1930 (pbuf (process-buffer process))
1931 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932 (set-buffer pbuf)
1933 (goto-char (point-max))
1934 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001935 (if (not (or py-this-is-emacs-19-p
1936 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937 (move-marker last-input-start (point))) ; muck w/ shell-mode
1938 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001939 (if (not (or py-this-is-emacs-19-p
1940 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941 (move-marker last-input-end (point))) ; muck w/ shell-mode
1942 (set-buffer cbuf))
1943 (sit-for 0))
1944
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001945(defun py-keep-region-active ()
1946 ;; do whatever is necessary to keep the region active in XEmacs.
1947 ;; Ignore byte-compiler warnings you might see. Also note that
1948 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1949 ;; require us to take explicit action.
1950 (and (boundp 'zmacs-region-stays)
1951 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001952
1953
Barry Warsaw850437a1995-03-08 21:50:28 +00001954(defconst py-version "$Revision$"
1955 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001956(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001957 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001958
Barry Warsaw850437a1995-03-08 21:50:28 +00001959(defun py-version ()
1960 "Echo the current version of `python-mode' in the minibuffer."
1961 (interactive)
1962 (message "Using `python-mode' version %s" py-version)
1963 (py-keep-region-active))
1964
1965;; only works under Emacs 19
1966;(eval-when-compile
1967; (require 'reporter))
1968
1969(defun py-submit-bug-report (enhancement-p)
1970 "Submit via mail a bug report on `python-mode'.
1971With \\[universal-argument] just submit an enhancement request."
1972 (interactive
1973 (list (not (y-or-n-p
1974 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001975 (let ((reporter-prompt-for-summary-p (if enhancement-p
1976 "(Very) brief summary: "
1977 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001978 (require 'reporter)
1979 (reporter-submit-bug-report
1980 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001981 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001982 ;; varlist
1983 (if enhancement-p nil
1984 '(py-python-command
1985 py-indent-offset
1986 py-block-comment-prefix
1987 py-scroll-process-buffer
1988 py-temp-directory
1989 py-beep-if-tab-change))
1990 nil ;pre-hooks
1991 nil ;post-hooks
1992 "Dear Barry,") ;salutation
1993 (if enhancement-p nil
1994 (set-mark (point))
1995 (insert
1996"Please replace this text with a sufficiently large code sample\n\
1997and an exact recipe so that I can reproduce your problem. Failure\n\
1998to do so may mean a greater delay in fixing your bug.\n\n")
1999 (exchange-point-and-mark)
2000 (py-keep-region-active))))
2001
2002
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002003;; arrange to kill temp files when Emacs exists
2004(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2005 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2006 ;; have to trust that other people are as respectful of our hook
2007 ;; fiddling as we are of theirs
2008 (if (boundp 'py-inherited-kill-emacs-hook)
2009 ;; we were loaded before -- trust others not to have screwed us
2010 ;; in the meantime (no choice, really)
2011 nil
2012 ;; else arrange for our hook to run theirs
2013 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2014 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2015
2016
2017
2018(provide 'python-mode)
2019;;; python-mode.el ends here