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