changes by Barry, e.g. font lock & email addresses
[python/dscho.git] / Misc / python-mode-old.el
blob18f93b08c6ff5be18df0093d3ed24437d464fc66
1 ;;; python-mode.el --- Major mode for editing Python programs
3 ;; Copyright (C) 1992,1993,1994 Tim Peters
5 ;; Author: 1995 Barry A. Warsaw
6 ;; 1992-1994 Tim Peters
7 ;; Maintainer: python-mode@python.org
8 ;; Created: Feb 1992
9 ;; Version: 2.26
10 ;; Last Modified: 1995/07/05 23:26:15
11 ;; Keywords: python editing language major-mode
13 ;; 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.
19 ;;; Commentary:
21 ;; 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
24 ;; have undertaken maintenance of the mode.
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
28 ;; mode works exceedingly well.
30 ;; The following statements, placed in your .emacs file or
31 ;; site-init.el, will cause this file to be autoloaded, and
32 ;; python-mode invoked, when visiting .py files (assuming this file is
33 ;; in your load-path):
35 ;; (autoload 'python-mode "python-mode" "Python editing mode." t)
36 ;; (setq auto-mode-alist
37 ;; (cons '("\\.py$" . python-mode) auto-mode-alist))
39 ;; Here's a brief list of recent additions/improvements:
41 ;; - Wrapping and indentation within triple quote strings should work
42 ;; properly now.
43 ;; - `Standard' bug reporting mechanism (use C-c C-b)
44 ;; - py-mark-block was moved to C-c C-m
45 ;; - C-c C-v shows you the python-mode version
46 ;; - a basic python-font-lock-keywords has been added for Emacs 19
47 ;; font-lock colorizations.
48 ;; - proper interaction with pending-del and del-sel modes.
49 ;; - New py-electric-colon (:) command for improved outdenting. Also
50 ;; py-indent-line (TAB) should handle outdented lines better.
51 ;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
53 ;; Here's a brief to do list:
55 ;; - Better integration with gud-mode for debugging.
56 ;; - Rewrite according to GNU Emacs Lisp standards.
57 ;; - py-delete-char should obey numeric arguments.
58 ;; - even better support for outdenting. Guido suggests outdents of
59 ;; at least one level after a return, raise, break, or continue
60 ;; statement.
61 ;; - de-electrify colon inside literals (e.g. comments and strings)
63 ;; If you can think of more things you'd like to see, drop me a line.
64 ;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
66 ;; Note that I only test things on XEmacs (currently 19.11). If you
67 ;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
68 ;; patches.
70 ;; LCD Archive Entry:
71 ;; python-mode|Barry A. Warsaw|python-mode@python.org
72 ;; |Major mode for editing Python programs
73 ;; |1995/07/05 23:26:15|2.26|
75 ;;; Code:
78 ;; user definable variables
79 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
81 (defvar py-python-command "python"
82 "*Shell command used to start Python interpreter.")
84 (defvar py-indent-offset 8 ; argue with Guido <grin>
85 "*Indentation increment.
86 Note that `\\[py-guess-indent-offset]' can usually guess a good value
87 when you're editing someone else's Python code.")
89 (defvar py-block-comment-prefix "##"
90 "*String used by `py-comment-region' to comment out a block of code.
91 This should follow the convention for non-indenting comment lines so
92 that the indentation commands won't get confused (i.e., the string
93 should be of the form `#x...' where `x' is not a blank or a tab, and
94 `...' is arbitrary).")
96 (defvar py-scroll-process-buffer t
97 "*Scroll Python process buffer as output arrives.
98 If nil, the Python process buffer acts, with respect to scrolling, like
99 Shell-mode buffers normally act. This is surprisingly complicated and
100 so won't be explained here; in fact, you can't get the whole story
101 without studying the Emacs C code.
103 If non-nil, the behavior is different in two respects (which are
104 slightly inaccurate in the interest of brevity):
106 - If the buffer is in a window, and you left point at its end, the
107 window will scroll as new output arrives, and point will move to the
108 buffer's end, even if the window is not the selected window (that
109 being the one the cursor is in). The usual behavior for shell-mode
110 windows is not to scroll, and to leave point where it was, if the
111 buffer is in a window other than the selected window.
113 - If the buffer is not visible in any window, and you left point at
114 its end, the buffer will be popped into a window as soon as more
115 output arrives. This is handy if you have a long-running
116 computation and don't want to tie up screen area waiting for the
117 output. The usual behavior for a shell-mode buffer is to stay
118 invisible until you explicitly visit it.
120 Note the `and if you left point at its end' clauses in both of the
121 above: you can `turn off' the special behaviors while output is in
122 progress, by visiting the Python buffer and moving point to anywhere
123 besides the end. Then the buffer won't scroll, point will remain where
124 you leave it, and if you hide the buffer it will stay hidden until you
125 visit it again. You can enable and disable the special behaviors as
126 often as you like, while output is in progress, by (respectively) moving
127 point to, or away from, the end of the buffer.
129 Warning: If you expect a large amount of output, you'll probably be
130 happier setting this option to nil.
132 Obscure: `End of buffer' above should really say `at or beyond the
133 process mark', but if you know what that means you didn't need to be
134 told <grin>.")
136 (defvar py-temp-directory
137 (let ((ok '(lambda (x)
138 (and x
139 (setq x (expand-file-name x)) ; always true
140 (file-directory-p x)
141 (file-writable-p x)
142 x))))
143 (or (funcall ok (getenv "TMPDIR"))
144 (funcall ok "/usr/tmp")
145 (funcall ok "/tmp")
146 (funcall ok ".")
147 (error
148 "Couldn't find a usable temp directory -- set py-temp-directory")))
149 "*Directory used for temp files created by a *Python* process.
150 By default, the first directory from this list that exists and that you
151 can write into: the value (if any) of the environment variable TMPDIR,
152 /usr/tmp, /tmp, or the current directory.")
154 (defvar py-beep-if-tab-change t
155 "*Ring the bell if tab-width is changed.
156 If a comment of the form
158 \t# vi:set tabsize=<number>:
160 is found before the first code line when the file is entered, and the
161 current value of (the general Emacs variable) `tab-width' does not
162 equal <number>, `tab-width' is set to <number>, a message saying so is
163 displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
164 the Emacs bell is also rung as a warning.")
166 ;; These were the previous font-lock keywords, but I think I now
167 ;; prefer the ones from XEmacs 19.12's font-lock.el. I've merged the
168 ;; two into the new definition below.
170 ;;(defvar python-font-lock-keywords
171 ;; (list
172 ;; (cons
173 ;; (concat
174 ;; "\\<\\("
175 ;; (mapconcat
176 ;; 'identity
177 ;; '("access" "and" "break" "continue"
178 ;; "del" "elif" "else" "except"
179 ;; "exec" "finally" "for" "from"
180 ;; "global" "if" "import" "in"
181 ;; "is" "lambda" "not" "or"
182 ;; "pass" "print" "raise" "return"
183 ;; "try" "while" "def" "class"
184 ;; )
185 ;; "\\|")
186 ;; "\\)\\>")
187 ;; 1)
188 ;; ;; functions
189 ;; '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
190 ;; ;; classes
191 ;; '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
192 ;; )
193 ;; "*Additional keywords to highlight `python-mode' buffers.")
195 ;; These are taken from XEmacs 19.12's font-lock.el file, but have the
196 ;; more complete list of keywords from the previous definition in
197 ;; python-mode.el. There are a few other minor stylistic changes as
198 ;; well.
200 (defvar python-font-lock-keywords
201 (list
202 (cons (concat
203 "\\b\\("
204 (mapconcat
205 'identity
206 '("access" "and" "break" "continue"
207 "del" "elif" "else:" "except"
208 "except:" "exec" "finally:" "for"
209 "from" "global" "if" "import"
210 "in" "is" "lambda" "not"
211 "or" "pass" "print" "raise"
212 "return" "try:" "while"
214 "\\|")
215 "\\)[ \n\t(]")
217 ;; classes
218 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
219 1 font-lock-type-face)
220 ;; functions
221 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
222 1 font-lock-function-name-face)
224 "*Additional expressions to highlight in Python mode.")
226 ;; R Lindsay Todd <toddr@rpi.edu> suggests these changes to the
227 ;; original keywords, which wouldn't be necessary if we go with the
228 ;; XEmacs defaults, but which I agree makes sense without them.
230 ;; functions
231 ;; '("\\bdef\\s +\\(\\sw+\\)\\s *(" 1 font-lock-function-name-face)
232 ;; classes
233 ;; '("\\bclass\\s +\\(\\sw+\\)\\s *[(:]" 1 font-lock-type-face)
237 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
238 ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
240 ;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
241 ;; seems to be the standard way of checking this.
242 ;; BAW - This is *not* the right solution. When at all possible,
243 ;; instead of testing for the version of Emacs, use feature tests.
245 (setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
246 (setq py-this-is-emacs-19-p
247 (and
248 (not py-this-is-lucid-emacs-p)
249 (string-match "^19\\." emacs-version)))
251 ;; have to bind py-file-queue before installing the kill-emacs hook
252 (defvar py-file-queue nil
253 "Queue of Python temp files awaiting execution.
254 Currently-active file is at the head of the list.")
256 ;; define a mode-specific abbrev table for those who use such things
257 (defvar python-mode-abbrev-table nil
258 "Abbrev table in use in `python-mode' buffers.")
259 (define-abbrev-table 'python-mode-abbrev-table nil)
261 (defvar python-mode-hook nil
262 "*Hook called by `python-mode'.")
264 ;; in previous version of python-mode.el, the hook was incorrectly
265 ;; called py-mode-hook, and was not defvar'd. deprecate its use.
266 (and (fboundp 'make-obsolete-variable)
267 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
269 (defvar py-mode-map ()
270 "Keymap used in `python-mode' buffers.")
272 (if py-mode-map
274 (setq py-mode-map (make-sparse-keymap))
276 ;; shadow global bindings for newline-and-indent w/ the py- version.
277 ;; BAW - this is extremely bad form, but I'm not going to change it
278 ;; for now.
279 (mapcar (function (lambda (key)
280 (define-key
281 py-mode-map key 'py-newline-and-indent)))
282 (where-is-internal 'newline-and-indent))
284 ;; BAW - you could do it this way, but its not considered proper
285 ;; major-mode form.
286 (mapcar (function
287 (lambda (x)
288 (define-key py-mode-map (car x) (cdr x))))
289 '((":" . py-electric-colon)
290 ("\C-c\C-c" . py-execute-buffer)
291 ("\C-c|" . py-execute-region)
292 ("\C-c!" . py-shell)
293 ("\177" . py-delete-char)
294 ("\n" . py-newline-and-indent)
295 ("\C-c:" . py-guess-indent-offset)
296 ("\C-c\t" . py-indent-region)
297 ("\C-c\C-l" . py-outdent-left)
298 ("\C-c\C-r" . py-indent-right)
299 ("\C-c<" . py-shift-region-left)
300 ("\C-c>" . py-shift-region-right)
301 ("\C-c\C-n" . py-next-statement)
302 ("\C-c\C-p" . py-previous-statement)
303 ("\C-c\C-u" . py-goto-block-up)
304 ("\C-c\C-m" . py-mark-block)
305 ("\C-c#" . py-comment-region)
306 ("\C-c?" . py-describe-mode)
307 ("\C-c\C-hm" . py-describe-mode)
308 ("\e\C-a" . beginning-of-python-def-or-class)
309 ("\e\C-e" . end-of-python-def-or-class)
310 ( "\e\C-h" . mark-python-def-or-class)))
311 ;; should do all keybindings this way
312 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
313 (define-key py-mode-map "\C-c\C-v" 'py-version)
316 (defvar py-mode-syntax-table nil
317 "Syntax table used in `python-mode' buffers.")
319 (if py-mode-syntax-table
321 (setq py-mode-syntax-table (make-syntax-table))
322 ;; BAW - again, blech.
323 (mapcar (function
324 (lambda (x) (modify-syntax-entry
325 (car x) (cdr x) py-mode-syntax-table)))
326 '(( ?\( . "()" ) ( ?\) . ")(" )
327 ( ?\[ . "(]" ) ( ?\] . ")[" )
328 ( ?\{ . "(}" ) ( ?\} . "){" )
329 ;; fix operator symbols misassigned in the std table
330 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
331 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
332 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
333 ( ?\> . "." ) ( ?\| . "." )
334 ( ?\_ . "w" ) ; underscore is legit in names
335 ( ?\' . "\"") ; single quote is string quote
336 ( ?\" . "\"" ) ; double quote is string quote too
337 ( ?\` . "$") ; backquote is open and close paren
338 ( ?\# . "<") ; hash starts comment
339 ( ?\n . ">")))) ; newline ends comment
341 (defconst py-stringlit-re
342 (concat
343 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
344 "\\|" ; or
345 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
346 "Regexp matching a Python string literal.")
348 ;; this is tricky because a trailing backslash does not mean
349 ;; continuation if it's in a comment
350 (defconst py-continued-re
351 (concat
352 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
353 "\\\\$")
354 "Regexp matching Python lines that are continued via backslash.")
356 (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
357 "Regexp matching blank or comment lines.")
359 (defconst py-outdent-re
360 (concat "\\(" (mapconcat 'identity
361 '("else:"
362 "except\\(\\s +.*\\)?:"
363 "finally:"
364 "elif\\s +.*:")
365 "\\|")
366 "\\)")
367 "Regexp matching clauses to be outdented one level.")
369 (defconst py-no-outdent-re
370 (concat "\\(" (mapconcat 'identity
371 '("try:"
372 "except\\(\\s +.*\\)?:"
373 "while\\s +.*:"
374 "for\\s +.*:"
375 "if\\s +.*:"
376 "elif\\s +.*:")
377 "\\|")
378 "\\)")
379 "Regexp matching lines to not outdent after.")
382 ;;;###autoload
383 (defun python-mode ()
384 "Major mode for editing Python files.
385 To submit a problem report, enter `\\[py-submit-bug-report]' from a
386 `python-mode' buffer. Do `\\[py-describe-mode]' for detailed
387 documentation. To see what version of `python-mode' you are running,
388 enter `\\[py-version]'.
390 This mode knows about Python indentation, tokens, comments and
391 continuation lines. Paragraphs are separated by blank lines only.
393 COMMANDS
394 \\{py-mode-map}
395 VARIABLES
397 py-indent-offset\tindentation increment
398 py-block-comment-prefix\tcomment string used by py-comment-region
399 py-python-command\tshell command to invoke Python interpreter
400 py-scroll-process-buffer\talways scroll Python process buffer
401 py-temp-directory\tdirectory used for temp files (if needed)
402 py-beep-if-tab-change\tring the bell if tab-width is changed"
403 (interactive)
404 (kill-all-local-variables)
405 (set-syntax-table py-mode-syntax-table)
406 (setq major-mode 'python-mode
407 mode-name "Python"
408 local-abbrev-table python-mode-abbrev-table)
409 (use-local-map py-mode-map)
410 ;; BAW -- style...
411 (mapcar (function (lambda (x)
412 (make-local-variable (car x))
413 (set (car x) (cdr x))))
414 '((paragraph-separate . "^[ \t]*$")
415 (paragraph-start . "^[ \t]*$")
416 (require-final-newline . t)
417 (comment-start . "# ")
418 (comment-start-skip . "# *")
419 (comment-column . 40)
420 (indent-region-function . py-indent-region)
421 (indent-line-function . py-indent-line)))
422 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
424 ;; not sure where the magic comment has to be; to save time
425 ;; searching for a rarity, we give up if it's not found prior to the
426 ;; first executable statement.
428 ;; BAW - on first glance, this seems like complete hackery. Why was
429 ;; this necessary, and is it still necessary?
430 (let ((case-fold-search nil)
431 (start (point))
432 new-tab-width)
433 (if (re-search-forward
434 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
435 (prog2 (py-next-statement 1) (point) (goto-char 1))
437 (progn
438 (setq new-tab-width
439 (string-to-int
440 (buffer-substring (match-beginning 1) (match-end 1))))
441 (if (= tab-width new-tab-width)
443 (setq tab-width new-tab-width)
444 (message "Caution: tab-width changed to %d" new-tab-width)
445 (if py-beep-if-tab-change (beep)))))
446 (goto-char start))
448 ;; run the mode hook. py-mode-hook use is deprecated
449 (if python-mode-hook
450 (run-hooks 'python-mode-hook)
451 (run-hooks 'py-mode-hook)))
454 ;; electric characters
455 (defun py-outdent-p ()
456 ;; returns non-nil if the current line should outdent one level
457 (save-excursion
458 (and (progn (back-to-indentation)
459 (looking-at py-outdent-re))
460 (progn (backward-to-indentation 1)
461 (while (or (looking-at py-blank-or-comment-re)
462 (bobp))
463 (backward-to-indentation 1))
464 (not (looking-at py-no-outdent-re)))
468 (defun py-electric-colon (arg)
469 "Insert a colon.
470 In certain cases the line is outdented appropriately. If a numeric
471 argument is provided, that many colons are inserted non-electrically."
472 (interactive "P")
473 (self-insert-command (prefix-numeric-value arg))
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)))
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 ))))
497 (defun py-indent-right (arg)
498 "Indent the line by one `py-indent-offset' level.
499 With numeric arg, indent by that many levels. You cannot indent
500 farther right than the distance the line would be indented by
501 \\[py-indent-line]."
502 (interactive "p")
503 (let ((col (current-indentation))
504 (want (* arg py-indent-offset))
505 (indent (py-compute-indentation))
506 (pos (- (point-max) (point)))
507 (bol (save-excursion (beginning-of-line) (point))))
508 (if (<= (+ col want) indent)
509 (progn
510 (beginning-of-line)
511 (delete-horizontal-space)
512 (indent-to (+ col want))
513 (if (> (- (point-max) pos) (point))
514 (goto-char (- (point-max) pos)))
515 ))))
517 (defun py-outdent-left (arg)
518 "Outdent the line by one `py-indent-offset' level.
519 With numeric arg, outdent by that many levels. You cannot outdent
520 farther left than column zero."
521 (interactive "p")
522 (let ((col (current-indentation))
523 (want (* arg py-indent-offset))
524 (pos (- (point-max) (point)))
525 (bol (save-excursion (beginning-of-line) (point))))
526 (if (<= 0 (- col want))
527 (progn
528 (beginning-of-line)
529 (delete-horizontal-space)
530 (indent-to (- col want))
531 (if (> (- (point-max) pos) (point))
532 (goto-char (- (point-max) pos)))
533 ))))
536 ;;; Functions that execute Python commands in a subprocess
537 (defun py-shell ()
538 "Start an interactive Python interpreter in another window.
539 This is like Shell mode, except that Python is running in the window
540 instead of a shell. See the `Interactive Shell' and `Shell Mode'
541 sections of the Emacs manual for details, especially for the key
542 bindings active in the `*Python*' buffer.
544 See the docs for variable `py-scroll-buffer' for info on scrolling
545 behavior in the process window.
547 Warning: Don't use an interactive Python if you change sys.ps1 or
548 sys.ps2 from their default values, or if you're running code that
549 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
550 distinguish your output from Python's output, and assumes that `>>> '
551 at the start of a line is a prompt from Python. Similarly, the Emacs
552 Shell mode code assumes that both `>>> ' and `... ' at the start of a
553 line are Python prompts. Bad things can happen if you fool either
554 mode.
556 Warning: If you do any editing *in* the process buffer *while* the
557 buffer is accepting output from Python, do NOT attempt to `undo' the
558 changes. Some of the output (nowhere near the parts you changed!) may
559 be lost if you do. This appears to be an Emacs bug, an unfortunate
560 interaction between undo and process filters; the same problem exists in
561 non-Python process buffers using the default (Emacs-supplied) process
562 filter."
563 ;; BAW - should undo be disabled in the python process buffer, if
564 ;; this bug still exists?
565 (interactive)
566 (if py-this-is-emacs-19-p
567 (progn
568 (require 'comint)
569 (switch-to-buffer-other-window
570 (make-comint "Python" py-python-command)))
571 (progn
572 (require 'shell)
573 (switch-to-buffer-other-window
574 (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
575 "Python" py-python-command nil))))
576 (make-local-variable 'shell-prompt-pattern)
577 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
578 (set-process-filter (get-buffer-process (current-buffer))
579 'py-process-filter)
580 (set-syntax-table py-mode-syntax-table))
582 (defun py-execute-region (start end)
583 "Send the region between START and END to a Python interpreter.
584 If there is a *Python* process it is used.
586 Hint: If you want to execute part of a Python file several times
587 \(e.g., perhaps you're developing a function and want to flesh it out
588 a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
589 the region of interest, and send the code to a *Python* process via
590 `\\[py-execute-buffer]' instead.
592 Following are subtleties to note when using a *Python* process:
594 If a *Python* process is used, the region is copied into a temporary
595 file (in directory `py-temp-directory'), and an `execfile' command is
596 sent to Python naming that file. If you send regions faster than
597 Python can execute them, `python-mode' will save them into distinct
598 temp files, and execute the next one in the queue the next time it
599 sees a `>>> ' prompt from Python. Each time this happens, the process
600 buffer is popped into a window (if it's not already in some window) so
601 you can see it, and a comment of the form
603 \t## working on region in file <name> ...
605 is inserted at the end.
607 Caution: No more than 26 regions can be pending at any given time.
608 This limit is (indirectly) inherited from libc's mktemp(3).
609 `python-mode' does not try to protect you from exceeding the limit.
610 It's extremely unlikely that you'll get anywhere close to the limit in
611 practice, unless you're trying to be a jerk <grin>.
613 See the `\\[py-shell]' docs for additional warnings."
614 (interactive "r")
615 (or (< start end) (error "Region is empty"))
616 (let ((pyproc (get-process "Python"))
617 fname)
618 (if (null pyproc)
619 (shell-command-on-region start end py-python-command)
620 ;; else feed it thru a temp file
621 (setq fname (py-make-temp-name))
622 (write-region start end fname nil 'no-msg)
623 (setq py-file-queue (append py-file-queue (list fname)))
624 (if (cdr py-file-queue)
625 (message "File %s queued for execution" fname)
626 ;; else
627 (py-execute-file pyproc fname)))))
629 (defun py-execute-file (pyproc fname)
630 (py-append-to-process-buffer
631 pyproc
632 (format "## working on region in file %s ...\n" fname))
633 (process-send-string pyproc (format "execfile('%s')\n" fname)))
635 (defun py-process-filter (pyproc string)
636 (let ((curbuf (current-buffer))
637 (pbuf (process-buffer pyproc))
638 (pmark (process-mark pyproc))
639 file-finished)
641 ;; make sure we switch to a different buffer at least once. if we
642 ;; *don't* do this, then if the process buffer is in the selected
643 ;; window, and point is before the end, and lots of output is
644 ;; coming at a fast pace, then (a) simple cursor-movement commands
645 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
646 ;; to have a visible effect (the window just doesn't get updated,
647 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
648 ;; get all the process output (until the next python prompt).
650 ;; #b makes no sense to me at all. #a almost makes sense: unless
651 ;; we actually change buffers, set_buffer_internal in buffer.c
652 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
653 ;; seems to make the Emacs command loop reluctant to update the
654 ;; display. Perhaps the default process filter in process.c's
655 ;; read_process_output has update_mode_lines++ for a similar
656 ;; reason? beats me ...
658 ;; BAW - we want to check to see if this still applies
659 (if (eq curbuf pbuf) ; mysterious ugly hack
660 (set-buffer (get-buffer-create "*scratch*")))
662 (set-buffer pbuf)
663 (let* ((start (point))
664 (goback (< start pmark))
665 (goend (and (not goback) (= start (point-max))))
666 (buffer-read-only nil))
667 (goto-char pmark)
668 (insert string)
669 (move-marker pmark (point))
670 (setq file-finished
671 (and py-file-queue
672 (equal ">>> "
673 (buffer-substring
674 (prog2 (beginning-of-line) (point)
675 (goto-char pmark))
676 (point)))))
677 (if goback (goto-char start)
678 ;; else
679 (if py-scroll-process-buffer
680 (let* ((pop-up-windows t)
681 (pwin (display-buffer pbuf)))
682 (set-window-point pwin (point)))))
683 (set-buffer curbuf)
684 (if file-finished
685 (progn
686 (py-delete-file-silently (car py-file-queue))
687 (setq py-file-queue (cdr py-file-queue))
688 (if py-file-queue
689 (py-execute-file pyproc (car py-file-queue)))))
690 (and goend
691 (progn (set-buffer pbuf)
692 (goto-char (point-max))))
695 (defun py-execute-buffer ()
696 "Send the contents of the buffer to a Python interpreter.
697 If there is a *Python* process buffer it is used. If a clipping
698 restriction is in effect, only the accessible portion of the buffer is
699 sent. A trailing newline will be supplied if needed.
701 See the `\\[py-execute-region]' docs for an account of some subtleties."
702 (interactive)
703 (py-execute-region (point-min) (point-max)))
707 ;; Functions for Python style indentation
708 (defun py-delete-char ()
709 "Reduce indentation or delete character.
710 If point is at the leftmost column, deletes the preceding newline.
712 Else if point is at the leftmost non-blank character of a line that is
713 neither a continuation line nor a non-indenting comment line, or if
714 point is at the end of a blank line, reduces the indentation to match
715 that of the line that opened the current block of code. The line that
716 opened the block is displayed in the echo area to help you keep track
717 of where you are.
719 Else the preceding character is deleted, converting a tab to spaces if
720 needed so that only a single column position is deleted."
721 (interactive "*")
722 (if (or (/= (current-indentation) (current-column))
723 (bolp)
724 (py-continuation-line-p)
725 (looking-at "#[^ \t\n]")) ; non-indenting #
726 (backward-delete-char-untabify 1)
727 ;; else indent the same as the colon line that opened the block
729 ;; force non-blank so py-goto-block-up doesn't ignore it
730 (insert-char ?* 1)
731 (backward-char)
732 (let ((base-indent 0) ; indentation of base line
733 (base-text "") ; and text of base line
734 (base-found-p nil))
735 (condition-case nil ; in case no enclosing block
736 (save-excursion
737 (py-goto-block-up 'no-mark)
738 (setq base-indent (current-indentation)
739 base-text (py-suck-up-leading-text)
740 base-found-p t))
741 (error nil))
742 (delete-char 1) ; toss the dummy character
743 (delete-horizontal-space)
744 (indent-to base-indent)
745 (if base-found-p
746 (message "Closes block: %s" base-text)))))
748 ;; required for pending-del and delsel modes
749 (put 'py-delete-char 'delete-selection 'supersede)
750 (put 'py-delete-char 'pending-delete 'supersede)
752 (defun py-indent-line ()
753 "Fix the indentation of the current line according to Python rules."
754 (interactive)
755 (let* ((ci (current-indentation))
756 (move-to-indentation-p (<= (current-column) ci))
757 (need (py-compute-indentation)))
758 ;; see if we need to outdent
759 (if (py-outdent-p)
760 (setq need (- need py-indent-offset)))
761 (if (/= ci need)
762 (save-excursion
763 (beginning-of-line)
764 (delete-horizontal-space)
765 (indent-to need)))
766 (if move-to-indentation-p (back-to-indentation))))
768 (defun py-newline-and-indent ()
769 "Strives to act like the Emacs `newline-and-indent'.
770 This is just `strives to' because correct indentation can't be computed
771 from scratch for Python code. In general, deletes the whitespace before
772 point, inserts a newline, and takes an educated guess as to how you want
773 the new line indented."
774 (interactive)
775 (let ((ci (current-indentation)))
776 (if (< ci (current-column)) ; if point beyond indentation
777 (newline-and-indent)
778 ;; else try to act like newline-and-indent "normally" acts
779 (beginning-of-line)
780 (insert-char ?\n 1)
781 (move-to-column ci))))
783 (defun py-compute-indentation ()
784 (save-excursion
785 (beginning-of-line)
786 (cond
787 ;; are we on a continuation line?
788 ((py-continuation-line-p)
789 (let ((startpos (point))
790 (open-bracket-pos (py-nesting-level))
791 endpos searching found)
792 (if open-bracket-pos
793 (progn
794 ;; align with first item in list; else a normal
795 ;; indent beyond the line with the open bracket
796 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
797 ;; is the first list item on the same line?
798 (skip-chars-forward " \t")
799 (if (null (memq (following-char) '(?\n ?# ?\\)))
800 ; yes, so line up with it
801 (current-column)
802 ;; first list item on another line, or doesn't exist yet
803 (forward-line 1)
804 (while (and (< (point) startpos)
805 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
806 (forward-line 1))
807 (if (< (point) startpos)
808 ;; again mimic the first list item
809 (current-indentation)
810 ;; else they're about to enter the first item
811 (goto-char open-bracket-pos)
812 (+ (current-indentation) py-indent-offset))))
814 ;; else on backslash continuation line
815 (forward-line -1)
816 (if (py-continuation-line-p) ; on at least 3rd line in block
817 (current-indentation) ; so just continue the pattern
818 ;; else started on 2nd line in block, so indent more.
819 ;; if base line is an assignment with a start on a RHS,
820 ;; indent to 2 beyond the leftmost "="; else skip first
821 ;; chunk of non-whitespace characters on base line, + 1 more
822 ;; column
823 (end-of-line)
824 (setq endpos (point) searching t)
825 (back-to-indentation)
826 (setq startpos (point))
827 ;; look at all "=" from left to right, stopping at first
828 ;; one not nested in a list or string
829 (while searching
830 (skip-chars-forward "^=" endpos)
831 (if (= (point) endpos)
832 (setq searching nil)
833 (forward-char 1)
834 (setq state (parse-partial-sexp startpos (point)))
835 (if (and (zerop (car state)) ; not in a bracket
836 (null (nth 3 state))) ; & not in a string
837 (progn
838 (setq searching nil) ; done searching in any case
839 (setq found
840 (not (or
841 (eq (following-char) ?=)
842 (memq (char-after (- (point) 2))
843 '(?< ?> ?!)))))))))
844 (if (or (not found) ; not an assignment
845 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
846 (progn
847 (goto-char startpos)
848 (skip-chars-forward "^ \t\n")))
849 (1+ (current-column))))))
851 ;; not on a continuation line
853 ;; if at start of restriction, or on a non-indenting comment line,
854 ;; assume they intended whatever's there
855 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
856 (current-indentation))
858 ;; else indentation based on that of the statement that precedes
859 ;; us; use the first line of that statement to establish the base,
860 ;; in case the user forced a non-std indentation for the
861 ;; continuation lines (if any)
863 ;; skip back over blank & non-indenting comment lines
864 ;; note: will skip a blank or non-indenting comment line that
865 ;; happens to be a continuation line too
866 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
867 nil 'move)
868 ;; if we landed inside a string, go to the beginning of that
869 ;; string. this handles triple quoted, multi-line spanning
870 ;; strings.
871 (let ((state (parse-partial-sexp
872 (save-excursion (beginning-of-python-def-or-class)
873 (point))
874 (point))))
875 (if (nth 3 state)
876 (goto-char (nth 2 state))))
877 (py-goto-initial-line)
878 (if (py-statement-opens-block-p)
879 (+ (current-indentation) py-indent-offset)
880 (current-indentation))))))
882 (defun py-guess-indent-offset (&optional global)
883 "Guess a good value for, and change, `py-indent-offset'.
884 By default (without a prefix arg), makes a buffer-local copy of
885 `py-indent-offset' with the new value. This will not affect any other
886 Python buffers. With a prefix arg, changes the global value of
887 `py-indent-offset'. This affects all Python buffers (that don't have
888 their own buffer-local copy), both those currently existing and those
889 created later in the Emacs session.
891 Some people use a different value for `py-indent-offset' than you use.
892 There's no excuse for such foolishness, but sometimes you have to deal
893 with their ugly code anyway. This function examines the file and sets
894 `py-indent-offset' to what it thinks it was when they created the
895 mess.
897 Specifically, it searches forward from the statement containing point,
898 looking for a line that opens a block of code. `py-indent-offset' is
899 set to the difference in indentation between that line and the Python
900 statement following it. If the search doesn't succeed going forward,
901 it's tried again going backward."
902 (interactive "P") ; raw prefix arg
903 (let (new-value
904 (start (point))
905 restart
906 (found nil)
907 colon-indent)
908 (py-goto-initial-line)
909 (while (not (or found (eobp)))
910 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
911 (progn
912 (setq restart (point))
913 (py-goto-initial-line)
914 (if (py-statement-opens-block-p)
915 (setq found t)
916 (goto-char restart)))))
917 (if found
919 (goto-char start)
920 (py-goto-initial-line)
921 (while (not (or found (bobp)))
922 (setq found
923 (and
924 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
925 (or (py-goto-initial-line) t) ; always true -- side effect
926 (py-statement-opens-block-p)))))
927 (setq colon-indent (current-indentation)
928 found (and found (zerop (py-next-statement 1)))
929 new-value (- (current-indentation) colon-indent))
930 (goto-char start)
931 (if found
932 (progn
933 (funcall (if global 'kill-local-variable 'make-local-variable)
934 'py-indent-offset)
935 (setq py-indent-offset new-value)
936 (message "%s value of py-indent-offset set to %d"
937 (if global "Global" "Local")
938 py-indent-offset))
939 (error "Sorry, couldn't guess a value for py-indent-offset"))))
941 (defun py-shift-region (start end count)
942 (save-excursion
943 (goto-char end) (beginning-of-line) (setq end (point))
944 (goto-char start) (beginning-of-line) (setq start (point))
945 (indent-rigidly start end count)))
947 (defun py-shift-region-left (start end &optional count)
948 "Shift region of Python code to the left.
949 The lines from the line containing the start of the current region up
950 to (but not including) the line containing the end of the region are
951 shifted to the left, by `py-indent-offset' columns.
953 If a prefix argument is given, the region is instead shifted by that
954 many columns."
955 (interactive "*r\nP") ; region; raw prefix arg
956 (py-shift-region start end
957 (- (prefix-numeric-value
958 (or count py-indent-offset)))))
960 (defun py-shift-region-right (start end &optional count)
961 "Shift region of Python code to the right.
962 The lines from the line containing the start of the current region up
963 to (but not including) the line containing the end of the region are
964 shifted to the right, by `py-indent-offset' columns.
966 If a prefix argument is given, the region is instead shifted by that
967 many columns."
968 (interactive "*r\nP") ; region; raw prefix arg
969 (py-shift-region start end (prefix-numeric-value
970 (or count py-indent-offset))))
972 (defun py-indent-region (start end &optional indent-offset)
973 "Reindent a region of Python code.
974 The lines from the line containing the start of the current region up
975 to (but not including) the line containing the end of the region are
976 reindented. If the first line of the region has a non-whitespace
977 character in the first column, the first line is left alone and the
978 rest of the region is reindented with respect to it. Else the entire
979 region is reindented with respect to the (closest code or
980 indenting-comment) statement immediately preceding the region.
982 This is useful when code blocks are moved or yanked, when enclosing
983 control structures are introduced or removed, or to reformat code
984 using a new value for the indentation offset.
986 If a numeric prefix argument is given, it will be used as the value of
987 the indentation offset. Else the value of `py-indent-offset' will be
988 used.
990 Warning: The region must be consistently indented before this function
991 is called! This function does not compute proper indentation from
992 scratch (that's impossible in Python), it merely adjusts the existing
993 indentation to be correct in context.
995 Warning: This function really has no idea what to do with
996 non-indenting comment lines, and shifts them as if they were indenting
997 comment lines. Fixing this appears to require telepathy.
999 Special cases: whitespace is deleted from blank lines; continuation
1000 lines are shifted by the same amount their initial line was shifted,
1001 in order to preserve their relative indentation with respect to their
1002 initial line; and comment lines beginning in column 1 are ignored."
1003 (interactive "*r\nP") ; region; raw prefix arg
1004 (save-excursion
1005 (goto-char end) (beginning-of-line) (setq end (point-marker))
1006 (goto-char start) (beginning-of-line)
1007 (let ((py-indent-offset (prefix-numeric-value
1008 (or indent-offset py-indent-offset)))
1009 (indents '(-1)) ; stack of active indent levels
1010 (target-column 0) ; column to which to indent
1011 (base-shifted-by 0) ; amount last base line was shifted
1012 (indent-base (if (looking-at "[ \t\n]")
1013 (py-compute-indentation)
1016 (while (< (point) end)
1017 (setq ci (current-indentation))
1018 ;; figure out appropriate target column
1019 (cond
1020 ((or (eq (following-char) ?#) ; comment in column 1
1021 (looking-at "[ \t]*$")) ; entirely blank
1022 (setq target-column 0))
1023 ((py-continuation-line-p) ; shift relative to base line
1024 (setq target-column (+ ci base-shifted-by)))
1025 (t ; new base line
1026 (if (> ci (car indents)) ; going deeper; push it
1027 (setq indents (cons ci indents))
1028 ;; else we should have seen this indent before
1029 (setq indents (memq ci indents)) ; pop deeper indents
1030 (if (null indents)
1031 (error "Bad indentation in region, at line %d"
1032 (save-restriction
1033 (widen)
1034 (1+ (count-lines 1 (point)))))))
1035 (setq target-column (+ indent-base
1036 (* py-indent-offset
1037 (- (length indents) 2))))
1038 (setq base-shifted-by (- target-column ci))))
1039 ;; shift as needed
1040 (if (/= ci target-column)
1041 (progn
1042 (delete-horizontal-space)
1043 (indent-to target-column)))
1044 (forward-line 1))))
1045 (set-marker end nil))
1048 ;; Functions for moving point
1049 (defun py-previous-statement (count)
1050 "Go to the start of previous Python statement.
1051 If the statement at point is the i'th Python statement, goes to the
1052 start of statement i-COUNT. If there is no such statement, goes to the
1053 first statement. Returns count of statements left to move.
1054 `Statements' do not include blank, comment, or continuation lines."
1055 (interactive "p") ; numeric prefix arg
1056 (if (< count 0) (py-next-statement (- count))
1057 (py-goto-initial-line)
1058 (let (start)
1059 (while (and
1060 (setq start (point)) ; always true -- side effect
1061 (> count 0)
1062 (zerop (forward-line -1))
1063 (py-goto-statement-at-or-above))
1064 (setq count (1- count)))
1065 (if (> count 0) (goto-char start)))
1066 count))
1068 (defun py-next-statement (count)
1069 "Go to the start of next Python statement.
1070 If the statement at point is the i'th Python statement, goes to the
1071 start of statement i+COUNT. If there is no such statement, goes to the
1072 last statement. Returns count of statements left to move. `Statements'
1073 do not include blank, comment, or continuation lines."
1074 (interactive "p") ; numeric prefix arg
1075 (if (< count 0) (py-previous-statement (- count))
1076 (beginning-of-line)
1077 (let (start)
1078 (while (and
1079 (setq start (point)) ; always true -- side effect
1080 (> count 0)
1081 (py-goto-statement-below))
1082 (setq count (1- count)))
1083 (if (> count 0) (goto-char start)))
1084 count))
1086 (defun py-goto-block-up (&optional nomark)
1087 "Move up to start of current block.
1088 Go to the statement that starts the smallest enclosing block; roughly
1089 speaking, this will be the closest preceding statement that ends with a
1090 colon and is indented less than the statement you started on. If
1091 successful, also sets the mark to the starting point.
1093 `\\[py-mark-block]' can be used afterward to mark the whole code
1094 block, if desired.
1096 If called from a program, the mark will not be set if optional argument
1097 NOMARK is not nil."
1098 (interactive)
1099 (let ((start (point))
1100 (found nil)
1101 initial-indent)
1102 (py-goto-initial-line)
1103 ;; if on blank or non-indenting comment line, use the preceding stmt
1104 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1105 (progn
1106 (py-goto-statement-at-or-above)
1107 (setq found (py-statement-opens-block-p))))
1108 ;; search back for colon line indented less
1109 (setq initial-indent (current-indentation))
1110 (if (zerop initial-indent)
1111 ;; force fast exit
1112 (goto-char (point-min)))
1113 (while (not (or found (bobp)))
1114 (setq found
1115 (and
1116 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1117 (or (py-goto-initial-line) t) ; always true -- side effect
1118 (< (current-indentation) initial-indent)
1119 (py-statement-opens-block-p))))
1120 (if found
1121 (progn
1122 (or nomark (push-mark start))
1123 (back-to-indentation))
1124 (goto-char start)
1125 (error "Enclosing block not found"))))
1127 (defun beginning-of-python-def-or-class (&optional class)
1128 "Move point to start of def (or class, with prefix arg).
1130 Searches back for the closest preceding `def'. If you supply a prefix
1131 arg, looks for a `class' instead. The docs assume the `def' case;
1132 just substitute `class' for `def' for the other case.
1134 If point is in a def statement already, and after the `d', simply
1135 moves point to the start of the statement.
1137 Else (point is not in a def statement, or at or before the `d' of a
1138 def statement), searches for the closest preceding def statement, and
1139 leaves point at its start. If no such statement can be found, leaves
1140 point at the start of the buffer.
1142 Returns t iff a def statement is found by these rules.
1144 Note that doing this command repeatedly will take you closer to the
1145 start of the buffer each time.
1147 If you want to mark the current def/class, see
1148 `\\[mark-python-def-or-class]'."
1149 (interactive "P") ; raw prefix arg
1150 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1151 (start-of-line (progn (beginning-of-line) (point)))
1152 (start-of-stmt (progn (py-goto-initial-line) (point))))
1153 (if (or (/= start-of-stmt start-of-line)
1154 (not at-or-before-p))
1155 (end-of-line)) ; OK to match on this line
1156 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
1157 nil 'move)))
1159 (defun end-of-python-def-or-class (&optional class)
1160 "Move point beyond end of def (or class, with prefix arg) body.
1162 By default, looks for an appropriate `def'. If you supply a prefix arg,
1163 looks for a `class' instead. The docs assume the `def' case; just
1164 substitute `class' for `def' for the other case.
1166 If point is in a def statement already, this is the def we use.
1168 Else if the def found by `\\[beginning-of-python-def-or-class]'
1169 contains the statement you started on, that's the def we use.
1171 Else we search forward for the closest following def, and use that.
1173 If a def can be found by these rules, point is moved to the start of
1174 the line immediately following the def block, and the position of the
1175 start of the def is returned.
1177 Else point is moved to the end of the buffer, and nil is returned.
1179 Note that doing this command repeatedly will take you closer to the
1180 end of the buffer each time.
1182 If you want to mark the current def/class, see
1183 `\\[mark-python-def-or-class]'."
1184 (interactive "P") ; raw prefix arg
1185 (let ((start (progn (py-goto-initial-line) (point)))
1186 (which (if class "class" "def"))
1187 (state 'not-found))
1188 ;; move point to start of appropriate def/class
1189 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1190 (setq state 'at-beginning)
1191 ;; else see if beginning-of-python-def-or-class hits container
1192 (if (and (beginning-of-python-def-or-class class)
1193 (progn (py-goto-beyond-block)
1194 (> (point) start)))
1195 (setq state 'at-end)
1196 ;; else search forward
1197 (goto-char start)
1198 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1199 (progn (setq state 'at-beginning)
1200 (beginning-of-line)))))
1201 (cond
1202 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1203 ((eq state 'at-end) t)
1204 ((eq state 'not-found) nil)
1205 (t (error "internal error in end-of-python-def-or-class")))))
1208 ;; Functions for marking regions
1209 (defun py-mark-block (&optional extend just-move)
1210 "Mark following block of lines. With prefix arg, mark structure.
1211 Easier to use than explain. It sets the region to an `interesting'
1212 block of succeeding lines. If point is on a blank line, it goes down to
1213 the next non-blank line. That will be the start of the region. The end
1214 of the region depends on the kind of line at the start:
1216 - If a comment, the region will include all succeeding comment lines up
1217 to (but not including) the next non-comment line (if any).
1219 - Else if a prefix arg is given, and the line begins one of these
1220 structures:
1222 if elif else try except finally for while def class
1224 the region will be set to the body of the structure, including
1225 following blocks that `belong' to it, but excluding trailing blank
1226 and comment lines. E.g., if on a `try' statement, the `try' block
1227 and all (if any) of the following `except' and `finally' blocks
1228 that belong to the `try' structure will be in the region. Ditto
1229 for if/elif/else, for/else and while/else structures, and (a bit
1230 degenerate, since they're always one-block structures) def and
1231 class blocks.
1233 - Else if no prefix argument is given, and the line begins a Python
1234 block (see list above), and the block is not a `one-liner' (i.e.,
1235 the statement ends with a colon, not with code), the region will
1236 include all succeeding lines up to (but not including) the next
1237 code statement (if any) that's indented no more than the starting
1238 line, except that trailing blank and comment lines are excluded.
1239 E.g., if the starting line begins a multi-statement `def'
1240 structure, the region will be set to the full function definition,
1241 but without any trailing `noise' lines.
1243 - Else the region will include all succeeding lines up to (but not
1244 including) the next blank line, or code or indenting-comment line
1245 indented strictly less than the starting line. Trailing indenting
1246 comment lines are included in this case, but not trailing blank
1247 lines.
1249 A msg identifying the location of the mark is displayed in the echo
1250 area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1252 If called from a program, optional argument EXTEND plays the role of
1253 the prefix arg, and if optional argument JUST-MOVE is not nil, just
1254 moves to the end of the block (& does not set mark or display a msg)."
1255 (interactive "P") ; raw prefix arg
1256 (py-goto-initial-line)
1257 ;; skip over blank lines
1258 (while (and
1259 (looking-at "[ \t]*$") ; while blank line
1260 (not (eobp))) ; & somewhere to go
1261 (forward-line 1))
1262 (if (eobp)
1263 (error "Hit end of buffer without finding a non-blank stmt"))
1264 (let ((initial-pos (point))
1265 (initial-indent (current-indentation))
1266 last-pos ; position of last stmt in region
1267 (followers
1268 '((if elif else) (elif elif else) (else)
1269 (try except finally) (except except) (finally)
1270 (for else) (while else)
1271 (def) (class) ) )
1272 first-symbol next-symbol)
1274 (cond
1275 ;; if comment line, suck up the following comment lines
1276 ((looking-at "[ \t]*#")
1277 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1278 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1279 (setq last-pos (point)))
1281 ;; else if line is a block line and EXTEND given, suck up
1282 ;; the whole structure
1283 ((and extend
1284 (setq first-symbol (py-suck-up-first-keyword) )
1285 (assq first-symbol followers))
1286 (while (and
1287 (or (py-goto-beyond-block) t) ; side effect
1288 (forward-line -1) ; side effect
1289 (setq last-pos (point)) ; side effect
1290 (py-goto-statement-below)
1291 (= (current-indentation) initial-indent)
1292 (setq next-symbol (py-suck-up-first-keyword))
1293 (memq next-symbol (cdr (assq first-symbol followers))))
1294 (setq first-symbol next-symbol)))
1296 ;; else if line *opens* a block, search for next stmt indented <=
1297 ((py-statement-opens-block-p)
1298 (while (and
1299 (setq last-pos (point)) ; always true -- side effect
1300 (py-goto-statement-below)
1301 (> (current-indentation) initial-indent))
1302 nil))
1304 ;; else plain code line; stop at next blank line, or stmt or
1305 ;; indenting comment line indented <
1307 (while (and
1308 (setq last-pos (point)) ; always true -- side effect
1309 (or (py-goto-beyond-final-line) t)
1310 (not (looking-at "[ \t]*$")) ; stop at blank line
1312 (>= (current-indentation) initial-indent)
1313 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1314 nil)))
1316 ;; skip to end of last stmt
1317 (goto-char last-pos)
1318 (py-goto-beyond-final-line)
1320 ;; set mark & display
1321 (if just-move
1322 () ; just return
1323 (push-mark (point) 'no-msg)
1324 (forward-line -1)
1325 (message "Mark set after: %s" (py-suck-up-leading-text))
1326 (goto-char initial-pos))))
1328 (defun mark-python-def-or-class (&optional class)
1329 "Set region to body of def (or class, with prefix arg) enclosing point.
1330 Pushes the current mark, then point, on the mark ring (all language
1331 modes do this, but although it's handy it's never documented ...).
1333 In most Emacs language modes, this function bears at least a
1334 hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1335 `\\[beginning-of-python-def-or-class]'.
1337 And in earlier versions of Python mode, all 3 were tightly connected.
1338 Turned out that was more confusing than useful: the `goto start' and
1339 `goto end' commands are usually used to search through a file, and
1340 people expect them to act a lot like `search backward' and `search
1341 forward' string-search commands. But because Python `def' and `class'
1342 can nest to arbitrary levels, finding the smallest def containing
1343 point cannot be done via a simple backward search: the def containing
1344 point may not be the closest preceding def, or even the closest
1345 preceding def that's indented less. The fancy algorithm required is
1346 appropriate for the usual uses of this `mark' command, but not for the
1347 `goto' variations.
1349 So the def marked by this command may not be the one either of the
1350 `goto' commands find: If point is on a blank or non-indenting comment
1351 line, moves back to start of the closest preceding code statement or
1352 indenting comment line. If this is a `def' statement, that's the def
1353 we use. Else searches for the smallest enclosing `def' block and uses
1354 that. Else signals an error.
1356 When an enclosing def is found: The mark is left immediately beyond
1357 the last line of the def block. Point is left at the start of the
1358 def, except that: if the def is preceded by a number of comment lines
1359 followed by (at most) one optional blank line, point is left at the
1360 start of the comments; else if the def is preceded by a blank line,
1361 point is left at its start.
1363 The intent is to mark the containing def/class and its associated
1364 documentation, to make moving and duplicating functions and classes
1365 pleasant."
1366 (interactive "P") ; raw prefix arg
1367 (let ((start (point))
1368 (which (if class "class" "def")))
1369 (push-mark start)
1370 (if (not (py-go-up-tree-to-keyword which))
1371 (progn (goto-char start)
1372 (error "Enclosing %s not found" which))
1373 ;; else enclosing def/class found
1374 (setq start (point))
1375 (py-goto-beyond-block)
1376 (push-mark (point))
1377 (goto-char start)
1378 (if (zerop (forward-line -1)) ; if there is a preceding line
1379 (progn
1380 (if (looking-at "[ \t]*$") ; it's blank
1381 (setq start (point)) ; so reset start point
1382 (goto-char start)) ; else try again
1383 (if (zerop (forward-line -1))
1384 (if (looking-at "[ \t]*#") ; a comment
1385 ;; look back for non-comment line
1386 ;; tricky: note that the regexp matches a blank
1387 ;; line, cuz \n is in the 2nd character class
1388 (and
1389 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1390 (forward-line 1))
1391 ;; no comment, so go back
1392 (goto-char start))))))))
1394 (defun py-comment-region (start end &optional uncomment-p)
1395 "Comment out region of code; with prefix arg, uncomment region.
1396 The lines from the line containing the start of the current region up
1397 to (but not including) the line containing the end of the region are
1398 commented out, by inserting the string `py-block-comment-prefix' at
1399 the start of each line. With a prefix arg, removes
1400 `py-block-comment-prefix' from the start of each line instead."
1401 (interactive "*r\nP") ; region; raw prefix arg
1402 (goto-char end) (beginning-of-line) (setq end (point))
1403 (goto-char start) (beginning-of-line) (setq start (point))
1404 (let ((prefix-len (length py-block-comment-prefix)) )
1405 (save-excursion
1406 (save-restriction
1407 (narrow-to-region start end)
1408 (while (not (eobp))
1409 (if uncomment-p
1410 (and (string= py-block-comment-prefix
1411 (buffer-substring
1412 (point) (+ (point) prefix-len)))
1413 (delete-char prefix-len))
1414 (insert py-block-comment-prefix))
1415 (forward-line 1))))))
1418 ;; Documentation functions
1420 ;; dump the long form of the mode blurb; does the usual doc escapes,
1421 ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1422 ;; out of the right places, along with the keys they're on & current
1423 ;; values
1424 (defun py-dump-help-string (str)
1425 (with-output-to-temp-buffer "*Help*"
1426 (let ((locals (buffer-local-variables))
1427 funckind funcname func funcdoc
1428 (start 0) mstart end
1429 keys )
1430 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1431 (setq mstart (match-beginning 0) end (match-end 0)
1432 funckind (substring str (match-beginning 1) (match-end 1))
1433 funcname (substring str (match-beginning 2) (match-end 2))
1434 func (intern funcname))
1435 (princ (substitute-command-keys (substring str start mstart)))
1436 (cond
1437 ((equal funckind "c") ; command
1438 (setq funcdoc (documentation func)
1439 keys (concat
1440 "Key(s): "
1441 (mapconcat 'key-description
1442 (where-is-internal func py-mode-map)
1443 ", "))))
1444 ((equal funckind "v") ; variable
1445 (setq funcdoc (substitute-command-keys
1446 (get func 'variable-documentation))
1447 keys (if (assq func locals)
1448 (concat
1449 "Local/Global values: "
1450 (prin1-to-string (symbol-value func))
1451 " / "
1452 (prin1-to-string (default-value func)))
1453 (concat
1454 "Value: "
1455 (prin1-to-string (symbol-value func))))))
1456 (t ; unexpected
1457 (error "Error in py-dump-help-string, tag `%s'" funckind)))
1458 (princ (format "\n-> %s:\t%s\t%s\n\n"
1459 (if (equal funckind "c") "Command" "Variable")
1460 funcname keys))
1461 (princ funcdoc)
1462 (terpri)
1463 (setq start end))
1464 (princ (substitute-command-keys (substring str start))))
1465 (print-help-return-message)))
1467 (defun py-describe-mode ()
1468 "Dump long form of Python-mode docs."
1469 (interactive)
1470 (py-dump-help-string "Major mode for editing Python files.
1471 Knows about Python indentation, tokens, comments and continuation lines.
1472 Paragraphs are separated by blank lines only.
1474 Major sections below begin with the string `@'; specific function and
1475 variable docs begin with `->'.
1477 @EXECUTING PYTHON CODE
1479 \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1480 \\[py-execute-region]\tsends the current region
1481 \\[py-shell]\tstarts a Python interpreter window; this will be used by
1482 \tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1483 %c:py-execute-buffer
1484 %c:py-execute-region
1485 %c:py-shell
1487 @VARIABLES
1489 py-indent-offset\tindentation increment
1490 py-block-comment-prefix\tcomment string used by py-comment-region
1492 py-python-command\tshell command to invoke Python interpreter
1493 py-scroll-process-buffer\talways scroll Python process buffer
1494 py-temp-directory\tdirectory used for temp files (if needed)
1496 py-beep-if-tab-change\tring the bell if tab-width is changed
1497 %v:py-indent-offset
1498 %v:py-block-comment-prefix
1499 %v:py-python-command
1500 %v:py-scroll-process-buffer
1501 %v:py-temp-directory
1502 %v:py-beep-if-tab-change
1504 @KINDS OF LINES
1506 Each physical line in the file is either a `continuation line' (the
1507 preceding line ends with a backslash that's not part of a comment, or
1508 the paren/bracket/brace nesting level at the start of the line is
1509 non-zero, or both) or an `initial line' (everything else).
1511 An initial line is in turn a `blank line' (contains nothing except
1512 possibly blanks or tabs), a `comment line' (leftmost non-blank
1513 character is `#'), or a `code line' (everything else).
1515 Comment Lines
1517 Although all comment lines are treated alike by Python, Python mode
1518 recognizes two kinds that act differently with respect to indentation.
1520 An `indenting comment line' is a comment line with a blank, tab or
1521 nothing after the initial `#'. The indentation commands (see below)
1522 treat these exactly as if they were code lines: a line following an
1523 indenting comment line will be indented like the comment line. All
1524 other comment lines (those with a non-whitespace character immediately
1525 following the initial `#') are `non-indenting comment lines', and
1526 their indentation is ignored by the indentation commands.
1528 Indenting comment lines are by far the usual case, and should be used
1529 whenever possible. Non-indenting comment lines are useful in cases
1530 like these:
1532 \ta = b # a very wordy single-line comment that ends up being
1533 \t #... continued onto another line
1535 \tif a == b:
1536 ##\t\tprint 'panic!' # old code we've `commented out'
1537 \t\treturn a
1539 Since the `#...' and `##' comment lines have a non-whitespace
1540 character following the initial `#', Python mode ignores them when
1541 computing the proper indentation for the next line.
1543 Continuation Lines and Statements
1545 The Python-mode commands generally work on statements instead of on
1546 individual lines, where a `statement' is a comment or blank line, or a
1547 code line and all of its following continuation lines (if any)
1548 considered as a single logical unit. The commands in this mode
1549 generally (when it makes sense) automatically move to the start of the
1550 statement containing point, even if point happens to be in the middle
1551 of some continuation line.
1554 @INDENTATION
1556 Primarily for entering new code:
1557 \t\\[indent-for-tab-command]\t indent line appropriately
1558 \t\\[py-newline-and-indent]\t insert newline, then indent
1559 \t\\[py-delete-char]\t reduce indentation, or delete single character
1561 Primarily for reindenting existing code:
1562 \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1563 \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1565 \t\\[py-indent-region]\t reindent region to match its context
1566 \t\\[py-shift-region-left]\t shift region left by py-indent-offset
1567 \t\\[py-shift-region-right]\t shift region right by py-indent-offset
1569 Unlike most programming languages, Python uses indentation, and only
1570 indentation, to specify block structure. Hence the indentation supplied
1571 automatically by Python-mode is just an educated guess: only you know
1572 the block structure you intend, so only you can supply correct
1573 indentation.
1575 The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1576 the indentation of preceding statements. E.g., assuming
1577 py-indent-offset is 4, after you enter
1578 \tif a > 0: \\[py-newline-and-indent]
1579 the cursor will be moved to the position of the `_' (_ is not a
1580 character in the file, it's just used here to indicate the location of
1581 the cursor):
1582 \tif a > 0:
1583 \t _
1584 If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1586 \tif a > 0:
1587 \t c = d
1588 \t _
1589 Python-mode cannot know whether that's what you intended, or whether
1590 \tif a > 0:
1591 \t c = d
1593 was your intent. In general, Python-mode either reproduces the
1594 indentation of the (closest code or indenting-comment) preceding
1595 statement, or adds an extra py-indent-offset blanks if the preceding
1596 statement has `:' as its last significant (non-whitespace and non-
1597 comment) character. If the suggested indentation is too much, use
1598 \\[py-delete-char] to reduce it.
1600 Continuation lines are given extra indentation. If you don't like the
1601 suggested indentation, change it to something you do like, and Python-
1602 mode will strive to indent later lines of the statement in the same way.
1604 If a line is a continuation line by virtue of being in an unclosed
1605 paren/bracket/brace structure (`list', for short), the suggested
1606 indentation depends on whether the current line contains the first item
1607 in the list. If it does, it's indented py-indent-offset columns beyond
1608 the indentation of the line containing the open bracket. If you don't
1609 like that, change it by hand. The remaining items in the list will mimic
1610 whatever indentation you give to the first item.
1612 If a line is a continuation line because the line preceding it ends with
1613 a backslash, the third and following lines of the statement inherit their
1614 indentation from the line preceding them. The indentation of the second
1615 line in the statement depends on the form of the first (base) line: if
1616 the base line is an assignment statement with anything more interesting
1617 than the backslash following the leftmost assigning `=', the second line
1618 is indented two columns beyond that `='. Else it's indented to two
1619 columns beyond the leftmost solid chunk of non-whitespace characters on
1620 the base line.
1622 Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1623 repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1624 structure you intend.
1625 %c:indent-for-tab-command
1626 %c:py-newline-and-indent
1627 %c:py-delete-char
1630 The next function may be handy when editing code you didn't write:
1631 %c:py-guess-indent-offset
1634 The remaining `indent' functions apply to a region of Python code. They
1635 assume the block structure (equals indentation, in Python) of the region
1636 is correct, and alter the indentation in various ways while preserving
1637 the block structure:
1638 %c:py-indent-region
1639 %c:py-shift-region-left
1640 %c:py-shift-region-right
1642 @MARKING & MANIPULATING REGIONS OF CODE
1644 \\[py-mark-block]\t mark block of lines
1645 \\[mark-python-def-or-class]\t mark smallest enclosing def
1646 \\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1647 \\[py-comment-region]\t comment out region of code
1648 \\[universal-argument] \\[py-comment-region]\t uncomment region of code
1649 %c:py-mark-block
1650 %c:mark-python-def-or-class
1651 %c:py-comment-region
1653 @MOVING POINT
1655 \\[py-previous-statement]\t move to statement preceding point
1656 \\[py-next-statement]\t move to statement following point
1657 \\[py-goto-block-up]\t move up to start of current block
1658 \\[beginning-of-python-def-or-class]\t move to start of def
1659 \\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1660 \\[end-of-python-def-or-class]\t move to end of def
1661 \\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1663 The first two move to one statement beyond the statement that contains
1664 point. A numeric prefix argument tells them to move that many
1665 statements instead. Blank lines, comment lines, and continuation lines
1666 do not count as `statements' for these commands. So, e.g., you can go
1667 to the first code statement in a file by entering
1668 \t\\[beginning-of-buffer]\t to move to the top of the file
1669 \t\\[py-next-statement]\t to skip over initial comments and blank lines
1670 Or do `\\[py-previous-statement]' with a huge prefix argument.
1671 %c:py-previous-statement
1672 %c:py-next-statement
1673 %c:py-goto-block-up
1674 %c:beginning-of-python-def-or-class
1675 %c:end-of-python-def-or-class
1677 @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1679 `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1681 `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1682 overall class and def structure of a module.
1684 `\\[back-to-indentation]' moves point to a line's first non-blank character.
1686 `\\[indent-relative]' is handy for creating odd indentation.
1688 @OTHER EMACS HINTS
1690 If you don't like the default value of a variable, change its value to
1691 whatever you do like by putting a `setq' line in your .emacs file.
1692 E.g., to set the indentation increment to 4, put this line in your
1693 .emacs:
1694 \t(setq py-indent-offset 4)
1695 To see the value of a variable, do `\\[describe-variable]' and enter the variable
1696 name at the prompt.
1698 When entering a key sequence like `C-c C-n', it is not necessary to
1699 release the CONTROL key after doing the `C-c' part -- it suffices to
1700 press the CONTROL key, press and release `c' (while still holding down
1701 CONTROL), press and release `n' (while still holding down CONTROL), &
1702 then release CONTROL.
1704 Entering Python mode calls with no arguments the value of the variable
1705 `python-mode-hook', if that value exists and is not nil; for backward
1706 compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1707 the Elisp manual for details.
1709 Obscure: When python-mode is first loaded, it looks for all bindings
1710 to newline-and-indent in the global keymap, and shadows them with
1711 local bindings to py-newline-and-indent."))
1714 ;; Helper functions
1715 (defvar py-parse-state-re
1716 (concat
1717 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1718 "\\|"
1719 "^[^ #\t\n]"))
1721 ;; returns the parse state at point (see parse-partial-sexp docs)
1722 (defun py-parse-state ()
1723 (save-excursion
1724 (let ((here (point)) )
1725 ;; back up to the first preceding line (if any; else start of
1726 ;; buffer) that begins with a popular Python keyword, or a non-
1727 ;; whitespace and non-comment character. These are good places
1728 ;; to start parsing to see whether where we started is at a
1729 ;; non-zero nesting level. It may be slow for people who write
1730 ;; huge code blocks or huge lists ... tough beans.
1731 (re-search-backward py-parse-state-re nil 'move)
1732 (beginning-of-line)
1733 (parse-partial-sexp (point) here))))
1735 ;; if point is at a non-zero nesting level, returns the number of the
1736 ;; character that opens the smallest enclosing unclosed list; else
1737 ;; returns nil.
1738 (defun py-nesting-level ()
1739 (let ((status (py-parse-state)) )
1740 (if (zerop (car status))
1741 nil ; not in a nest
1742 (car (cdr status))))) ; char# of open bracket
1744 ;; t iff preceding line ends with backslash that's not in a comment
1745 (defun py-backslash-continuation-line-p ()
1746 (save-excursion
1747 (beginning-of-line)
1748 (and
1749 ;; use a cheap test first to avoid the regexp if possible
1750 ;; use 'eq' because char-after may return nil
1751 (eq (char-after (- (point) 2)) ?\\ )
1752 ;; make sure; since eq test passed, there is a preceding line
1753 (forward-line -1) ; always true -- side effect
1754 (looking-at py-continued-re))))
1756 ;; t iff current line is a continuation line
1757 (defun py-continuation-line-p ()
1758 (save-excursion
1759 (beginning-of-line)
1760 (or (py-backslash-continuation-line-p)
1761 (py-nesting-level))))
1763 ;; go to initial line of current statement; usually this is the line
1764 ;; we're on, but if we're on the 2nd or following lines of a
1765 ;; continuation block, we need to go up to the first line of the
1766 ;; block.
1768 ;; Tricky: We want to avoid quadratic-time behavior for long continued
1769 ;; blocks, whether of the backslash or open-bracket varieties, or a
1770 ;; mix of the two. The following manages to do that in the usual
1771 ;; cases.
1772 (defun py-goto-initial-line ()
1773 (let ( open-bracket-pos )
1774 (while (py-continuation-line-p)
1775 (beginning-of-line)
1776 (if (py-backslash-continuation-line-p)
1777 (while (py-backslash-continuation-line-p)
1778 (forward-line -1))
1779 ;; else zip out of nested brackets/braces/parens
1780 (while (setq open-bracket-pos (py-nesting-level))
1781 (goto-char open-bracket-pos)))))
1782 (beginning-of-line))
1784 ;; go to point right beyond final line of current statement; usually
1785 ;; this is the start of the next line, but if this is a multi-line
1786 ;; statement we need to skip over the continuation lines. Tricky:
1787 ;; Again we need to be clever to avoid quadratic time behavior.
1788 (defun py-goto-beyond-final-line ()
1789 (forward-line 1)
1790 (let (state)
1791 (while (and (py-continuation-line-p)
1792 (not (eobp)))
1793 ;; skip over the backslash flavor
1794 (while (and (py-backslash-continuation-line-p)
1795 (not (eobp)))
1796 (forward-line 1))
1797 ;; if in nest, zip to the end of the nest
1798 (setq state (py-parse-state))
1799 (if (and (not (zerop (car state)))
1800 (not (eobp)))
1801 (progn
1802 ;; BUG ALERT: I could swear, from reading the docs, that
1803 ;; the 3rd argument should be plain 0
1804 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1805 nil state)
1806 (forward-line 1))))))
1808 ;; t iff statement opens a block == iff it ends with a colon that's
1809 ;; not in a comment. point should be at the start of a statement
1810 (defun py-statement-opens-block-p ()
1811 (save-excursion
1812 (let ((start (point))
1813 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1814 (searching t)
1815 (answer nil)
1816 state)
1817 (goto-char start)
1818 (while searching
1819 ;; look for a colon with nothing after it except whitespace, and
1820 ;; maybe a comment
1821 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1822 finish t)
1823 (if (eq (point) finish) ; note: no `else' clause; just
1824 ; keep searching if we're not at
1825 ; the end yet
1826 ;; sure looks like it opens a block -- but it might
1827 ;; be in a comment
1828 (progn
1829 (setq searching nil) ; search is done either way
1830 (setq state (parse-partial-sexp start
1831 (match-beginning 0)))
1832 (setq answer (not (nth 4 state)))))
1833 ;; search failed: couldn't find another interesting colon
1834 (setq searching nil)))
1835 answer)))
1837 ;; go to point right beyond final line of block begun by the current
1838 ;; line. This is the same as where py-goto-beyond-final-line goes
1839 ;; unless we're on colon line, in which case we go to the end of the
1840 ;; block. assumes point is at bolp
1841 (defun py-goto-beyond-block ()
1842 (if (py-statement-opens-block-p)
1843 (py-mark-block nil 'just-move)
1844 (py-goto-beyond-final-line)))
1846 ;; go to start of first statement (not blank or comment or
1847 ;; continuation line) at or preceding point. returns t if there is
1848 ;; one, else nil
1849 (defun py-goto-statement-at-or-above ()
1850 (py-goto-initial-line)
1851 (if (looking-at py-blank-or-comment-re)
1852 ;; skip back over blank & comment lines
1853 ;; note: will skip a blank or comment line that happens to be
1854 ;; a continuation line too
1855 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1856 (progn (py-goto-initial-line) t)
1857 nil)
1860 ;; go to start of first statement (not blank or comment or
1861 ;; continuation line) following the statement containing point returns
1862 ;; t if there is one, else nil
1863 (defun py-goto-statement-below ()
1864 (beginning-of-line)
1865 (let ((start (point)))
1866 (py-goto-beyond-final-line)
1867 (while (and
1868 (looking-at py-blank-or-comment-re)
1869 (not (eobp)))
1870 (forward-line 1))
1871 (if (eobp)
1872 (progn (goto-char start) nil)
1873 t)))
1875 ;; go to start of statement, at or preceding point, starting with
1876 ;; keyword KEY. Skips blank lines and non-indenting comments upward
1877 ;; first. If that statement starts with KEY, done, else go back to
1878 ;; first enclosing block starting with KEY. If successful, leaves
1879 ;; point at the start of the KEY line & returns t. Else leaves point
1880 ;; at an undefined place & returns nil.
1881 (defun py-go-up-tree-to-keyword (key)
1882 ;; skip blanks and non-indenting #
1883 (py-goto-initial-line)
1884 (while (and
1885 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1886 (zerop (forward-line -1))) ; go back
1887 nil)
1888 (py-goto-initial-line)
1889 (let* ((re (concat "[ \t]*" key "\\b"))
1890 (case-fold-search nil) ; let* so looking-at sees this
1891 (found (looking-at re))
1892 (dead nil))
1893 (while (not (or found dead))
1894 (condition-case nil ; in case no enclosing block
1895 (py-goto-block-up 'no-mark)
1896 (error (setq dead t)))
1897 (or dead (setq found (looking-at re))))
1898 (beginning-of-line)
1899 found))
1901 ;; return string in buffer from start of indentation to end of line;
1902 ;; prefix "..." if leading whitespace was skipped
1903 (defun py-suck-up-leading-text ()
1904 (save-excursion
1905 (back-to-indentation)
1906 (concat
1907 (if (bolp) "" "...")
1908 (buffer-substring (point) (progn (end-of-line) (point))))))
1910 ;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1911 ;; as a Lisp symbol; return nil if none
1912 (defun py-suck-up-first-keyword ()
1913 (let ((case-fold-search nil))
1914 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1915 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1916 nil)))
1918 (defun py-make-temp-name ()
1919 (make-temp-name
1920 (concat (file-name-as-directory py-temp-directory) "python")))
1922 (defun py-delete-file-silently (fname)
1923 (condition-case nil
1924 (delete-file fname)
1925 (error nil)))
1927 (defun py-kill-emacs-hook ()
1928 ;; delete our temp files
1929 (while py-file-queue
1930 (py-delete-file-silently (car py-file-queue))
1931 (setq py-file-queue (cdr py-file-queue)))
1932 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1933 ;; run the hook we inherited, if any
1934 (and py-inherited-kill-emacs-hook
1935 (funcall py-inherited-kill-emacs-hook))))
1937 ;; make PROCESS's buffer visible, append STRING to it, and force
1938 ;; display; also make shell-mode believe the user typed this string,
1939 ;; so that kill-output-from-shell and show-output-from-shell work
1940 ;; "right"
1941 (defun py-append-to-process-buffer (process string)
1942 (let ((cbuf (current-buffer))
1943 (pbuf (process-buffer process))
1944 (py-scroll-process-buffer t))
1945 (set-buffer pbuf)
1946 (goto-char (point-max))
1947 (move-marker (process-mark process) (point))
1948 (if (not (or py-this-is-emacs-19-p
1949 py-this-is-lucid-emacs-p))
1950 (move-marker last-input-start (point))) ; muck w/ shell-mode
1951 (funcall (process-filter process) process string)
1952 (if (not (or py-this-is-emacs-19-p
1953 py-this-is-lucid-emacs-p))
1954 (move-marker last-input-end (point))) ; muck w/ shell-mode
1955 (set-buffer cbuf))
1956 (sit-for 0))
1958 (defun py-keep-region-active ()
1959 ;; do whatever is necessary to keep the region active in XEmacs.
1960 ;; Ignore byte-compiler warnings you might see. Also note that
1961 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1962 ;; require us to take explicit action.
1963 (and (boundp 'zmacs-region-stays)
1964 (setq zmacs-region-stays t)))
1967 (defconst py-version "2.26"
1968 "`python-mode' version number.")
1969 (defconst py-help-address "python-mode@python.org"
1970 "Address accepting submission of bug reports.")
1972 (defun py-version ()
1973 "Echo the current version of `python-mode' in the minibuffer."
1974 (interactive)
1975 (message "Using `python-mode' version %s" py-version)
1976 (py-keep-region-active))
1978 ;; only works under Emacs 19
1979 ;(eval-when-compile
1980 ; (require 'reporter))
1982 (defun py-submit-bug-report (enhancement-p)
1983 "Submit via mail a bug report on `python-mode'.
1984 With \\[universal-argument] just submit an enhancement request."
1985 (interactive
1986 (list (not (y-or-n-p
1987 "Is this a bug report? (hit `n' to send other comments) "))))
1988 (let ((reporter-prompt-for-summary-p (if enhancement-p
1989 "(Very) brief summary: "
1990 t)))
1991 (require 'reporter)
1992 (reporter-submit-bug-report
1993 py-help-address ;address
1994 (concat "python-mode " py-version) ;pkgname
1995 ;; varlist
1996 (if enhancement-p nil
1997 '(py-python-command
1998 py-indent-offset
1999 py-block-comment-prefix
2000 py-scroll-process-buffer
2001 py-temp-directory
2002 py-beep-if-tab-change))
2003 nil ;pre-hooks
2004 nil ;post-hooks
2005 "Dear Barry,") ;salutation
2006 (if enhancement-p nil
2007 (set-mark (point))
2008 (insert
2009 "Please replace this text with a sufficiently large code sample\n\
2010 and an exact recipe so that I can reproduce your problem. Failure\n\
2011 to do so may mean a greater delay in fixing your bug.\n\n")
2012 (exchange-point-and-mark)
2013 (py-keep-region-active))))
2016 ;; arrange to kill temp files when Emacs exists
2017 (if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2018 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2019 ;; have to trust that other people are as respectful of our hook
2020 ;; fiddling as we are of theirs
2021 (if (boundp 'py-inherited-kill-emacs-hook)
2022 ;; we were loaded before -- trust others not to have screwed us
2023 ;; in the meantime (no choice, really)
2025 ;; else arrange for our hook to run theirs
2026 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2027 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2031 (provide 'python-mode)
2032 ;;; python-mode.el ends here