blob: 854e3f945c9e8bf41d6edc1648a3f05c8988eedd [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw4669d7e1996-03-22 16:13:24 +00005;; Author: 1995-1996 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
22;; by Tim Peters <tim@ksr.com> after an original idea by Michael
23;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000024;; (Barry) have undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
27;; line with GNU Emacs Lisp coding standards. But all in all, the
Barry Warsaw4669d7e1996-03-22 16:13:24 +000028;; mode works exceedingly well, and I've simply been tweeking it as I
29;; go along. Ain't it wonderful that Python has a much more sane
30;; syntax than C? (or <shudder> C++?! :-).
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031
32;; The following statements, placed in your .emacs file or
33;; site-init.el, will cause this file to be autoloaded, and
34;; python-mode invoked, when visiting .py files (assuming this file is
35;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000037;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;; (setq auto-mode-alist
39;; (cons '("\\.py$" . python-mode) auto-mode-alist))
40
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000041;; Here's a brief list of recent additions/improvements:
42;;
43;; - Wrapping and indentation within triple quote strings should work
44;; properly now.
45;; - `Standard' bug reporting mechanism (use C-c C-b)
46;; - py-mark-block was moved to C-c C-m
47;; - C-c C-v shows you the python-mode version
48;; - a basic python-font-lock-keywords has been added for Emacs 19
49;; font-lock colorizations.
50;; - proper interaction with pending-del and del-sel modes.
51;; - New py-electric-colon (:) command for improved outdenting. Also
52;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +000053;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000054
Barry Warsaw7b0f5681995-03-08 21:33:04 +000055;; Here's a brief to do list:
56;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000057;; - Better integration with gud-mode for debugging.
58;; - Rewrite according to GNU Emacs Lisp standards.
59;; - py-delete-char should obey numeric arguments.
60;; - even better support for outdenting. Guido suggests outdents of
61;; at least one level after a return, raise, break, or continue
62;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000063;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; If you can think of more things you'd like to see, drop me a line.
66;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
67;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000068;; Note that I only test things on XEmacs. If you port stuff to FSF
69;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
70;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsaw7b0f5681995-03-08 21:33:04 +000072;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000073;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000074;; |Major mode for editing Python programs
75;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000076
Barry Warsaw7b0f5681995-03-08 21:33:04 +000077;;; Code:
78
79
80;; user definable variables
81;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000082
83(defvar py-python-command "python"
84 "*Shell command used to start Python interpreter.")
85
Barry Warsaw17914f41995-11-03 18:25:15 +000086(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000087 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000088Note that `\\[py-guess-indent-offset]' can usually guess a good value
89when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000090
Barry Warsaw095e9c61995-09-19 20:01:42 +000091(defvar py-align-multiline-strings-p t
92 "*Flag describing how multiline triple quoted strings are aligned.
93When this flag is non-nil, continuation lines are lined up under the
94preceding line's indentation. When this flag is nil, continuation
95lines are aligned to column zero.")
96
Barry Warsaw7ae77681994-12-12 20:38:05 +000097(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +000098 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000099This should follow the convention for non-indenting comment lines so
100that the indentation commands won't get confused (i.e., the string
101should be of the form `#x...' where `x' is not a blank or a tab, and
102`...' is arbitrary).")
103
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000104(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000105 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000106
Barry Warsaw6d627751996-03-06 18:41:38 +0000107When nil, all comment lines are skipped for indentation purposes, and
108in Emacs 19, a faster algorithm is used.
109
110When t, lines that begin with a single `#' are a hint to subsequent
111line indentation. If the previous line is such a comment line (as
112opposed to one that starts with `py-block-comment-prefix'), then it's
113indentation is used as a hint for this line's indentation. Lines that
114begin with `py-block-comment-prefix' are ignored for indentation
115purposes.
116
117When not nil or t, comment lines that begin with a `#' are used as
118indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000119
Barry Warsaw7ae77681994-12-12 20:38:05 +0000120(defvar py-scroll-process-buffer t
121 "*Scroll Python process buffer as output arrives.
122If nil, the Python process buffer acts, with respect to scrolling, like
123Shell-mode buffers normally act. This is surprisingly complicated and
124so won't be explained here; in fact, you can't get the whole story
125without studying the Emacs C code.
126
127If non-nil, the behavior is different in two respects (which are
128slightly inaccurate in the interest of brevity):
129
130 - If the buffer is in a window, and you left point at its end, the
131 window will scroll as new output arrives, and point will move to the
132 buffer's end, even if the window is not the selected window (that
133 being the one the cursor is in). The usual behavior for shell-mode
134 windows is not to scroll, and to leave point where it was, if the
135 buffer is in a window other than the selected window.
136
137 - If the buffer is not visible in any window, and you left point at
138 its end, the buffer will be popped into a window as soon as more
139 output arrives. This is handy if you have a long-running
140 computation and don't want to tie up screen area waiting for the
141 output. The usual behavior for a shell-mode buffer is to stay
142 invisible until you explicitly visit it.
143
144Note the `and if you left point at its end' clauses in both of the
145above: you can `turn off' the special behaviors while output is in
146progress, by visiting the Python buffer and moving point to anywhere
147besides the end. Then the buffer won't scroll, point will remain where
148you leave it, and if you hide the buffer it will stay hidden until you
149visit it again. You can enable and disable the special behaviors as
150often as you like, while output is in progress, by (respectively) moving
151point to, or away from, the end of the buffer.
152
153Warning: If you expect a large amount of output, you'll probably be
154happier setting this option to nil.
155
156Obscure: `End of buffer' above should really say `at or beyond the
157process mark', but if you know what that means you didn't need to be
158told <grin>.")
159
160(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000161 (let ((ok '(lambda (x)
162 (and x
163 (setq x (expand-file-name x)) ; always true
164 (file-directory-p x)
165 (file-writable-p x)
166 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000167 (or (funcall ok (getenv "TMPDIR"))
168 (funcall ok "/usr/tmp")
169 (funcall ok "/tmp")
170 (funcall ok ".")
171 (error
172 "Couldn't find a usable temp directory -- set py-temp-directory")))
173 "*Directory used for temp files created by a *Python* process.
174By default, the first directory from this list that exists and that you
175can write into: the value (if any) of the environment variable TMPDIR,
176/usr/tmp, /tmp, or the current directory.")
177
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000178(defvar py-beep-if-tab-change t
179 "*Ring the bell if tab-width is changed.
180If a comment of the form
181
182 \t# vi:set tabsize=<number>:
183
184is found before the first code line when the file is entered, and the
185current value of (the general Emacs variable) `tab-width' does not
186equal <number>, `tab-width' is set to <number>, a message saying so is
187displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
188the Emacs bell is also rung as a warning.")
189
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000190(defconst python-font-lock-keywords
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000191 (let* ((keywords '("access" "and" "break" "continue"
192 "del" "elif" "else:" "except"
193 "except:" "exec" "finally:" "for"
194 "from" "global" "if" "import"
195 "in" "is" "lambda" "not"
196 "or" "pass" "print" "raise"
197 "return" "try:" "while"
198 ))
199 (kwregex (mapconcat 'identity keywords "\\|")))
200 (list
201 ;; keywords not at beginning of line
202 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
203 ;; keywords at beginning of line. i don't think regexps are
204 ;; powerful enough to handle these two cases in one regexp.
205 ;; prove me wrong!
206 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
207 ;; classes
208 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
209 1 font-lock-type-face)
210 ;; functions
211 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
212 1 font-lock-function-name-face)
213 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000214 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000215
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000216
217;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
218;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
219
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000220(make-variable-buffer-local 'py-indent-offset)
221
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000222;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
223;; seems to be the standard way of checking this.
224;; BAW - This is *not* the right solution. When at all possible,
225;; instead of testing for the version of Emacs, use feature tests.
226
227(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
228(setq py-this-is-emacs-19-p
229 (and
230 (not py-this-is-lucid-emacs-p)
231 (string-match "^19\\." emacs-version)))
232
Barry Warsaw7ae77681994-12-12 20:38:05 +0000233;; have to bind py-file-queue before installing the kill-emacs hook
234(defvar py-file-queue nil
235 "Queue of Python temp files awaiting execution.
236Currently-active file is at the head of the list.")
237
238;; define a mode-specific abbrev table for those who use such things
239(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000240 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000241(define-abbrev-table 'python-mode-abbrev-table nil)
242
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243(defvar python-mode-hook nil
244 "*Hook called by `python-mode'.")
245
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000246;; in previous version of python-mode.el, the hook was incorrectly
247;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000248(and (fboundp 'make-obsolete-variable)
249 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
250
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000251(defvar py-mode-map ()
252 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253
Barry Warsaw7ae77681994-12-12 20:38:05 +0000254(if py-mode-map
255 ()
256 (setq py-mode-map (make-sparse-keymap))
257
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000258 ;; shadow global bindings for newline-and-indent w/ the py- version.
259 ;; BAW - this is extremely bad form, but I'm not going to change it
260 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261 (mapcar (function (lambda (key)
262 (define-key
263 py-mode-map key 'py-newline-and-indent)))
264 (where-is-internal 'newline-and-indent))
265
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000266 ;; BAW - you could do it this way, but its not considered proper
267 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000268 (mapcar (function
269 (lambda (x)
270 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000271 '((":" . py-electric-colon)
272 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000273 ("\C-c|" . py-execute-region)
274 ("\C-c!" . py-shell)
275 ("\177" . py-delete-char)
276 ("\n" . py-newline-and-indent)
277 ("\C-c:" . py-guess-indent-offset)
278 ("\C-c\t" . py-indent-region)
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000279 ("\C-c\C-l" . py-outdent-left)
280 ("\C-c\C-r" . py-indent-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000281 ("\C-c<" . py-shift-region-left)
282 ("\C-c>" . py-shift-region-right)
283 ("\C-c\C-n" . py-next-statement)
284 ("\C-c\C-p" . py-previous-statement)
285 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000286 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000287 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000288 ("\C-c?" . py-describe-mode)
289 ("\C-c\C-hm" . py-describe-mode)
290 ("\e\C-a" . beginning-of-python-def-or-class)
291 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000292 ( "\e\C-h" . mark-python-def-or-class)))
293 ;; should do all keybindings this way
294 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
295 (define-key py-mode-map "\C-c\C-v" 'py-version)
296 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000297
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298(defvar py-mode-syntax-table nil
299 "Syntax table used in `python-mode' buffers.")
300
Barry Warsaw7ae77681994-12-12 20:38:05 +0000301(if py-mode-syntax-table
302 ()
303 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000304 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000305 (mapcar (function
306 (lambda (x) (modify-syntax-entry
307 (car x) (cdr x) py-mode-syntax-table)))
308 '(( ?\( . "()" ) ( ?\) . ")(" )
309 ( ?\[ . "(]" ) ( ?\] . ")[" )
310 ( ?\{ . "(}" ) ( ?\} . "){" )
311 ;; fix operator symbols misassigned in the std table
312 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
313 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
314 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
315 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw2bbe49b1995-10-18 14:41:12 +0000316 ( ?\_ . "_" ) ; underscore is legit in symbols, but not words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000317 ( ?\' . "\"") ; single quote is string quote
318 ( ?\" . "\"" ) ; double quote is string quote too
319 ( ?\` . "$") ; backquote is open and close paren
320 ( ?\# . "<") ; hash starts comment
321 ( ?\n . ">")))) ; newline ends comment
322
323(defconst py-stringlit-re
324 (concat
325 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
326 "\\|" ; or
327 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000328 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000329
330;; this is tricky because a trailing backslash does not mean
331;; continuation if it's in a comment
332(defconst py-continued-re
333 (concat
334 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
335 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000336 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000337
338(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000339 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000340
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000341(defconst py-outdent-re
342 (concat "\\(" (mapconcat 'identity
343 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000344 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000345 "finally:"
346 "elif\\s +.*:")
347 "\\|")
348 "\\)")
349 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000350
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000351(defconst py-no-outdent-re
352 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000353 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000354 "except\\(\\s +.*\\)?:"
355 "while\\s +.*:"
356 "for\\s +.*:"
357 "if\\s +.*:"
358 "elif\\s +.*:")
359 "\\|")
360 "\\)")
361 "Regexp matching lines to not outdent after.")
362
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000363
364;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365(defun python-mode ()
366 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000367To submit a problem report, enter `\\[py-submit-bug-report]' from a
368`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
369documentation. To see what version of `python-mode' you are running,
370enter `\\[py-version]'.
371
372This mode knows about Python indentation, tokens, comments and
373continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000374
375COMMANDS
376\\{py-mode-map}
377VARIABLES
378
379py-indent-offset\tindentation increment
380py-block-comment-prefix\tcomment string used by py-comment-region
381py-python-command\tshell command to invoke Python interpreter
382py-scroll-process-buffer\talways scroll Python process buffer
383py-temp-directory\tdirectory used for temp files (if needed)
384py-beep-if-tab-change\tring the bell if tab-width is changed"
385 (interactive)
386 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000388 (setq major-mode 'python-mode
389 mode-name "Python"
390 local-abbrev-table python-mode-abbrev-table)
391 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000392 ;; Emacs 19 requires this
393 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
394 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000395 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000396 (mapcar (function (lambda (x)
397 (make-local-variable (car x))
398 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399 '((paragraph-separate . "^[ \t]*$")
400 (paragraph-start . "^[ \t]*$")
401 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000402 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000403 (comment-start-skip . "# *")
404 (comment-column . 40)
405 (indent-region-function . py-indent-region)
406 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000407 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000408 ;;
409 ;; not sure where the magic comment has to be; to save time
410 ;; searching for a rarity, we give up if it's not found prior to the
411 ;; first executable statement.
412 ;;
413 ;; BAW - on first glance, this seems like complete hackery. Why was
414 ;; this necessary, and is it still necessary?
415 (let ((case-fold-search nil)
416 (start (point))
417 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000418 (if (re-search-forward
419 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
420 (prog2 (py-next-statement 1) (point) (goto-char 1))
421 t)
422 (progn
423 (setq new-tab-width
424 (string-to-int
425 (buffer-substring (match-beginning 1) (match-end 1))))
426 (if (= tab-width new-tab-width)
427 nil
428 (setq tab-width new-tab-width)
429 (message "Caution: tab-width changed to %d" new-tab-width)
430 (if py-beep-if-tab-change (beep)))))
431 (goto-char start))
432
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000433 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000434 (if python-mode-hook
435 (run-hooks 'python-mode-hook)
436 (run-hooks 'py-mode-hook)))
437
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000438
Barry Warsaw826255b1996-03-22 16:09:34 +0000439(defun py-keep-region-active ()
440 ;; Do whatever is necessary to keep the region active in
441 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
442 ;; ignore byte-compiler warnings you might see.
443 (and (boundp 'zmacs-region-stays)
444 (setq zmacs-region-stays t)))
445
Barry Warsawb91b7431995-03-14 15:55:20 +0000446;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000447(defun py-outdent-p ()
448 ;; returns non-nil if the current line should outdent one level
449 (save-excursion
450 (and (progn (back-to-indentation)
451 (looking-at py-outdent-re))
452 (progn (backward-to-indentation 1)
453 (while (or (looking-at py-blank-or-comment-re)
454 (bobp))
455 (backward-to-indentation 1))
456 (not (looking-at py-no-outdent-re)))
457 )))
458
459
Barry Warsawb91b7431995-03-14 15:55:20 +0000460(defun py-electric-colon (arg)
461 "Insert a colon.
462In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000463argument is provided, that many colons are inserted non-electrically.
464Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000465 (interactive "P")
466 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000467 ;; are we in a string or comment?
468 (if (save-excursion
469 (let ((pps (parse-partial-sexp (save-excursion
470 (beginning-of-python-def-or-class)
471 (point))
472 (point))))
473 (not (or (nth 3 pps) (nth 4 pps)))))
474 (save-excursion
475 (let ((here (point))
476 (outdent 0)
477 (indent (py-compute-indentation)))
478 (if (and (not arg)
479 (py-outdent-p)
480 (= indent (save-excursion
481 (forward-line -1)
482 (py-compute-indentation)))
483 )
484 (setq outdent py-indent-offset))
485 ;; Don't indent, only outdent. This assumes that any lines that
486 ;; are already outdented relative to py-compute-indentation were
487 ;; put there on purpose. Its highly annoying to have `:' indent
488 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
489 ;; there a better way to determine this???
490 (if (< (current-indentation) indent) nil
491 (goto-char here)
492 (beginning-of-line)
493 (delete-horizontal-space)
494 (indent-to (- indent outdent))
495 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000496
Barry Warsaw826255b1996-03-22 16:09:34 +0000497(defun py-indent-right (start end arg)
498 "Indent lines in the region by one `py-indent-offset' level.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000499With numeric arg, indent by that many levels. You cannot indent
500farther right than the distance the line would be indented by
Barry Warsaw826255b1996-03-22 16:09:34 +0000501\\[py-indent-line]. With no active region, indent only the
502current line."
503 (interactive
504 (let ((p (point))
505 (m (mark)))
506 (list (min p m) (max p m) (prefix-numeric-value current-prefix-arg))))
507 (let ((pos (- (point-max) (point)))
508 (end (save-excursion
509 (goto-char (or end (1+ start)))
510 (and (not (bolp))
511 (forward-line 1))
512 (set-marker (make-marker) (point))))
513 col want indent)
514 (goto-char start)
515 (beginning-of-line)
516 (unwind-protect
517 (while (< (point) end)
518 (setq col (current-indentation)
519 want (* arg py-indent-offset)
520 indent (py-compute-indentation))
521 (if (<= (+ col want) indent)
522 (progn
523 (beginning-of-line)
524 (delete-horizontal-space)
525 (indent-to (+ col want))))
526 (forward-line 1))
527 (set-marker end nil))
528 (goto-char (- (point-max) pos))
529 (py-keep-region-active)))
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000530
Barry Warsaw826255b1996-03-22 16:09:34 +0000531(defun py-outdent-left (start end arg)
532 "Outdent lines in the region by one `py-indent-offset' level.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000533With numeric arg, outdent by that many levels. You cannot outdent
Barry Warsaw826255b1996-03-22 16:09:34 +0000534farther left than column zero. With no active region, outdent only
535the current line."
536 (interactive
537 (let ((p (point))
538 (m (mark)))
539 (list (min p m) (max p m) (prefix-numeric-value current-prefix-arg))))
540 (let ((pos (- (point-max) (point)))
541 (end (save-excursion
542 (goto-char (or end (1+ start)))
543 (and (not (bolp))
544 (forward-line 1))
545 (set-marker (make-marker) (point))))
546 col want)
547 (goto-char start)
548 (beginning-of-line)
549 (unwind-protect
550 (while (< (point) end)
551 (setq col (current-indentation)
552 want (* arg py-indent-offset))
553 (if (<= 0 (- col want))
554 (progn
555 (beginning-of-line)
556 (delete-horizontal-space)
557 (indent-to (- col want))))
558 (forward-line 1))
559 (set-marker end nil))
560 (goto-char (- (point-max) pos))
561 (py-keep-region-active)))
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000562
Barry Warsawb91b7431995-03-14 15:55:20 +0000563
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000565(defun py-shell ()
566 "Start an interactive Python interpreter in another window.
567This is like Shell mode, except that Python is running in the window
568instead of a shell. See the `Interactive Shell' and `Shell Mode'
569sections of the Emacs manual for details, especially for the key
570bindings active in the `*Python*' buffer.
571
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000572See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000573behavior in the process window.
574
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000575Warning: Don't use an interactive Python if you change sys.ps1 or
576sys.ps2 from their default values, or if you're running code that
577prints `>>> ' or `... ' at the start of a line. `python-mode' can't
578distinguish your output from Python's output, and assumes that `>>> '
579at the start of a line is a prompt from Python. Similarly, the Emacs
580Shell mode code assumes that both `>>> ' and `... ' at the start of a
581line are Python prompts. Bad things can happen if you fool either
582mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000583
584Warning: If you do any editing *in* the process buffer *while* the
585buffer is accepting output from Python, do NOT attempt to `undo' the
586changes. Some of the output (nowhere near the parts you changed!) may
587be lost if you do. This appears to be an Emacs bug, an unfortunate
588interaction between undo and process filters; the same problem exists in
589non-Python process buffers using the default (Emacs-supplied) process
590filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000591 ;; BAW - should undo be disabled in the python process buffer, if
592 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000593 (interactive)
594 (if py-this-is-emacs-19-p
595 (progn
596 (require 'comint)
597 (switch-to-buffer-other-window
598 (make-comint "Python" py-python-command)))
599 (progn
600 (require 'shell)
601 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000602 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000603 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000604 (make-local-variable 'shell-prompt-pattern)
605 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
606 (set-process-filter (get-buffer-process (current-buffer))
607 'py-process-filter)
608 (set-syntax-table py-mode-syntax-table))
609
610(defun py-execute-region (start end)
611 "Send the region between START and END to a Python interpreter.
612If there is a *Python* process it is used.
613
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000614Hint: If you want to execute part of a Python file several times
615\(e.g., perhaps you're developing a function and want to flesh it out
616a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
617the region of interest, and send the code to a *Python* process via
618`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000619
620Following are subtleties to note when using a *Python* process:
621
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000622If a *Python* process is used, the region is copied into a temporary
623file (in directory `py-temp-directory'), and an `execfile' command is
624sent to Python naming that file. If you send regions faster than
625Python can execute them, `python-mode' will save them into distinct
626temp files, and execute the next one in the queue the next time it
627sees a `>>> ' prompt from Python. Each time this happens, the process
628buffer is popped into a window (if it's not already in some window) so
629you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000631 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000632
633is inserted at the end.
634
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000635Caution: No more than 26 regions can be pending at any given time.
636This limit is (indirectly) inherited from libc's mktemp(3).
637`python-mode' does not try to protect you from exceeding the limit.
638It's extremely unlikely that you'll get anywhere close to the limit in
639practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000640
641See the `\\[py-shell]' docs for additional warnings."
642 (interactive "r")
643 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000644 (let ((pyproc (get-process "Python"))
645 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000646 (if (null pyproc)
647 (shell-command-on-region start end py-python-command)
648 ;; else feed it thru a temp file
649 (setq fname (py-make-temp-name))
650 (write-region start end fname nil 'no-msg)
651 (setq py-file-queue (append py-file-queue (list fname)))
652 (if (cdr py-file-queue)
653 (message "File %s queued for execution" fname)
654 ;; else
655 (py-execute-file pyproc fname)))))
656
657(defun py-execute-file (pyproc fname)
658 (py-append-to-process-buffer
659 pyproc
660 (format "## working on region in file %s ...\n" fname))
661 (process-send-string pyproc (format "execfile('%s')\n" fname)))
662
663(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000664 (let ((curbuf (current-buffer))
665 (pbuf (process-buffer pyproc))
666 (pmark (process-mark pyproc))
667 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000668
669 ;; make sure we switch to a different buffer at least once. if we
670 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000671 ;; window, and point is before the end, and lots of output is
672 ;; coming at a fast pace, then (a) simple cursor-movement commands
673 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
674 ;; to have a visible effect (the window just doesn't get updated,
675 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
676 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000677 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000678 ;; #b makes no sense to me at all. #a almost makes sense: unless
679 ;; we actually change buffers, set_buffer_internal in buffer.c
680 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
681 ;; seems to make the Emacs command loop reluctant to update the
682 ;; display. Perhaps the default process filter in process.c's
683 ;; read_process_output has update_mode_lines++ for a similar
684 ;; reason? beats me ...
685
686 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000687 (if (eq curbuf pbuf) ; mysterious ugly hack
688 (set-buffer (get-buffer-create "*scratch*")))
689
690 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000691 (let* ((start (point))
692 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000693 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000694 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000695 (goto-char pmark)
696 (insert string)
697 (move-marker pmark (point))
698 (setq file-finished
699 (and py-file-queue
700 (equal ">>> "
701 (buffer-substring
702 (prog2 (beginning-of-line) (point)
703 (goto-char pmark))
704 (point)))))
705 (if goback (goto-char start)
706 ;; else
707 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708 (let* ((pop-up-windows t)
709 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000710 (set-window-point pwin (point)))))
711 (set-buffer curbuf)
712 (if file-finished
713 (progn
714 (py-delete-file-silently (car py-file-queue))
715 (setq py-file-queue (cdr py-file-queue))
716 (if py-file-queue
717 (py-execute-file pyproc (car py-file-queue)))))
718 (and goend
719 (progn (set-buffer pbuf)
720 (goto-char (point-max))))
721 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000722
723(defun py-execute-buffer ()
724 "Send the contents of the buffer to a Python interpreter.
725If there is a *Python* process buffer it is used. If a clipping
726restriction is in effect, only the accessible portion of the buffer is
727sent. A trailing newline will be supplied if needed.
728
729See the `\\[py-execute-region]' docs for an account of some subtleties."
730 (interactive)
731 (py-execute-region (point-min) (point-max)))
732
733
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000734
735;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000736(defun py-delete-char ()
737 "Reduce indentation or delete character.
738If point is at the leftmost column, deletes the preceding newline.
739
740Else if point is at the leftmost non-blank character of a line that is
741neither a continuation line nor a non-indenting comment line, or if
742point is at the end of a blank line, reduces the indentation to match
743that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000744opened the block is displayed in the echo area to help you keep track
745of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746
747Else the preceding character is deleted, converting a tab to spaces if
748needed so that only a single column position is deleted."
749 (interactive "*")
750 (if (or (/= (current-indentation) (current-column))
751 (bolp)
752 (py-continuation-line-p)
753 (looking-at "#[^ \t\n]")) ; non-indenting #
754 (backward-delete-char-untabify 1)
755 ;; else indent the same as the colon line that opened the block
756
757 ;; force non-blank so py-goto-block-up doesn't ignore it
758 (insert-char ?* 1)
759 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000760 (let ((base-indent 0) ; indentation of base line
761 (base-text "") ; and text of base line
762 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000763 (condition-case nil ; in case no enclosing block
764 (save-excursion
765 (py-goto-block-up 'no-mark)
766 (setq base-indent (current-indentation)
767 base-text (py-suck-up-leading-text)
768 base-found-p t))
769 (error nil))
770 (delete-char 1) ; toss the dummy character
771 (delete-horizontal-space)
772 (indent-to base-indent)
773 (if base-found-p
774 (message "Closes block: %s" base-text)))))
775
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000776;; required for pending-del and delsel modes
777(put 'py-delete-char 'delete-selection 'supersede)
778(put 'py-delete-char 'pending-delete 'supersede)
779
Barry Warsaw7ae77681994-12-12 20:38:05 +0000780(defun py-indent-line ()
781 "Fix the indentation of the current line according to Python rules."
782 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000783 (let* ((ci (current-indentation))
784 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000785 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000786 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000787 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000788 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000789 (if (/= ci need)
790 (save-excursion
791 (beginning-of-line)
792 (delete-horizontal-space)
793 (indent-to need)))
794 (if move-to-indentation-p (back-to-indentation))))
795
796(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000797 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000798This is just `strives to' because correct indentation can't be computed
799from scratch for Python code. In general, deletes the whitespace before
800point, inserts a newline, and takes an educated guess as to how you want
801the new line indented."
802 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000803 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000804 (if (< ci (current-column)) ; if point beyond indentation
805 (newline-and-indent)
806 ;; else try to act like newline-and-indent "normally" acts
807 (beginning-of-line)
808 (insert-char ?\n 1)
809 (move-to-column ci))))
810
811(defun py-compute-indentation ()
812 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000813 (let ((pps (parse-partial-sexp (save-excursion
814 (beginning-of-python-def-or-class)
815 (point))
816 (point))))
817 (beginning-of-line)
818 (cond
819 ;; are we inside a string or comment?
820 ((or (nth 3 pps) (nth 4 pps))
821 (save-excursion
822 (if (not py-align-multiline-strings-p) 0
823 ;; skip back over blank & non-indenting comment lines
824 ;; note: will skip a blank or non-indenting comment line
825 ;; that happens to be a continuation line too
826 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
827 (back-to-indentation)
828 (current-column))))
829 ;; are we on a continuation line?
830 ((py-continuation-line-p)
831 (let ((startpos (point))
832 (open-bracket-pos (py-nesting-level))
833 endpos searching found)
834 (if open-bracket-pos
835 (progn
836 ;; align with first item in list; else a normal
837 ;; indent beyond the line with the open bracket
838 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
839 ;; is the first list item on the same line?
840 (skip-chars-forward " \t")
841 (if (null (memq (following-char) '(?\n ?# ?\\)))
842 ; yes, so line up with it
843 (current-column)
844 ;; first list item on another line, or doesn't exist yet
845 (forward-line 1)
846 (while (and (< (point) startpos)
847 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
848 (forward-line 1))
849 (if (< (point) startpos)
850 ;; again mimic the first list item
851 (current-indentation)
852 ;; else they're about to enter the first item
853 (goto-char open-bracket-pos)
854 (+ (current-indentation) py-indent-offset))))
855
856 ;; else on backslash continuation line
857 (forward-line -1)
858 (if (py-continuation-line-p) ; on at least 3rd line in block
859 (current-indentation) ; so just continue the pattern
860 ;; else started on 2nd line in block, so indent more.
861 ;; if base line is an assignment with a start on a RHS,
862 ;; indent to 2 beyond the leftmost "="; else skip first
863 ;; chunk of non-whitespace characters on base line, + 1 more
864 ;; column
865 (end-of-line)
866 (setq endpos (point) searching t)
867 (back-to-indentation)
868 (setq startpos (point))
869 ;; look at all "=" from left to right, stopping at first
870 ;; one not nested in a list or string
871 (while searching
872 (skip-chars-forward "^=" endpos)
873 (if (= (point) endpos)
874 (setq searching nil)
875 (forward-char 1)
876 (setq state (parse-partial-sexp startpos (point)))
877 (if (and (zerop (car state)) ; not in a bracket
878 (null (nth 3 state))) ; & not in a string
879 (progn
880 (setq searching nil) ; done searching in any case
881 (setq found
882 (not (or
883 (eq (following-char) ?=)
884 (memq (char-after (- (point) 2))
885 '(?< ?> ?!)))))))))
886 (if (or (not found) ; not an assignment
887 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
888 (progn
889 (goto-char startpos)
890 (skip-chars-forward "^ \t\n")))
891 (1+ (current-column))))))
892
893 ;; not on a continuation line
894
895 ;; if at start of restriction, or on a non-indenting comment
896 ;; line, assume they intended whatever's there
897 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
898 (current-indentation))
899
900 ;; else indentation based on that of the statement that
901 ;; precedes us; use the first line of that statement to
902 ;; establish the base, in case the user forced a non-std
903 ;; indentation for the continuation lines (if any)
904 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000905 ;; skip back over blank & non-indenting comment lines note:
906 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000907 ;; happens to be a continuation line too. use fast Emacs 19
908 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000909 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000910 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000911 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000912 (let (done)
913 (while (not done)
914 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
915 nil 'move)
916 (setq done (or (eq py-honor-comment-indentation t)
917 (bobp)
918 (/= (following-char) ?#)
919 (not (zerop (current-column)))))
920 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000921 ;; if we landed inside a string, go to the beginning of that
922 ;; string. this handles triple quoted, multi-line spanning
923 ;; strings.
924 (py-goto-initial-line)
925 (if (py-statement-opens-block-p)
926 (+ (current-indentation) py-indent-offset)
927 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000928
929(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000930 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000931By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000932`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000933Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000934`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935their own buffer-local copy), both those currently existing and those
936created later in the Emacs session.
937
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000938Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000939There's no excuse for such foolishness, but sometimes you have to deal
940with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000941`py-indent-offset' to what it thinks it was when they created the
942mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000943
944Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945looking for a line that opens a block of code. `py-indent-offset' is
946set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000947statement following it. If the search doesn't succeed going forward,
948it's tried again going backward."
949 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000950 (let (new-value
951 (start (point))
952 restart
953 (found nil)
954 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000955 (py-goto-initial-line)
956 (while (not (or found (eobp)))
957 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
958 (progn
959 (setq restart (point))
960 (py-goto-initial-line)
961 (if (py-statement-opens-block-p)
962 (setq found t)
963 (goto-char restart)))))
964 (if found
965 ()
966 (goto-char start)
967 (py-goto-initial-line)
968 (while (not (or found (bobp)))
969 (setq found
970 (and
971 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
972 (or (py-goto-initial-line) t) ; always true -- side effect
973 (py-statement-opens-block-p)))))
974 (setq colon-indent (current-indentation)
975 found (and found (zerop (py-next-statement 1)))
976 new-value (- (current-indentation) colon-indent))
977 (goto-char start)
978 (if found
979 (progn
980 (funcall (if global 'kill-local-variable 'make-local-variable)
981 'py-indent-offset)
982 (setq py-indent-offset new-value)
983 (message "%s value of py-indent-offset set to %d"
984 (if global "Global" "Local")
985 py-indent-offset))
986 (error "Sorry, couldn't guess a value for py-indent-offset"))))
987
988(defun py-shift-region (start end count)
989 (save-excursion
990 (goto-char end) (beginning-of-line) (setq end (point))
991 (goto-char start) (beginning-of-line) (setq start (point))
992 (indent-rigidly start end count)))
993
994(defun py-shift-region-left (start end &optional count)
995 "Shift region of Python code to the left.
996The lines from the line containing the start of the current region up
997to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000998shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999
1000If a prefix argument is given, the region is instead shifted by that
1001many columns."
1002 (interactive "*r\nP") ; region; raw prefix arg
1003 (py-shift-region start end
1004 (- (prefix-numeric-value
1005 (or count py-indent-offset)))))
1006
1007(defun py-shift-region-right (start end &optional count)
1008 "Shift region of Python code to the right.
1009The lines from the line containing the start of the current region up
1010to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001011shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012
1013If a prefix argument is given, the region is instead shifted by that
1014many columns."
1015 (interactive "*r\nP") ; region; raw prefix arg
1016 (py-shift-region start end (prefix-numeric-value
1017 (or count py-indent-offset))))
1018
1019(defun py-indent-region (start end &optional indent-offset)
1020 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001021
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022The lines from the line containing the start of the current region up
1023to (but not including) the line containing the end of the region are
1024reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001025character in the first column, the first line is left alone and the
1026rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001027region is reindented with respect to the (closest code or indenting
1028comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029
1030This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001031control structures are introduced or removed, or to reformat code
1032using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001033
1034If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001035the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001036used.
1037
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001038Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001039is called! This function does not compute proper indentation from
1040scratch (that's impossible in Python), it merely adjusts the existing
1041indentation to be correct in context.
1042
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001043Warning: This function really has no idea what to do with
1044non-indenting comment lines, and shifts them as if they were indenting
1045comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001046
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001047Special cases: whitespace is deleted from blank lines; continuation
1048lines are shifted by the same amount their initial line was shifted,
1049in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001050initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001051 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052 (save-excursion
1053 (goto-char end) (beginning-of-line) (setq end (point-marker))
1054 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001055 (let ((py-indent-offset (prefix-numeric-value
1056 (or indent-offset py-indent-offset)))
1057 (indents '(-1)) ; stack of active indent levels
1058 (target-column 0) ; column to which to indent
1059 (base-shifted-by 0) ; amount last base line was shifted
1060 (indent-base (if (looking-at "[ \t\n]")
1061 (py-compute-indentation)
1062 0))
1063 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001064 (while (< (point) end)
1065 (setq ci (current-indentation))
1066 ;; figure out appropriate target column
1067 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001068 ((or (eq (following-char) ?#) ; comment in column 1
1069 (looking-at "[ \t]*$")) ; entirely blank
1070 (setq target-column 0))
1071 ((py-continuation-line-p) ; shift relative to base line
1072 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001073 (t ; new base line
1074 (if (> ci (car indents)) ; going deeper; push it
1075 (setq indents (cons ci indents))
1076 ;; else we should have seen this indent before
1077 (setq indents (memq ci indents)) ; pop deeper indents
1078 (if (null indents)
1079 (error "Bad indentation in region, at line %d"
1080 (save-restriction
1081 (widen)
1082 (1+ (count-lines 1 (point)))))))
1083 (setq target-column (+ indent-base
1084 (* py-indent-offset
1085 (- (length indents) 2))))
1086 (setq base-shifted-by (- target-column ci))))
1087 ;; shift as needed
1088 (if (/= ci target-column)
1089 (progn
1090 (delete-horizontal-space)
1091 (indent-to target-column)))
1092 (forward-line 1))))
1093 (set-marker end nil))
1094
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001095
1096;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097(defun py-previous-statement (count)
1098 "Go to the start of previous Python statement.
1099If the statement at point is the i'th Python statement, goes to the
1100start of statement i-COUNT. If there is no such statement, goes to the
1101first statement. Returns count of statements left to move.
1102`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001103 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001104 (if (< count 0) (py-next-statement (- count))
1105 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001106 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001107 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001108 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001109 (> count 0)
1110 (zerop (forward-line -1))
1111 (py-goto-statement-at-or-above))
1112 (setq count (1- count)))
1113 (if (> count 0) (goto-char start)))
1114 count))
1115
1116(defun py-next-statement (count)
1117 "Go to the start of next Python statement.
1118If the statement at point is the i'th Python statement, goes to the
1119start of statement i+COUNT. If there is no such statement, goes to the
1120last statement. Returns count of statements left to move. `Statements'
1121do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001122 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001123 (if (< count 0) (py-previous-statement (- count))
1124 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001125 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001126 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001127 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001128 (> count 0)
1129 (py-goto-statement-below))
1130 (setq count (1- count)))
1131 (if (> count 0) (goto-char start)))
1132 count))
1133
1134(defun py-goto-block-up (&optional nomark)
1135 "Move up to start of current block.
1136Go to the statement that starts the smallest enclosing block; roughly
1137speaking, this will be the closest preceding statement that ends with a
1138colon and is indented less than the statement you started on. If
1139successful, also sets the mark to the starting point.
1140
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001141`\\[py-mark-block]' can be used afterward to mark the whole code
1142block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001143
1144If called from a program, the mark will not be set if optional argument
1145NOMARK is not nil."
1146 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001147 (let ((start (point))
1148 (found nil)
1149 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150 (py-goto-initial-line)
1151 ;; if on blank or non-indenting comment line, use the preceding stmt
1152 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1153 (progn
1154 (py-goto-statement-at-or-above)
1155 (setq found (py-statement-opens-block-p))))
1156 ;; search back for colon line indented less
1157 (setq initial-indent (current-indentation))
1158 (if (zerop initial-indent)
1159 ;; force fast exit
1160 (goto-char (point-min)))
1161 (while (not (or found (bobp)))
1162 (setq found
1163 (and
1164 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1165 (or (py-goto-initial-line) t) ; always true -- side effect
1166 (< (current-indentation) initial-indent)
1167 (py-statement-opens-block-p))))
1168 (if found
1169 (progn
1170 (or nomark (push-mark start))
1171 (back-to-indentation))
1172 (goto-char start)
1173 (error "Enclosing block not found"))))
1174
1175(defun beginning-of-python-def-or-class (&optional class)
1176 "Move point to start of def (or class, with prefix arg).
1177
1178Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001179arg, looks for a `class' instead. The docs assume the `def' case;
1180just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001181
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182If point is in a def statement already, and after the `d', simply
1183moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001184
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001185Else (point is not in a def statement, or at or before the `d' of a
1186def statement), searches for the closest preceding def statement, and
1187leaves point at its start. If no such statement can be found, leaves
1188point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001189
1190Returns t iff a def statement is found by these rules.
1191
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001192Note that doing this command repeatedly will take you closer to the
1193start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001194
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001195If you want to mark the current def/class, see
1196`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001197 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1199 (start-of-line (progn (beginning-of-line) (point)))
1200 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201 (if (or (/= start-of-stmt start-of-line)
1202 (not at-or-before-p))
1203 (end-of-line)) ; OK to match on this line
1204 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001205 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001206
1207(defun end-of-python-def-or-class (&optional class)
1208 "Move point beyond end of def (or class, with prefix arg) body.
1209
1210By default, looks for an appropriate `def'. If you supply a prefix arg,
1211looks for a `class' instead. The docs assume the `def' case; just
1212substitute `class' for `def' for the other case.
1213
1214If point is in a def statement already, this is the def we use.
1215
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001216Else if the def found by `\\[beginning-of-python-def-or-class]'
1217contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001218
1219Else we search forward for the closest following def, and use that.
1220
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001221If a def can be found by these rules, point is moved to the start of
1222the line immediately following the def block, and the position of the
1223start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001224
1225Else point is moved to the end of the buffer, and nil is returned.
1226
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001227Note that doing this command repeatedly will take you closer to the
1228end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001229
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001230If you want to mark the current def/class, see
1231`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001232 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001233 (let ((start (progn (py-goto-initial-line) (point)))
1234 (which (if class "class" "def"))
1235 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001236 ;; move point to start of appropriate def/class
1237 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1238 (setq state 'at-beginning)
1239 ;; else see if beginning-of-python-def-or-class hits container
1240 (if (and (beginning-of-python-def-or-class class)
1241 (progn (py-goto-beyond-block)
1242 (> (point) start)))
1243 (setq state 'at-end)
1244 ;; else search forward
1245 (goto-char start)
1246 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1247 (progn (setq state 'at-beginning)
1248 (beginning-of-line)))))
1249 (cond
1250 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1251 ((eq state 'at-end) t)
1252 ((eq state 'not-found) nil)
1253 (t (error "internal error in end-of-python-def-or-class")))))
1254
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001255
1256;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257(defun py-mark-block (&optional extend just-move)
1258 "Mark following block of lines. With prefix arg, mark structure.
1259Easier to use than explain. It sets the region to an `interesting'
1260block of succeeding lines. If point is on a blank line, it goes down to
1261the next non-blank line. That will be the start of the region. The end
1262of the region depends on the kind of line at the start:
1263
1264 - If a comment, the region will include all succeeding comment lines up
1265 to (but not including) the next non-comment line (if any).
1266
1267 - Else if a prefix arg is given, and the line begins one of these
1268 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001269
1270 if elif else try except finally for while def class
1271
Barry Warsaw7ae77681994-12-12 20:38:05 +00001272 the region will be set to the body of the structure, including
1273 following blocks that `belong' to it, but excluding trailing blank
1274 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001275 and all (if any) of the following `except' and `finally' blocks
1276 that belong to the `try' structure will be in the region. Ditto
1277 for if/elif/else, for/else and while/else structures, and (a bit
1278 degenerate, since they're always one-block structures) def and
1279 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280
1281 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001282 block (see list above), and the block is not a `one-liner' (i.e.,
1283 the statement ends with a colon, not with code), the region will
1284 include all succeeding lines up to (but not including) the next
1285 code statement (if any) that's indented no more than the starting
1286 line, except that trailing blank and comment lines are excluded.
1287 E.g., if the starting line begins a multi-statement `def'
1288 structure, the region will be set to the full function definition,
1289 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290
1291 - Else the region will include all succeeding lines up to (but not
1292 including) the next blank line, or code or indenting-comment line
1293 indented strictly less than the starting line. Trailing indenting
1294 comment lines are included in this case, but not trailing blank
1295 lines.
1296
1297A msg identifying the location of the mark is displayed in the echo
1298area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1299
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001300If called from a program, optional argument EXTEND plays the role of
1301the prefix arg, and if optional argument JUST-MOVE is not nil, just
1302moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001303 (interactive "P") ; raw prefix arg
1304 (py-goto-initial-line)
1305 ;; skip over blank lines
1306 (while (and
1307 (looking-at "[ \t]*$") ; while blank line
1308 (not (eobp))) ; & somewhere to go
1309 (forward-line 1))
1310 (if (eobp)
1311 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001312 (let ((initial-pos (point))
1313 (initial-indent (current-indentation))
1314 last-pos ; position of last stmt in region
1315 (followers
1316 '((if elif else) (elif elif else) (else)
1317 (try except finally) (except except) (finally)
1318 (for else) (while else)
1319 (def) (class) ) )
1320 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001321
1322 (cond
1323 ;; if comment line, suck up the following comment lines
1324 ((looking-at "[ \t]*#")
1325 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1326 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1327 (setq last-pos (point)))
1328
1329 ;; else if line is a block line and EXTEND given, suck up
1330 ;; the whole structure
1331 ((and extend
1332 (setq first-symbol (py-suck-up-first-keyword) )
1333 (assq first-symbol followers))
1334 (while (and
1335 (or (py-goto-beyond-block) t) ; side effect
1336 (forward-line -1) ; side effect
1337 (setq last-pos (point)) ; side effect
1338 (py-goto-statement-below)
1339 (= (current-indentation) initial-indent)
1340 (setq next-symbol (py-suck-up-first-keyword))
1341 (memq next-symbol (cdr (assq first-symbol followers))))
1342 (setq first-symbol next-symbol)))
1343
1344 ;; else if line *opens* a block, search for next stmt indented <=
1345 ((py-statement-opens-block-p)
1346 (while (and
1347 (setq last-pos (point)) ; always true -- side effect
1348 (py-goto-statement-below)
1349 (> (current-indentation) initial-indent))
1350 nil))
1351
1352 ;; else plain code line; stop at next blank line, or stmt or
1353 ;; indenting comment line indented <
1354 (t
1355 (while (and
1356 (setq last-pos (point)) ; always true -- side effect
1357 (or (py-goto-beyond-final-line) t)
1358 (not (looking-at "[ \t]*$")) ; stop at blank line
1359 (or
1360 (>= (current-indentation) initial-indent)
1361 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1362 nil)))
1363
1364 ;; skip to end of last stmt
1365 (goto-char last-pos)
1366 (py-goto-beyond-final-line)
1367
1368 ;; set mark & display
1369 (if just-move
1370 () ; just return
1371 (push-mark (point) 'no-msg)
1372 (forward-line -1)
1373 (message "Mark set after: %s" (py-suck-up-leading-text))
1374 (goto-char initial-pos))))
1375
1376(defun mark-python-def-or-class (&optional class)
1377 "Set region to body of def (or class, with prefix arg) enclosing point.
1378Pushes the current mark, then point, on the mark ring (all language
1379modes do this, but although it's handy it's never documented ...).
1380
1381In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001382hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1383`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384
1385And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001386Turned out that was more confusing than useful: the `goto start' and
1387`goto end' commands are usually used to search through a file, and
1388people expect them to act a lot like `search backward' and `search
1389forward' string-search commands. But because Python `def' and `class'
1390can nest to arbitrary levels, finding the smallest def containing
1391point cannot be done via a simple backward search: the def containing
1392point may not be the closest preceding def, or even the closest
1393preceding def that's indented less. The fancy algorithm required is
1394appropriate for the usual uses of this `mark' command, but not for the
1395`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001397So the def marked by this command may not be the one either of the
1398`goto' commands find: If point is on a blank or non-indenting comment
1399line, moves back to start of the closest preceding code statement or
1400indenting comment line. If this is a `def' statement, that's the def
1401we use. Else searches for the smallest enclosing `def' block and uses
1402that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001403
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001404When an enclosing def is found: The mark is left immediately beyond
1405the last line of the def block. Point is left at the start of the
1406def, except that: if the def is preceded by a number of comment lines
1407followed by (at most) one optional blank line, point is left at the
1408start of the comments; else if the def is preceded by a blank line,
1409point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001410
1411The intent is to mark the containing def/class and its associated
1412documentation, to make moving and duplicating functions and classes
1413pleasant."
1414 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001415 (let ((start (point))
1416 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001417 (push-mark start)
1418 (if (not (py-go-up-tree-to-keyword which))
1419 (progn (goto-char start)
1420 (error "Enclosing %s not found" which))
1421 ;; else enclosing def/class found
1422 (setq start (point))
1423 (py-goto-beyond-block)
1424 (push-mark (point))
1425 (goto-char start)
1426 (if (zerop (forward-line -1)) ; if there is a preceding line
1427 (progn
1428 (if (looking-at "[ \t]*$") ; it's blank
1429 (setq start (point)) ; so reset start point
1430 (goto-char start)) ; else try again
1431 (if (zerop (forward-line -1))
1432 (if (looking-at "[ \t]*#") ; a comment
1433 ;; look back for non-comment line
1434 ;; tricky: note that the regexp matches a blank
1435 ;; line, cuz \n is in the 2nd character class
1436 (and
1437 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1438 (forward-line 1))
1439 ;; no comment, so go back
1440 (goto-char start))))))))
1441
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001442
1443;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001444
1445;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001446;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1447;; out of the right places, along with the keys they're on & current
1448;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449(defun py-dump-help-string (str)
1450 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001451 (let ((locals (buffer-local-variables))
1452 funckind funcname func funcdoc
1453 (start 0) mstart end
1454 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1456 (setq mstart (match-beginning 0) end (match-end 0)
1457 funckind (substring str (match-beginning 1) (match-end 1))
1458 funcname (substring str (match-beginning 2) (match-end 2))
1459 func (intern funcname))
1460 (princ (substitute-command-keys (substring str start mstart)))
1461 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001462 ((equal funckind "c") ; command
1463 (setq funcdoc (documentation func)
1464 keys (concat
1465 "Key(s): "
1466 (mapconcat 'key-description
1467 (where-is-internal func py-mode-map)
1468 ", "))))
1469 ((equal funckind "v") ; variable
1470 (setq funcdoc (substitute-command-keys
1471 (get func 'variable-documentation))
1472 keys (if (assq func locals)
1473 (concat
1474 "Local/Global values: "
1475 (prin1-to-string (symbol-value func))
1476 " / "
1477 (prin1-to-string (default-value func)))
1478 (concat
1479 "Value: "
1480 (prin1-to-string (symbol-value func))))))
1481 (t ; unexpected
1482 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001483 (princ (format "\n-> %s:\t%s\t%s\n\n"
1484 (if (equal funckind "c") "Command" "Variable")
1485 funcname keys))
1486 (princ funcdoc)
1487 (terpri)
1488 (setq start end))
1489 (princ (substitute-command-keys (substring str start))))
1490 (print-help-return-message)))
1491
1492(defun py-describe-mode ()
1493 "Dump long form of Python-mode docs."
1494 (interactive)
1495 (py-dump-help-string "Major mode for editing Python files.
1496Knows about Python indentation, tokens, comments and continuation lines.
1497Paragraphs are separated by blank lines only.
1498
1499Major sections below begin with the string `@'; specific function and
1500variable docs begin with `->'.
1501
1502@EXECUTING PYTHON CODE
1503
1504\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1505\\[py-execute-region]\tsends the current region
1506\\[py-shell]\tstarts a Python interpreter window; this will be used by
1507\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1508%c:py-execute-buffer
1509%c:py-execute-region
1510%c:py-shell
1511
1512@VARIABLES
1513
1514py-indent-offset\tindentation increment
1515py-block-comment-prefix\tcomment string used by py-comment-region
1516
1517py-python-command\tshell command to invoke Python interpreter
1518py-scroll-process-buffer\talways scroll Python process buffer
1519py-temp-directory\tdirectory used for temp files (if needed)
1520
1521py-beep-if-tab-change\tring the bell if tab-width is changed
1522%v:py-indent-offset
1523%v:py-block-comment-prefix
1524%v:py-python-command
1525%v:py-scroll-process-buffer
1526%v:py-temp-directory
1527%v:py-beep-if-tab-change
1528
1529@KINDS OF LINES
1530
1531Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001532preceding line ends with a backslash that's not part of a comment, or
1533the paren/bracket/brace nesting level at the start of the line is
1534non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001535
1536An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537possibly blanks or tabs), a `comment line' (leftmost non-blank
1538character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001539
1540Comment Lines
1541
1542Although all comment lines are treated alike by Python, Python mode
1543recognizes two kinds that act differently with respect to indentation.
1544
1545An `indenting comment line' is a comment line with a blank, tab or
1546nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548indenting comment line will be indented like the comment line. All
1549other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001550following the initial `#') are `non-indenting comment lines', and
1551their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552
1553Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001554whenever possible. Non-indenting comment lines are useful in cases
1555like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001556
1557\ta = b # a very wordy single-line comment that ends up being
1558\t #... continued onto another line
1559
1560\tif a == b:
1561##\t\tprint 'panic!' # old code we've `commented out'
1562\t\treturn a
1563
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001564Since the `#...' and `##' comment lines have a non-whitespace
1565character following the initial `#', Python mode ignores them when
1566computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567
1568Continuation Lines and Statements
1569
1570The Python-mode commands generally work on statements instead of on
1571individual lines, where a `statement' is a comment or blank line, or a
1572code line and all of its following continuation lines (if any)
1573considered as a single logical unit. The commands in this mode
1574generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001575statement containing point, even if point happens to be in the middle
1576of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577
1578
1579@INDENTATION
1580
1581Primarily for entering new code:
1582\t\\[indent-for-tab-command]\t indent line appropriately
1583\t\\[py-newline-and-indent]\t insert newline, then indent
1584\t\\[py-delete-char]\t reduce indentation, or delete single character
1585
1586Primarily for reindenting existing code:
1587\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1588\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1589
1590\t\\[py-indent-region]\t reindent region to match its context
1591\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1592\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1593
1594Unlike most programming languages, Python uses indentation, and only
1595indentation, to specify block structure. Hence the indentation supplied
1596automatically by Python-mode is just an educated guess: only you know
1597the block structure you intend, so only you can supply correct
1598indentation.
1599
1600The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1601the indentation of preceding statements. E.g., assuming
1602py-indent-offset is 4, after you enter
1603\tif a > 0: \\[py-newline-and-indent]
1604the cursor will be moved to the position of the `_' (_ is not a
1605character in the file, it's just used here to indicate the location of
1606the cursor):
1607\tif a > 0:
1608\t _
1609If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1610to
1611\tif a > 0:
1612\t c = d
1613\t _
1614Python-mode cannot know whether that's what you intended, or whether
1615\tif a > 0:
1616\t c = d
1617\t_
1618was your intent. In general, Python-mode either reproduces the
1619indentation of the (closest code or indenting-comment) preceding
1620statement, or adds an extra py-indent-offset blanks if the preceding
1621statement has `:' as its last significant (non-whitespace and non-
1622comment) character. If the suggested indentation is too much, use
1623\\[py-delete-char] to reduce it.
1624
1625Continuation lines are given extra indentation. If you don't like the
1626suggested indentation, change it to something you do like, and Python-
1627mode will strive to indent later lines of the statement in the same way.
1628
1629If a line is a continuation line by virtue of being in an unclosed
1630paren/bracket/brace structure (`list', for short), the suggested
1631indentation depends on whether the current line contains the first item
1632in the list. If it does, it's indented py-indent-offset columns beyond
1633the indentation of the line containing the open bracket. If you don't
1634like that, change it by hand. The remaining items in the list will mimic
1635whatever indentation you give to the first item.
1636
1637If a line is a continuation line because the line preceding it ends with
1638a backslash, the third and following lines of the statement inherit their
1639indentation from the line preceding them. The indentation of the second
1640line in the statement depends on the form of the first (base) line: if
1641the base line is an assignment statement with anything more interesting
1642than the backslash following the leftmost assigning `=', the second line
1643is indented two columns beyond that `='. Else it's indented to two
1644columns beyond the leftmost solid chunk of non-whitespace characters on
1645the base line.
1646
1647Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1648repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1649structure you intend.
1650%c:indent-for-tab-command
1651%c:py-newline-and-indent
1652%c:py-delete-char
1653
1654
1655The next function may be handy when editing code you didn't write:
1656%c:py-guess-indent-offset
1657
1658
1659The remaining `indent' functions apply to a region of Python code. They
1660assume the block structure (equals indentation, in Python) of the region
1661is correct, and alter the indentation in various ways while preserving
1662the block structure:
1663%c:py-indent-region
1664%c:py-shift-region-left
1665%c:py-shift-region-right
1666
1667@MARKING & MANIPULATING REGIONS OF CODE
1668
1669\\[py-mark-block]\t mark block of lines
1670\\[mark-python-def-or-class]\t mark smallest enclosing def
1671\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1672\\[py-comment-region]\t comment out region of code
1673\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1674%c:py-mark-block
1675%c:mark-python-def-or-class
1676%c:py-comment-region
1677
1678@MOVING POINT
1679
1680\\[py-previous-statement]\t move to statement preceding point
1681\\[py-next-statement]\t move to statement following point
1682\\[py-goto-block-up]\t move up to start of current block
1683\\[beginning-of-python-def-or-class]\t move to start of def
1684\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1685\\[end-of-python-def-or-class]\t move to end of def
1686\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1687
1688The first two move to one statement beyond the statement that contains
1689point. A numeric prefix argument tells them to move that many
1690statements instead. Blank lines, comment lines, and continuation lines
1691do not count as `statements' for these commands. So, e.g., you can go
1692to the first code statement in a file by entering
1693\t\\[beginning-of-buffer]\t to move to the top of the file
1694\t\\[py-next-statement]\t to skip over initial comments and blank lines
1695Or do `\\[py-previous-statement]' with a huge prefix argument.
1696%c:py-previous-statement
1697%c:py-next-statement
1698%c:py-goto-block-up
1699%c:beginning-of-python-def-or-class
1700%c:end-of-python-def-or-class
1701
1702@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1703
1704`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1705
1706`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1707overall class and def structure of a module.
1708
1709`\\[back-to-indentation]' moves point to a line's first non-blank character.
1710
1711`\\[indent-relative]' is handy for creating odd indentation.
1712
1713@OTHER EMACS HINTS
1714
1715If you don't like the default value of a variable, change its value to
1716whatever you do like by putting a `setq' line in your .emacs file.
1717E.g., to set the indentation increment to 4, put this line in your
1718.emacs:
1719\t(setq py-indent-offset 4)
1720To see the value of a variable, do `\\[describe-variable]' and enter the variable
1721name at the prompt.
1722
1723When entering a key sequence like `C-c C-n', it is not necessary to
1724release the CONTROL key after doing the `C-c' part -- it suffices to
1725press the CONTROL key, press and release `c' (while still holding down
1726CONTROL), press and release `n' (while still holding down CONTROL), &
1727then release CONTROL.
1728
1729Entering Python mode calls with no arguments the value of the variable
1730`python-mode-hook', if that value exists and is not nil; for backward
1731compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1732the Elisp manual for details.
1733
1734Obscure: When python-mode is first loaded, it looks for all bindings
1735to newline-and-indent in the global keymap, and shadows them with
1736local bindings to py-newline-and-indent."))
1737
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738
1739;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001740(defvar py-parse-state-re
1741 (concat
1742 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1743 "\\|"
1744 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001745
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746;; returns the parse state at point (see parse-partial-sexp docs)
1747(defun py-parse-state ()
1748 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001750 ;; back up to the first preceding line (if any; else start of
1751 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752 ;; whitespace and non-comment character. These are good places
1753 ;; to start parsing to see whether where we started is at a
1754 ;; non-zero nesting level. It may be slow for people who write
1755 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (re-search-backward py-parse-state-re nil 'move)
1757 (beginning-of-line)
1758 (parse-partial-sexp (point) here))))
1759
1760;; if point is at a non-zero nesting level, returns the number of the
1761;; character that opens the smallest enclosing unclosed list; else
1762;; returns nil.
1763(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001765 (if (zerop (car status))
1766 nil ; not in a nest
1767 (car (cdr status))))) ; char# of open bracket
1768
1769;; t iff preceding line ends with backslash that's not in a comment
1770(defun py-backslash-continuation-line-p ()
1771 (save-excursion
1772 (beginning-of-line)
1773 (and
1774 ;; use a cheap test first to avoid the regexp if possible
1775 ;; use 'eq' because char-after may return nil
1776 (eq (char-after (- (point) 2)) ?\\ )
1777 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779 (looking-at py-continued-re))))
1780
1781;; t iff current line is a continuation line
1782(defun py-continuation-line-p ()
1783 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001785 (or (py-backslash-continuation-line-p)
1786 (py-nesting-level))))
1787
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788;; go to initial line of current statement; usually this is the line
1789;; we're on, but if we're on the 2nd or following lines of a
1790;; continuation block, we need to go up to the first line of the
1791;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001793;; Tricky: We want to avoid quadratic-time behavior for long continued
1794;; blocks, whether of the backslash or open-bracket varieties, or a
1795;; mix of the two. The following manages to do that in the usual
1796;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797(defun py-goto-initial-line ()
1798 (let ( open-bracket-pos )
1799 (while (py-continuation-line-p)
1800 (beginning-of-line)
1801 (if (py-backslash-continuation-line-p)
1802 (while (py-backslash-continuation-line-p)
1803 (forward-line -1))
1804 ;; else zip out of nested brackets/braces/parens
1805 (while (setq open-bracket-pos (py-nesting-level))
1806 (goto-char open-bracket-pos)))))
1807 (beginning-of-line))
1808
1809;; go to point right beyond final line of current statement; usually
1810;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811;; statement we need to skip over the continuation lines. Tricky:
1812;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813(defun py-goto-beyond-final-line ()
1814 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001816 (while (and (py-continuation-line-p)
1817 (not (eobp)))
1818 ;; skip over the backslash flavor
1819 (while (and (py-backslash-continuation-line-p)
1820 (not (eobp)))
1821 (forward-line 1))
1822 ;; if in nest, zip to the end of the nest
1823 (setq state (py-parse-state))
1824 (if (and (not (zerop (car state)))
1825 (not (eobp)))
1826 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828 ;; the 3rd argument should be plain 0
1829 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1830 nil state)
1831 (forward-line 1))))))
1832
1833;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001835(defun py-statement-opens-block-p ()
1836 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837 (let ((start (point))
1838 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1839 (searching t)
1840 (answer nil)
1841 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842 (goto-char start)
1843 (while searching
1844 ;; look for a colon with nothing after it except whitespace, and
1845 ;; maybe a comment
1846 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1847 finish t)
1848 (if (eq (point) finish) ; note: no `else' clause; just
1849 ; keep searching if we're not at
1850 ; the end yet
1851 ;; sure looks like it opens a block -- but it might
1852 ;; be in a comment
1853 (progn
1854 (setq searching nil) ; search is done either way
1855 (setq state (parse-partial-sexp start
1856 (match-beginning 0)))
1857 (setq answer (not (nth 4 state)))))
1858 ;; search failed: couldn't find another interesting colon
1859 (setq searching nil)))
1860 answer)))
1861
1862;; go to point right beyond final line of block begun by the current
1863;; line. This is the same as where py-goto-beyond-final-line goes
1864;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866(defun py-goto-beyond-block ()
1867 (if (py-statement-opens-block-p)
1868 (py-mark-block nil 'just-move)
1869 (py-goto-beyond-final-line)))
1870
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871;; go to start of first statement (not blank or comment or
1872;; continuation line) at or preceding point. returns t if there is
1873;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874(defun py-goto-statement-at-or-above ()
1875 (py-goto-initial-line)
1876 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 ;; skip back over blank & comment lines
1878 ;; note: will skip a blank or comment line that happens to be
1879 ;; a continuation line too
1880 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1881 (progn (py-goto-initial-line) t)
1882 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883 t))
1884
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885;; go to start of first statement (not blank or comment or
1886;; continuation line) following the statement containing point returns
1887;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888(defun py-goto-statement-below ()
1889 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001890 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001891 (py-goto-beyond-final-line)
1892 (while (and
1893 (looking-at py-blank-or-comment-re)
1894 (not (eobp)))
1895 (forward-line 1))
1896 (if (eobp)
1897 (progn (goto-char start) nil)
1898 t)))
1899
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900;; go to start of statement, at or preceding point, starting with
1901;; keyword KEY. Skips blank lines and non-indenting comments upward
1902;; first. If that statement starts with KEY, done, else go back to
1903;; first enclosing block starting with KEY. If successful, leaves
1904;; point at the start of the KEY line & returns t. Else leaves point
1905;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001906(defun py-go-up-tree-to-keyword (key)
1907 ;; skip blanks and non-indenting #
1908 (py-goto-initial-line)
1909 (while (and
1910 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1911 (zerop (forward-line -1))) ; go back
1912 nil)
1913 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914 (let* ((re (concat "[ \t]*" key "\\b"))
1915 (case-fold-search nil) ; let* so looking-at sees this
1916 (found (looking-at re))
1917 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918 (while (not (or found dead))
1919 (condition-case nil ; in case no enclosing block
1920 (py-goto-block-up 'no-mark)
1921 (error (setq dead t)))
1922 (or dead (setq found (looking-at re))))
1923 (beginning-of-line)
1924 found))
1925
1926;; return string in buffer from start of indentation to end of line;
1927;; prefix "..." if leading whitespace was skipped
1928(defun py-suck-up-leading-text ()
1929 (save-excursion
1930 (back-to-indentation)
1931 (concat
1932 (if (bolp) "" "...")
1933 (buffer-substring (point) (progn (end-of-line) (point))))))
1934
1935;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1936;; as a Lisp symbol; return nil if none
1937(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1940 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1941 nil)))
1942
1943(defun py-make-temp-name ()
1944 (make-temp-name
1945 (concat (file-name-as-directory py-temp-directory) "python")))
1946
1947(defun py-delete-file-silently (fname)
1948 (condition-case nil
1949 (delete-file fname)
1950 (error nil)))
1951
1952(defun py-kill-emacs-hook ()
1953 ;; delete our temp files
1954 (while py-file-queue
1955 (py-delete-file-silently (car py-file-queue))
1956 (setq py-file-queue (cdr py-file-queue)))
1957 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1958 ;; run the hook we inherited, if any
1959 (and py-inherited-kill-emacs-hook
1960 (funcall py-inherited-kill-emacs-hook))))
1961
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001962;; make PROCESS's buffer visible, append STRING to it, and force
1963;; display; also make shell-mode believe the user typed this string,
1964;; so that kill-output-from-shell and show-output-from-shell work
1965;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001966(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967 (let ((cbuf (current-buffer))
1968 (pbuf (process-buffer process))
1969 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001970 (set-buffer pbuf)
1971 (goto-char (point-max))
1972 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001973 (if (not (or py-this-is-emacs-19-p
1974 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001975 (move-marker last-input-start (point))) ; muck w/ shell-mode
1976 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001977 (if (not (or py-this-is-emacs-19-p
1978 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001979 (move-marker last-input-end (point))) ; muck w/ shell-mode
1980 (set-buffer cbuf))
1981 (sit-for 0))
1982
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001983(defun py-keep-region-active ()
1984 ;; do whatever is necessary to keep the region active in XEmacs.
1985 ;; Ignore byte-compiler warnings you might see. Also note that
1986 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1987 ;; require us to take explicit action.
1988 (and (boundp 'zmacs-region-stays)
1989 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001990
1991
Barry Warsaw850437a1995-03-08 21:50:28 +00001992(defconst py-version "$Revision$"
1993 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001994(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001995 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996
Barry Warsaw850437a1995-03-08 21:50:28 +00001997(defun py-version ()
1998 "Echo the current version of `python-mode' in the minibuffer."
1999 (interactive)
2000 (message "Using `python-mode' version %s" py-version)
2001 (py-keep-region-active))
2002
2003;; only works under Emacs 19
2004;(eval-when-compile
2005; (require 'reporter))
2006
2007(defun py-submit-bug-report (enhancement-p)
2008 "Submit via mail a bug report on `python-mode'.
2009With \\[universal-argument] just submit an enhancement request."
2010 (interactive
2011 (list (not (y-or-n-p
2012 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002013 (let ((reporter-prompt-for-summary-p (if enhancement-p
2014 "(Very) brief summary: "
2015 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002016 (require 'reporter)
2017 (reporter-submit-bug-report
2018 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002019 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002020 ;; varlist
2021 (if enhancement-p nil
2022 '(py-python-command
2023 py-indent-offset
2024 py-block-comment-prefix
2025 py-scroll-process-buffer
2026 py-temp-directory
2027 py-beep-if-tab-change))
2028 nil ;pre-hooks
2029 nil ;post-hooks
2030 "Dear Barry,") ;salutation
2031 (if enhancement-p nil
2032 (set-mark (point))
2033 (insert
2034"Please replace this text with a sufficiently large code sample\n\
2035and an exact recipe so that I can reproduce your problem. Failure\n\
2036to do so may mean a greater delay in fixing your bug.\n\n")
2037 (exchange-point-and-mark)
2038 (py-keep-region-active))))
2039
2040
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002041;; arrange to kill temp files when Emacs exists
2042(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2043 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2044 ;; have to trust that other people are as respectful of our hook
2045 ;; fiddling as we are of theirs
2046 (if (boundp 'py-inherited-kill-emacs-hook)
2047 ;; we were loaded before -- trust others not to have screwed us
2048 ;; in the meantime (no choice, really)
2049 nil
2050 ;; else arrange for our hook to run theirs
2051 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2052 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2053
2054
2055
2056(provide 'python-mode)
2057;;; python-mode.el ends here