blob: a1ff2c7df11243b6b13ed415ba06ad7ec686c522 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
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: ???
9;; Version: $Revision$
10;; Last Modified: $Date$
11;; Keywords: python editing language major-mode
12
13;; This file is not part of GNU Emacs.
14
15;; This program is free software; you can redistribute it and/or modify
16;; it under the terms of the GNU General Public License as published by
17;; the Free Software Foundation; either version 2 of the License, or
18;; (at your option) any later version.
19;;
20;; This program is distributed in the hope that it will be useful,
21;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23;; GNU General Public License for more details.
24;;
25;; You should have received a copy of the GNU General Public License
26;; along with this program; if not, write to the Free Software
27;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28
29;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000030;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000031;; This is a major mode for editing Python programs. It was developed
32;; by Tim Peters <tim@ksr.com> after an original idea by Michael
33;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
34;; have undertaken maintenance of the mode. Here is Tim's original
35;; copyright notice:
36
37;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Barry Warsaw7ae77681994-12-12 20:38:05 +000038;; Copyright (c) 1992,1993,1994 Tim Peters
39;;
40;; This software is provided as-is, without express or implied warranty.
41;; Permission to use, copy, modify, distribute or sell this software,
42;; without fee, for any purpose and by any individual or organization, is
43;; hereby granted, provided that the above copyright notice and this
44;; paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000045;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
46
47;; At some point this mode will undergo a rewrite to bring it more in
48;; line with GNU Emacs Lisp coding standards. But all in all, the
49;; mode works exceedingly well.
50
51;; The following statements, placed in your .emacs file or
52;; site-init.el, will cause this file to be autoloaded, and
53;; python-mode invoked, when visiting .py files (assuming this file is
54;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000055;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000056;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000057;; (setq auto-mode-alist
58;; (cons '("\\.py$" . python-mode) auto-mode-alist))
59
Barry Warsaw7b0f5681995-03-08 21:33:04 +000060;; Here's a brief to do list:
61;;
62;; 1. Better integration with gud-mode for debugging.
63;; 2. Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw7ae77681994-12-12 20:38:05 +000064
Barry Warsaw7b0f5681995-03-08 21:33:04 +000065;; If you can think of more things you'd like to see, drop me a line.
66;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
67;;
68;; Note that I only test things on XEmacs (currently 19.11). If you
69;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
70;; patches.
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsaw7b0f5681995-03-08 21:33:04 +000072;; LCD Archive Entry:
73;; python-mode|Barry A. Warsaw|bwarsaw@cnri.reston.va.us
74;; |Major mode for editing Python programs
75;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000076
Barry Warsaw7b0f5681995-03-08 21:33:04 +000077;;; Code:
78
79
80;; user definable variables
81;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000082
83(defvar py-python-command "python"
84 "*Shell command used to start Python interpreter.")
85
86(defvar py-indent-offset 8 ; argue with Guido <grin>
87 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000088Note that `\\[py-guess-indent-offset]' can usually guess a good value
89when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000090
91(defvar py-block-comment-prefix "##"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000092 "*String used by `py-comment-region' to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000093This should follow the convention for non-indenting comment lines so
94that the indentation commands won't get confused (i.e., the string
95should be of the form `#x...' where `x' is not a blank or a tab, and
96`...' is arbitrary).")
97
98(defvar py-scroll-process-buffer t
99 "*Scroll Python process buffer as output arrives.
100If nil, the Python process buffer acts, with respect to scrolling, like
101Shell-mode buffers normally act. This is surprisingly complicated and
102so won't be explained here; in fact, you can't get the whole story
103without studying the Emacs C code.
104
105If non-nil, the behavior is different in two respects (which are
106slightly inaccurate in the interest of brevity):
107
108 - If the buffer is in a window, and you left point at its end, the
109 window will scroll as new output arrives, and point will move to the
110 buffer's end, even if the window is not the selected window (that
111 being the one the cursor is in). The usual behavior for shell-mode
112 windows is not to scroll, and to leave point where it was, if the
113 buffer is in a window other than the selected window.
114
115 - If the buffer is not visible in any window, and you left point at
116 its end, the buffer will be popped into a window as soon as more
117 output arrives. This is handy if you have a long-running
118 computation and don't want to tie up screen area waiting for the
119 output. The usual behavior for a shell-mode buffer is to stay
120 invisible until you explicitly visit it.
121
122Note the `and if you left point at its end' clauses in both of the
123above: you can `turn off' the special behaviors while output is in
124progress, by visiting the Python buffer and moving point to anywhere
125besides the end. Then the buffer won't scroll, point will remain where
126you leave it, and if you hide the buffer it will stay hidden until you
127visit it again. You can enable and disable the special behaviors as
128often as you like, while output is in progress, by (respectively) moving
129point to, or away from, the end of the buffer.
130
131Warning: If you expect a large amount of output, you'll probably be
132happier setting this option to nil.
133
134Obscure: `End of buffer' above should really say `at or beyond the
135process mark', but if you know what that means you didn't need to be
136told <grin>.")
137
138(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000139 (let ((ok '(lambda (x)
140 (and x
141 (setq x (expand-file-name x)) ; always true
142 (file-directory-p x)
143 (file-writable-p x)
144 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000145 (or (funcall ok (getenv "TMPDIR"))
146 (funcall ok "/usr/tmp")
147 (funcall ok "/tmp")
148 (funcall ok ".")
149 (error
150 "Couldn't find a usable temp directory -- set py-temp-directory")))
151 "*Directory used for temp files created by a *Python* process.
152By default, the first directory from this list that exists and that you
153can write into: the value (if any) of the environment variable TMPDIR,
154/usr/tmp, /tmp, or the current directory.")
155
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000156(defvar py-beep-if-tab-change t
157 "*Ring the bell if tab-width is changed.
158If a comment of the form
159
160 \t# vi:set tabsize=<number>:
161
162is found before the first code line when the file is entered, and the
163current value of (the general Emacs variable) `tab-width' does not
164equal <number>, `tab-width' is set to <number>, a message saying so is
165displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
166the Emacs bell is also rung as a warning.")
167
Barry Warsaw4f005cf1995-03-08 22:02:44 +0000168(defvar python-font-lock-keywords
Barry Warsaw65bc7a71995-03-08 22:25:47 +0000169 (list
170 (cons
171 (concat
172 "\\<\\("
173 (mapconcat
174 'identity
175 '("access" "and" "break" "continue"
176 "del" "elif" "else" "except"
177 "exec" "finally" "for" "from"
178 "global" "if" "import" "in"
179 "is" "lambda" "not" "or"
180 "pass" "print" "raise" "return"
181 "try" "while" "def" "class"
182 )
183 "\\|")
184 "\\)\\>")
185 1)
186 ;; functions
187 '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
188 ;; classes
189 '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
190 )
Barry Warsawc723b751995-03-08 22:03:16 +0000191 "*Additional keywords to highlight `python-mode' buffers.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000192
193
194;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
195;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
196
197;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
198;; seems to be the standard way of checking this.
199;; BAW - This is *not* the right solution. When at all possible,
200;; instead of testing for the version of Emacs, use feature tests.
201
202(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
203(setq py-this-is-emacs-19-p
204 (and
205 (not py-this-is-lucid-emacs-p)
206 (string-match "^19\\." emacs-version)))
207
Barry Warsaw7ae77681994-12-12 20:38:05 +0000208;; have to bind py-file-queue before installing the kill-emacs hook
209(defvar py-file-queue nil
210 "Queue of Python temp files awaiting execution.
211Currently-active file is at the head of the list.")
212
213;; define a mode-specific abbrev table for those who use such things
214(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000215 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000216(define-abbrev-table 'python-mode-abbrev-table nil)
217
Barry Warsaw7ae77681994-12-12 20:38:05 +0000218(defvar python-mode-hook nil
219 "*Hook called by `python-mode'.")
220
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000221;; in previous version of python-mode.el, the hook was incorrectly
222;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000223(and (fboundp 'make-obsolete-variable)
224 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
225
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000226(defvar py-mode-map ()
227 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000228
Barry Warsaw7ae77681994-12-12 20:38:05 +0000229(if py-mode-map
230 ()
231 (setq py-mode-map (make-sparse-keymap))
232
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000233 ;; shadow global bindings for newline-and-indent w/ the py- version.
234 ;; BAW - this is extremely bad form, but I'm not going to change it
235 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000236 (mapcar (function (lambda (key)
237 (define-key
238 py-mode-map key 'py-newline-and-indent)))
239 (where-is-internal 'newline-and-indent))
240
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000241 ;; BAW - you could do it this way, but its not considered proper
242 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243 (mapcar (function
244 (lambda (x)
245 (define-key py-mode-map (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000246 '(("\C-c\C-c" . py-execute-buffer)
247 ("\C-c|" . py-execute-region)
248 ("\C-c!" . py-shell)
249 ("\177" . py-delete-char)
250 ("\n" . py-newline-and-indent)
251 ("\C-c:" . py-guess-indent-offset)
252 ("\C-c\t" . py-indent-region)
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)
Barry Warsaw850437a1995-03-08 21:50:28 +0000258 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000259 ("\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)
Barry Warsaw850437a1995-03-08 21:50:28 +0000264 ( "\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)
268 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000270(defvar py-mode-syntax-table nil
271 "Syntax table used in `python-mode' buffers.")
272
Barry Warsaw7ae77681994-12-12 20:38:05 +0000273(if py-mode-syntax-table
274 ()
275 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000277 (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
294
295(defconst py-stringlit-re
296 (concat
297 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
298 "\\|" ; or
299 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000300 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000301
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 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000308 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000309
310(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000311 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000312
Barry Warsaw7ae77681994-12-12 20:38:05 +0000313
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000314
315;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000316(defun python-mode ()
317 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000318To submit a problem report, enter `\\[py-submit-bug-report]' from a
319`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
320documentation. To see what version of `python-mode' you are running,
321enter `\\[py-version]'.
322
323This mode knows about Python indentation, tokens, comments and
324continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000325
326COMMANDS
327\\{py-mode-map}
328VARIABLES
329
330py-indent-offset\tindentation increment
331py-block-comment-prefix\tcomment string used by py-comment-region
332py-python-command\tshell command to invoke Python interpreter
333py-scroll-process-buffer\talways scroll Python process buffer
334py-temp-directory\tdirectory used for temp files (if needed)
335py-beep-if-tab-change\tring the bell if tab-width is changed"
336 (interactive)
337 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000338 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000339 (setq major-mode 'python-mode
340 mode-name "Python"
341 local-abbrev-table python-mode-abbrev-table)
342 (use-local-map py-mode-map)
343 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000344 (mapcar (function (lambda (x)
345 (make-local-variable (car x))
346 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000347 '((paragraph-separate . "^[ \t]*$")
348 (paragraph-start . "^[ \t]*$")
349 (require-final-newline . t)
350 (comment-start . "# ")
351 (comment-start-skip . "# *")
352 (comment-column . 40)
353 (indent-region-function . py-indent-region)
354 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000356 ;;
357 ;; not sure where the magic comment has to be; to save time
358 ;; searching for a rarity, we give up if it's not found prior to the
359 ;; first executable statement.
360 ;;
361 ;; BAW - on first glance, this seems like complete hackery. Why was
362 ;; this necessary, and is it still necessary?
363 (let ((case-fold-search nil)
364 (start (point))
365 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000366 (if (re-search-forward
367 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
368 (prog2 (py-next-statement 1) (point) (goto-char 1))
369 t)
370 (progn
371 (setq new-tab-width
372 (string-to-int
373 (buffer-substring (match-beginning 1) (match-end 1))))
374 (if (= tab-width new-tab-width)
375 nil
376 (setq tab-width new-tab-width)
377 (message "Caution: tab-width changed to %d" new-tab-width)
378 (if py-beep-if-tab-change (beep)))))
379 (goto-char start))
380
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000381 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000382 (if python-mode-hook
383 (run-hooks 'python-mode-hook)
384 (run-hooks 'py-mode-hook)))
385
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000386
Barry Warsaw7ae77681994-12-12 20:38:05 +0000387;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000388(defun py-shell ()
389 "Start an interactive Python interpreter in another window.
390This is like Shell mode, except that Python is running in the window
391instead of a shell. See the `Interactive Shell' and `Shell Mode'
392sections of the Emacs manual for details, especially for the key
393bindings active in the `*Python*' buffer.
394
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000395See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000396behavior in the process window.
397
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000398Warning: Don't use an interactive Python if you change sys.ps1 or
399sys.ps2 from their default values, or if you're running code that
400prints `>>> ' or `... ' at the start of a line. `python-mode' can't
401distinguish your output from Python's output, and assumes that `>>> '
402at the start of a line is a prompt from Python. Similarly, the Emacs
403Shell mode code assumes that both `>>> ' and `... ' at the start of a
404line are Python prompts. Bad things can happen if you fool either
405mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000406
407Warning: If you do any editing *in* the process buffer *while* the
408buffer is accepting output from Python, do NOT attempt to `undo' the
409changes. Some of the output (nowhere near the parts you changed!) may
410be lost if you do. This appears to be an Emacs bug, an unfortunate
411interaction between undo and process filters; the same problem exists in
412non-Python process buffers using the default (Emacs-supplied) process
413filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 ;; BAW - should undo be disabled in the python process buffer, if
415 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000416 (interactive)
417 (if py-this-is-emacs-19-p
418 (progn
419 (require 'comint)
420 (switch-to-buffer-other-window
421 (make-comint "Python" py-python-command)))
422 (progn
423 (require 'shell)
424 (switch-to-buffer-other-window
425 (make-shell "Python" py-python-command))))
426 (make-local-variable 'shell-prompt-pattern)
427 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
428 (set-process-filter (get-buffer-process (current-buffer))
429 'py-process-filter)
430 (set-syntax-table py-mode-syntax-table))
431
432(defun py-execute-region (start end)
433 "Send the region between START and END to a Python interpreter.
434If there is a *Python* process it is used.
435
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000436Hint: If you want to execute part of a Python file several times
437\(e.g., perhaps you're developing a function and want to flesh it out
438a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
439the region of interest, and send the code to a *Python* process via
440`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000441
442Following are subtleties to note when using a *Python* process:
443
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000444If a *Python* process is used, the region is copied into a temporary
445file (in directory `py-temp-directory'), and an `execfile' command is
446sent to Python naming that file. If you send regions faster than
447Python can execute them, `python-mode' will save them into distinct
448temp files, and execute the next one in the queue the next time it
449sees a `>>> ' prompt from Python. Each time this happens, the process
450buffer is popped into a window (if it's not already in some window) so
451you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000452
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000454
455is inserted at the end.
456
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000457Caution: No more than 26 regions can be pending at any given time.
458This limit is (indirectly) inherited from libc's mktemp(3).
459`python-mode' does not try to protect you from exceeding the limit.
460It's extremely unlikely that you'll get anywhere close to the limit in
461practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000462
463See the `\\[py-shell]' docs for additional warnings."
464 (interactive "r")
465 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000466 (let ((pyproc (get-process "Python"))
467 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000468 (if (null pyproc)
469 (shell-command-on-region start end py-python-command)
470 ;; else feed it thru a temp file
471 (setq fname (py-make-temp-name))
472 (write-region start end fname nil 'no-msg)
473 (setq py-file-queue (append py-file-queue (list fname)))
474 (if (cdr py-file-queue)
475 (message "File %s queued for execution" fname)
476 ;; else
477 (py-execute-file pyproc fname)))))
478
479(defun py-execute-file (pyproc fname)
480 (py-append-to-process-buffer
481 pyproc
482 (format "## working on region in file %s ...\n" fname))
483 (process-send-string pyproc (format "execfile('%s')\n" fname)))
484
485(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000486 (let ((curbuf (current-buffer))
487 (pbuf (process-buffer pyproc))
488 (pmark (process-mark pyproc))
489 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000490
491 ;; make sure we switch to a different buffer at least once. if we
492 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000493 ;; window, and point is before the end, and lots of output is
494 ;; coming at a fast pace, then (a) simple cursor-movement commands
495 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
496 ;; to have a visible effect (the window just doesn't get updated,
497 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
498 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000499 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000500 ;; #b makes no sense to me at all. #a almost makes sense: unless
501 ;; we actually change buffers, set_buffer_internal in buffer.c
502 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
503 ;; seems to make the Emacs command loop reluctant to update the
504 ;; display. Perhaps the default process filter in process.c's
505 ;; read_process_output has update_mode_lines++ for a similar
506 ;; reason? beats me ...
507
508 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000509 (if (eq curbuf pbuf) ; mysterious ugly hack
510 (set-buffer (get-buffer-create "*scratch*")))
511
512 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000513 (let* ((start (point))
514 (goback (< start pmark))
515 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000516 (goto-char pmark)
517 (insert string)
518 (move-marker pmark (point))
519 (setq file-finished
520 (and py-file-queue
521 (equal ">>> "
522 (buffer-substring
523 (prog2 (beginning-of-line) (point)
524 (goto-char pmark))
525 (point)))))
526 (if goback (goto-char start)
527 ;; else
528 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000529 (let* ((pop-up-windows t)
530 (pwin (display-buffer pbuf)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000531 (set-window-point pwin (point))))))
532 (set-buffer curbuf)
533 (if file-finished
534 (progn
535 (py-delete-file-silently (car py-file-queue))
536 (setq py-file-queue (cdr py-file-queue))
537 (if py-file-queue
538 (py-execute-file pyproc (car py-file-queue)))))))
539
540(defun py-execute-buffer ()
541 "Send the contents of the buffer to a Python interpreter.
542If there is a *Python* process buffer it is used. If a clipping
543restriction is in effect, only the accessible portion of the buffer is
544sent. A trailing newline will be supplied if needed.
545
546See the `\\[py-execute-region]' docs for an account of some subtleties."
547 (interactive)
548 (py-execute-region (point-min) (point-max)))
549
550
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000551
552;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000553(defun py-delete-char ()
554 "Reduce indentation or delete character.
555If point is at the leftmost column, deletes the preceding newline.
556
557Else if point is at the leftmost non-blank character of a line that is
558neither a continuation line nor a non-indenting comment line, or if
559point is at the end of a blank line, reduces the indentation to match
560that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000561opened the block is displayed in the echo area to help you keep track
562of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000563
564Else the preceding character is deleted, converting a tab to spaces if
565needed so that only a single column position is deleted."
566 (interactive "*")
567 (if (or (/= (current-indentation) (current-column))
568 (bolp)
569 (py-continuation-line-p)
570 (looking-at "#[^ \t\n]")) ; non-indenting #
571 (backward-delete-char-untabify 1)
572 ;; else indent the same as the colon line that opened the block
573
574 ;; force non-blank so py-goto-block-up doesn't ignore it
575 (insert-char ?* 1)
576 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000577 (let ((base-indent 0) ; indentation of base line
578 (base-text "") ; and text of base line
579 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000580 (condition-case nil ; in case no enclosing block
581 (save-excursion
582 (py-goto-block-up 'no-mark)
583 (setq base-indent (current-indentation)
584 base-text (py-suck-up-leading-text)
585 base-found-p t))
586 (error nil))
587 (delete-char 1) ; toss the dummy character
588 (delete-horizontal-space)
589 (indent-to base-indent)
590 (if base-found-p
591 (message "Closes block: %s" base-text)))))
592
593(defun py-indent-line ()
594 "Fix the indentation of the current line according to Python rules."
595 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000596 (let* ((ci (current-indentation))
597 (move-to-indentation-p (<= (current-column) ci))
598 (need (py-compute-indentation)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000599 (if (/= ci need)
600 (save-excursion
601 (beginning-of-line)
602 (delete-horizontal-space)
603 (indent-to need)))
604 (if move-to-indentation-p (back-to-indentation))))
605
606(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000607 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000608This is just `strives to' because correct indentation can't be computed
609from scratch for Python code. In general, deletes the whitespace before
610point, inserts a newline, and takes an educated guess as to how you want
611the new line indented."
612 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000613 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000614 (if (< ci (current-column)) ; if point beyond indentation
615 (newline-and-indent)
616 ;; else try to act like newline-and-indent "normally" acts
617 (beginning-of-line)
618 (insert-char ?\n 1)
619 (move-to-column ci))))
620
621(defun py-compute-indentation ()
622 (save-excursion
623 (beginning-of-line)
624 (cond
625 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000626 ((py-continuation-line-p)
627 (let ((startpos (point))
628 (open-bracket-pos (py-nesting-level))
629 endpos searching found)
630 (if open-bracket-pos
631 (progn
632 ;; align with first item in list; else a normal
633 ;; indent beyond the line with the open bracket
634 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
635 ;; is the first list item on the same line?
636 (skip-chars-forward " \t")
637 (if (null (memq (following-char) '(?\n ?# ?\\)))
638 ; yes, so line up with it
639 (current-column)
640 ;; first list item on another line, or doesn't exist yet
641 (forward-line 1)
642 (while (and (< (point) startpos)
643 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
644 (forward-line 1))
645 (if (< (point) startpos)
646 ;; again mimic the first list item
647 (current-indentation)
648 ;; else they're about to enter the first item
649 (goto-char open-bracket-pos)
650 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000651
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000652 ;; else on backslash continuation line
653 (forward-line -1)
654 (if (py-continuation-line-p) ; on at least 3rd line in block
655 (current-indentation) ; so just continue the pattern
656 ;; else started on 2nd line in block, so indent more.
657 ;; if base line is an assignment with a start on a RHS,
658 ;; indent to 2 beyond the leftmost "="; else skip first
659 ;; chunk of non-whitespace characters on base line, + 1 more
660 ;; column
661 (end-of-line)
662 (setq endpos (point) searching t)
663 (back-to-indentation)
664 (setq startpos (point))
665 ;; look at all "=" from left to right, stopping at first
666 ;; one not nested in a list or string
667 (while searching
668 (skip-chars-forward "^=" endpos)
669 (if (= (point) endpos)
670 (setq searching nil)
671 (forward-char 1)
672 (setq state (parse-partial-sexp startpos (point)))
673 (if (and (zerop (car state)) ; not in a bracket
674 (null (nth 3 state))) ; & not in a string
675 (progn
676 (setq searching nil) ; done searching in any case
677 (setq found
678 (not (or
679 (eq (following-char) ?=)
680 (memq (char-after (- (point) 2))
681 '(?< ?> ?!)))))))))
682 (if (or (not found) ; not an assignment
683 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
684 (progn
685 (goto-char startpos)
686 (skip-chars-forward "^ \t\n")))
687 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000688
689 ;; not on a continuation line
690
691 ;; if at start of restriction, or on a non-indenting comment line,
692 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000693 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
694 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000695
696 ;; else indentation based on that of the statement that precedes
697 ;; us; use the first line of that statement to establish the base,
698 ;; in case the user forced a non-std indentation for the
699 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000700 (t
701 ;; skip back over blank & non-indenting comment lines
702 ;; note: will skip a blank or non-indenting comment line that
703 ;; happens to be a continuation line too
704 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
705 nil 'move)
706 ;; if we landed inside a string, go to the beginning of that
707 ;; string. this handles triple quoted, multi-line spanning
708 ;; strings.
709 (let ((state (parse-partial-sexp
710 (save-excursion (beginning-of-python-def-or-class)
711 (point))
712 (point))))
713 (if (nth 3 state)
714 (goto-char (nth 2 state))))
715 (py-goto-initial-line)
716 (if (py-statement-opens-block-p)
717 (+ (current-indentation) py-indent-offset)
718 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000719
720(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000721 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000722By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000723`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000724Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000725`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000726their own buffer-local copy), both those currently existing and those
727created later in the Emacs session.
728
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000729Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000730There's no excuse for such foolishness, but sometimes you have to deal
731with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000732`py-indent-offset' to what it thinks it was when they created the
733mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000734
735Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000736looking for a line that opens a block of code. `py-indent-offset' is
737set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738statement following it. If the search doesn't succeed going forward,
739it's tried again going backward."
740 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000741 (let (new-value
742 (start (point))
743 restart
744 (found nil)
745 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746 (py-goto-initial-line)
747 (while (not (or found (eobp)))
748 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
749 (progn
750 (setq restart (point))
751 (py-goto-initial-line)
752 (if (py-statement-opens-block-p)
753 (setq found t)
754 (goto-char restart)))))
755 (if found
756 ()
757 (goto-char start)
758 (py-goto-initial-line)
759 (while (not (or found (bobp)))
760 (setq found
761 (and
762 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
763 (or (py-goto-initial-line) t) ; always true -- side effect
764 (py-statement-opens-block-p)))))
765 (setq colon-indent (current-indentation)
766 found (and found (zerop (py-next-statement 1)))
767 new-value (- (current-indentation) colon-indent))
768 (goto-char start)
769 (if found
770 (progn
771 (funcall (if global 'kill-local-variable 'make-local-variable)
772 'py-indent-offset)
773 (setq py-indent-offset new-value)
774 (message "%s value of py-indent-offset set to %d"
775 (if global "Global" "Local")
776 py-indent-offset))
777 (error "Sorry, couldn't guess a value for py-indent-offset"))))
778
779(defun py-shift-region (start end count)
780 (save-excursion
781 (goto-char end) (beginning-of-line) (setq end (point))
782 (goto-char start) (beginning-of-line) (setq start (point))
783 (indent-rigidly start end count)))
784
785(defun py-shift-region-left (start end &optional count)
786 "Shift region of Python code to the left.
787The lines from the line containing the start of the current region up
788to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000789shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000790
791If a prefix argument is given, the region is instead shifted by that
792many columns."
793 (interactive "*r\nP") ; region; raw prefix arg
794 (py-shift-region start end
795 (- (prefix-numeric-value
796 (or count py-indent-offset)))))
797
798(defun py-shift-region-right (start end &optional count)
799 "Shift region of Python code to the right.
800The lines from the line containing the start of the current region up
801to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000802shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000803
804If a prefix argument is given, the region is instead shifted by that
805many columns."
806 (interactive "*r\nP") ; region; raw prefix arg
807 (py-shift-region start end (prefix-numeric-value
808 (or count py-indent-offset))))
809
810(defun py-indent-region (start end &optional indent-offset)
811 "Reindent a region of Python code.
812The lines from the line containing the start of the current region up
813to (but not including) the line containing the end of the region are
814reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000815character in the first column, the first line is left alone and the
816rest of the region is reindented with respect to it. Else the entire
817region is reindented with respect to the (closest code or
818indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000819
820This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000821control structures are introduced or removed, or to reformat code
822using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000823
824If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000825the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000826used.
827
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000828Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000829is called! This function does not compute proper indentation from
830scratch (that's impossible in Python), it merely adjusts the existing
831indentation to be correct in context.
832
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000833Warning: This function really has no idea what to do with
834non-indenting comment lines, and shifts them as if they were indenting
835comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000836
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000837Special cases: whitespace is deleted from blank lines; continuation
838lines are shifted by the same amount their initial line was shifted,
839in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000840initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000841 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000842 (save-excursion
843 (goto-char end) (beginning-of-line) (setq end (point-marker))
844 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000845 (let ((py-indent-offset (prefix-numeric-value
846 (or indent-offset py-indent-offset)))
847 (indents '(-1)) ; stack of active indent levels
848 (target-column 0) ; column to which to indent
849 (base-shifted-by 0) ; amount last base line was shifted
850 (indent-base (if (looking-at "[ \t\n]")
851 (py-compute-indentation)
852 0))
853 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000854 (while (< (point) end)
855 (setq ci (current-indentation))
856 ;; figure out appropriate target column
857 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000858 ((or (eq (following-char) ?#) ; comment in column 1
859 (looking-at "[ \t]*$")) ; entirely blank
860 (setq target-column 0))
861 ((py-continuation-line-p) ; shift relative to base line
862 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000863 (t ; new base line
864 (if (> ci (car indents)) ; going deeper; push it
865 (setq indents (cons ci indents))
866 ;; else we should have seen this indent before
867 (setq indents (memq ci indents)) ; pop deeper indents
868 (if (null indents)
869 (error "Bad indentation in region, at line %d"
870 (save-restriction
871 (widen)
872 (1+ (count-lines 1 (point)))))))
873 (setq target-column (+ indent-base
874 (* py-indent-offset
875 (- (length indents) 2))))
876 (setq base-shifted-by (- target-column ci))))
877 ;; shift as needed
878 (if (/= ci target-column)
879 (progn
880 (delete-horizontal-space)
881 (indent-to target-column)))
882 (forward-line 1))))
883 (set-marker end nil))
884
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000885
886;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887(defun py-previous-statement (count)
888 "Go to the start of previous Python statement.
889If the statement at point is the i'th Python statement, goes to the
890start of statement i-COUNT. If there is no such statement, goes to the
891first statement. Returns count of statements left to move.
892`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000893 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000894 (if (< count 0) (py-next-statement (- count))
895 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000896 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000897 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000898 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000899 (> count 0)
900 (zerop (forward-line -1))
901 (py-goto-statement-at-or-above))
902 (setq count (1- count)))
903 (if (> count 0) (goto-char start)))
904 count))
905
906(defun py-next-statement (count)
907 "Go to the start of next Python statement.
908If the statement at point is the i'th Python statement, goes to the
909start of statement i+COUNT. If there is no such statement, goes to the
910last statement. Returns count of statements left to move. `Statements'
911do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000912 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000913 (if (< count 0) (py-previous-statement (- count))
914 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000915 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918 (> count 0)
919 (py-goto-statement-below))
920 (setq count (1- count)))
921 (if (> count 0) (goto-char start)))
922 count))
923
924(defun py-goto-block-up (&optional nomark)
925 "Move up to start of current block.
926Go to the statement that starts the smallest enclosing block; roughly
927speaking, this will be the closest preceding statement that ends with a
928colon and is indented less than the statement you started on. If
929successful, also sets the mark to the starting point.
930
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000931`\\[py-mark-block]' can be used afterward to mark the whole code
932block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000933
934If called from a program, the mark will not be set if optional argument
935NOMARK is not nil."
936 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000937 (let ((start (point))
938 (found nil)
939 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940 (py-goto-initial-line)
941 ;; if on blank or non-indenting comment line, use the preceding stmt
942 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
943 (progn
944 (py-goto-statement-at-or-above)
945 (setq found (py-statement-opens-block-p))))
946 ;; search back for colon line indented less
947 (setq initial-indent (current-indentation))
948 (if (zerop initial-indent)
949 ;; force fast exit
950 (goto-char (point-min)))
951 (while (not (or found (bobp)))
952 (setq found
953 (and
954 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
955 (or (py-goto-initial-line) t) ; always true -- side effect
956 (< (current-indentation) initial-indent)
957 (py-statement-opens-block-p))))
958 (if found
959 (progn
960 (or nomark (push-mark start))
961 (back-to-indentation))
962 (goto-char start)
963 (error "Enclosing block not found"))))
964
965(defun beginning-of-python-def-or-class (&optional class)
966 "Move point to start of def (or class, with prefix arg).
967
968Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000969arg, looks for a `class' instead. The docs assume the `def' case;
970just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000972If point is in a def statement already, and after the `d', simply
973moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000974
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000975Else (point is not in a def statement, or at or before the `d' of a
976def statement), searches for the closest preceding def statement, and
977leaves point at its start. If no such statement can be found, leaves
978point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000979
980Returns t iff a def statement is found by these rules.
981
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000982Note that doing this command repeatedly will take you closer to the
983start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000984
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000985If you want to mark the current def/class, see
986`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000988 (let ((at-or-before-p (<= (current-column) (current-indentation)))
989 (start-of-line (progn (beginning-of-line) (point)))
990 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000991 (if (or (/= start-of-stmt start-of-line)
992 (not at-or-before-p))
993 (end-of-line)) ; OK to match on this line
994 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000995 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996
997(defun end-of-python-def-or-class (&optional class)
998 "Move point beyond end of def (or class, with prefix arg) body.
999
1000By default, looks for an appropriate `def'. If you supply a prefix arg,
1001looks for a `class' instead. The docs assume the `def' case; just
1002substitute `class' for `def' for the other case.
1003
1004If point is in a def statement already, this is the def we use.
1005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001006Else if the def found by `\\[beginning-of-python-def-or-class]'
1007contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008
1009Else we search forward for the closest following def, and use that.
1010
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001011If a def can be found by these rules, point is moved to the start of
1012the line immediately following the def block, and the position of the
1013start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001014
1015Else point is moved to the end of the buffer, and nil is returned.
1016
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017Note that doing this command repeatedly will take you closer to the
1018end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020If you want to mark the current def/class, see
1021`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001023 (let ((start (progn (py-goto-initial-line) (point)))
1024 (which (if class "class" "def"))
1025 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001026 ;; move point to start of appropriate def/class
1027 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1028 (setq state 'at-beginning)
1029 ;; else see if beginning-of-python-def-or-class hits container
1030 (if (and (beginning-of-python-def-or-class class)
1031 (progn (py-goto-beyond-block)
1032 (> (point) start)))
1033 (setq state 'at-end)
1034 ;; else search forward
1035 (goto-char start)
1036 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1037 (progn (setq state 'at-beginning)
1038 (beginning-of-line)))))
1039 (cond
1040 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1041 ((eq state 'at-end) t)
1042 ((eq state 'not-found) nil)
1043 (t (error "internal error in end-of-python-def-or-class")))))
1044
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001045
1046;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001047(defun py-mark-block (&optional extend just-move)
1048 "Mark following block of lines. With prefix arg, mark structure.
1049Easier to use than explain. It sets the region to an `interesting'
1050block of succeeding lines. If point is on a blank line, it goes down to
1051the next non-blank line. That will be the start of the region. The end
1052of the region depends on the kind of line at the start:
1053
1054 - If a comment, the region will include all succeeding comment lines up
1055 to (but not including) the next non-comment line (if any).
1056
1057 - Else if a prefix arg is given, and the line begins one of these
1058 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001059
1060 if elif else try except finally for while def class
1061
Barry Warsaw7ae77681994-12-12 20:38:05 +00001062 the region will be set to the body of the structure, including
1063 following blocks that `belong' to it, but excluding trailing blank
1064 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001065 and all (if any) of the following `except' and `finally' blocks
1066 that belong to the `try' structure will be in the region. Ditto
1067 for if/elif/else, for/else and while/else structures, and (a bit
1068 degenerate, since they're always one-block structures) def and
1069 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070
1071 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 block (see list above), and the block is not a `one-liner' (i.e.,
1073 the statement ends with a colon, not with code), the region will
1074 include all succeeding lines up to (but not including) the next
1075 code statement (if any) that's indented no more than the starting
1076 line, except that trailing blank and comment lines are excluded.
1077 E.g., if the starting line begins a multi-statement `def'
1078 structure, the region will be set to the full function definition,
1079 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001080
1081 - Else the region will include all succeeding lines up to (but not
1082 including) the next blank line, or code or indenting-comment line
1083 indented strictly less than the starting line. Trailing indenting
1084 comment lines are included in this case, but not trailing blank
1085 lines.
1086
1087A msg identifying the location of the mark is displayed in the echo
1088area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1089
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001090If called from a program, optional argument EXTEND plays the role of
1091the prefix arg, and if optional argument JUST-MOVE is not nil, just
1092moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001093 (interactive "P") ; raw prefix arg
1094 (py-goto-initial-line)
1095 ;; skip over blank lines
1096 (while (and
1097 (looking-at "[ \t]*$") ; while blank line
1098 (not (eobp))) ; & somewhere to go
1099 (forward-line 1))
1100 (if (eobp)
1101 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001102 (let ((initial-pos (point))
1103 (initial-indent (current-indentation))
1104 last-pos ; position of last stmt in region
1105 (followers
1106 '((if elif else) (elif elif else) (else)
1107 (try except finally) (except except) (finally)
1108 (for else) (while else)
1109 (def) (class) ) )
1110 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001111
1112 (cond
1113 ;; if comment line, suck up the following comment lines
1114 ((looking-at "[ \t]*#")
1115 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1116 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1117 (setq last-pos (point)))
1118
1119 ;; else if line is a block line and EXTEND given, suck up
1120 ;; the whole structure
1121 ((and extend
1122 (setq first-symbol (py-suck-up-first-keyword) )
1123 (assq first-symbol followers))
1124 (while (and
1125 (or (py-goto-beyond-block) t) ; side effect
1126 (forward-line -1) ; side effect
1127 (setq last-pos (point)) ; side effect
1128 (py-goto-statement-below)
1129 (= (current-indentation) initial-indent)
1130 (setq next-symbol (py-suck-up-first-keyword))
1131 (memq next-symbol (cdr (assq first-symbol followers))))
1132 (setq first-symbol next-symbol)))
1133
1134 ;; else if line *opens* a block, search for next stmt indented <=
1135 ((py-statement-opens-block-p)
1136 (while (and
1137 (setq last-pos (point)) ; always true -- side effect
1138 (py-goto-statement-below)
1139 (> (current-indentation) initial-indent))
1140 nil))
1141
1142 ;; else plain code line; stop at next blank line, or stmt or
1143 ;; indenting comment line indented <
1144 (t
1145 (while (and
1146 (setq last-pos (point)) ; always true -- side effect
1147 (or (py-goto-beyond-final-line) t)
1148 (not (looking-at "[ \t]*$")) ; stop at blank line
1149 (or
1150 (>= (current-indentation) initial-indent)
1151 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1152 nil)))
1153
1154 ;; skip to end of last stmt
1155 (goto-char last-pos)
1156 (py-goto-beyond-final-line)
1157
1158 ;; set mark & display
1159 (if just-move
1160 () ; just return
1161 (push-mark (point) 'no-msg)
1162 (forward-line -1)
1163 (message "Mark set after: %s" (py-suck-up-leading-text))
1164 (goto-char initial-pos))))
1165
1166(defun mark-python-def-or-class (&optional class)
1167 "Set region to body of def (or class, with prefix arg) enclosing point.
1168Pushes the current mark, then point, on the mark ring (all language
1169modes do this, but although it's handy it's never documented ...).
1170
1171In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001172hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1173`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174
1175And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001176Turned out that was more confusing than useful: the `goto start' and
1177`goto end' commands are usually used to search through a file, and
1178people expect them to act a lot like `search backward' and `search
1179forward' string-search commands. But because Python `def' and `class'
1180can nest to arbitrary levels, finding the smallest def containing
1181point cannot be done via a simple backward search: the def containing
1182point may not be the closest preceding def, or even the closest
1183preceding def that's indented less. The fancy algorithm required is
1184appropriate for the usual uses of this `mark' command, but not for the
1185`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001186
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001187So the def marked by this command may not be the one either of the
1188`goto' commands find: If point is on a blank or non-indenting comment
1189line, moves back to start of the closest preceding code statement or
1190indenting comment line. If this is a `def' statement, that's the def
1191we use. Else searches for the smallest enclosing `def' block and uses
1192that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001193
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001194When an enclosing def is found: The mark is left immediately beyond
1195the last line of the def block. Point is left at the start of the
1196def, except that: if the def is preceded by a number of comment lines
1197followed by (at most) one optional blank line, point is left at the
1198start of the comments; else if the def is preceded by a blank line,
1199point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001200
1201The intent is to mark the containing def/class and its associated
1202documentation, to make moving and duplicating functions and classes
1203pleasant."
1204 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001205 (let ((start (point))
1206 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001207 (push-mark start)
1208 (if (not (py-go-up-tree-to-keyword which))
1209 (progn (goto-char start)
1210 (error "Enclosing %s not found" which))
1211 ;; else enclosing def/class found
1212 (setq start (point))
1213 (py-goto-beyond-block)
1214 (push-mark (point))
1215 (goto-char start)
1216 (if (zerop (forward-line -1)) ; if there is a preceding line
1217 (progn
1218 (if (looking-at "[ \t]*$") ; it's blank
1219 (setq start (point)) ; so reset start point
1220 (goto-char start)) ; else try again
1221 (if (zerop (forward-line -1))
1222 (if (looking-at "[ \t]*#") ; a comment
1223 ;; look back for non-comment line
1224 ;; tricky: note that the regexp matches a blank
1225 ;; line, cuz \n is in the 2nd character class
1226 (and
1227 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1228 (forward-line 1))
1229 ;; no comment, so go back
1230 (goto-char start))))))))
1231
1232(defun py-comment-region (start end &optional uncomment-p)
1233 "Comment out region of code; with prefix arg, uncomment region.
1234The lines from the line containing the start of the current region up
1235to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001236commented out, by inserting the string `py-block-comment-prefix' at
1237the start of each line. With a prefix arg, removes
1238`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001239 (interactive "*r\nP") ; region; raw prefix arg
1240 (goto-char end) (beginning-of-line) (setq end (point))
1241 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001242 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001243 (save-excursion
1244 (save-restriction
1245 (narrow-to-region start end)
1246 (while (not (eobp))
1247 (if uncomment-p
1248 (and (string= py-block-comment-prefix
1249 (buffer-substring
1250 (point) (+ (point) prefix-len)))
1251 (delete-char prefix-len))
1252 (insert py-block-comment-prefix))
1253 (forward-line 1))))))
1254
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001255
1256;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257
1258;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001259;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1260;; out of the right places, along with the keys they're on & current
1261;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001262(defun py-dump-help-string (str)
1263 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001264 (let ((locals (buffer-local-variables))
1265 funckind funcname func funcdoc
1266 (start 0) mstart end
1267 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001268 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1269 (setq mstart (match-beginning 0) end (match-end 0)
1270 funckind (substring str (match-beginning 1) (match-end 1))
1271 funcname (substring str (match-beginning 2) (match-end 2))
1272 func (intern funcname))
1273 (princ (substitute-command-keys (substring str start mstart)))
1274 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001275 ((equal funckind "c") ; command
1276 (setq funcdoc (documentation func)
1277 keys (concat
1278 "Key(s): "
1279 (mapconcat 'key-description
1280 (where-is-internal func py-mode-map)
1281 ", "))))
1282 ((equal funckind "v") ; variable
1283 (setq funcdoc (substitute-command-keys
1284 (get func 'variable-documentation))
1285 keys (if (assq func locals)
1286 (concat
1287 "Local/Global values: "
1288 (prin1-to-string (symbol-value func))
1289 " / "
1290 (prin1-to-string (default-value func)))
1291 (concat
1292 "Value: "
1293 (prin1-to-string (symbol-value func))))))
1294 (t ; unexpected
1295 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296 (princ (format "\n-> %s:\t%s\t%s\n\n"
1297 (if (equal funckind "c") "Command" "Variable")
1298 funcname keys))
1299 (princ funcdoc)
1300 (terpri)
1301 (setq start end))
1302 (princ (substitute-command-keys (substring str start))))
1303 (print-help-return-message)))
1304
1305(defun py-describe-mode ()
1306 "Dump long form of Python-mode docs."
1307 (interactive)
1308 (py-dump-help-string "Major mode for editing Python files.
1309Knows about Python indentation, tokens, comments and continuation lines.
1310Paragraphs are separated by blank lines only.
1311
1312Major sections below begin with the string `@'; specific function and
1313variable docs begin with `->'.
1314
1315@EXECUTING PYTHON CODE
1316
1317\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1318\\[py-execute-region]\tsends the current region
1319\\[py-shell]\tstarts a Python interpreter window; this will be used by
1320\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1321%c:py-execute-buffer
1322%c:py-execute-region
1323%c:py-shell
1324
1325@VARIABLES
1326
1327py-indent-offset\tindentation increment
1328py-block-comment-prefix\tcomment string used by py-comment-region
1329
1330py-python-command\tshell command to invoke Python interpreter
1331py-scroll-process-buffer\talways scroll Python process buffer
1332py-temp-directory\tdirectory used for temp files (if needed)
1333
1334py-beep-if-tab-change\tring the bell if tab-width is changed
1335%v:py-indent-offset
1336%v:py-block-comment-prefix
1337%v:py-python-command
1338%v:py-scroll-process-buffer
1339%v:py-temp-directory
1340%v:py-beep-if-tab-change
1341
1342@KINDS OF LINES
1343
1344Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001345preceding line ends with a backslash that's not part of a comment, or
1346the paren/bracket/brace nesting level at the start of the line is
1347non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001348
1349An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001350possibly blanks or tabs), a `comment line' (leftmost non-blank
1351character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
1353Comment Lines
1354
1355Although all comment lines are treated alike by Python, Python mode
1356recognizes two kinds that act differently with respect to indentation.
1357
1358An `indenting comment line' is a comment line with a blank, tab or
1359nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361indenting comment line will be indented like the comment line. All
1362other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363following the initial `#') are `non-indenting comment lines', and
1364their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365
1366Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001367whenever possible. Non-indenting comment lines are useful in cases
1368like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
1370\ta = b # a very wordy single-line comment that ends up being
1371\t #... continued onto another line
1372
1373\tif a == b:
1374##\t\tprint 'panic!' # old code we've `commented out'
1375\t\treturn a
1376
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001377Since the `#...' and `##' comment lines have a non-whitespace
1378character following the initial `#', Python mode ignores them when
1379computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380
1381Continuation Lines and Statements
1382
1383The Python-mode commands generally work on statements instead of on
1384individual lines, where a `statement' is a comment or blank line, or a
1385code line and all of its following continuation lines (if any)
1386considered as a single logical unit. The commands in this mode
1387generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001388statement containing point, even if point happens to be in the middle
1389of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001390
1391
1392@INDENTATION
1393
1394Primarily for entering new code:
1395\t\\[indent-for-tab-command]\t indent line appropriately
1396\t\\[py-newline-and-indent]\t insert newline, then indent
1397\t\\[py-delete-char]\t reduce indentation, or delete single character
1398
1399Primarily for reindenting existing code:
1400\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1401\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1402
1403\t\\[py-indent-region]\t reindent region to match its context
1404\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1405\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1406
1407Unlike most programming languages, Python uses indentation, and only
1408indentation, to specify block structure. Hence the indentation supplied
1409automatically by Python-mode is just an educated guess: only you know
1410the block structure you intend, so only you can supply correct
1411indentation.
1412
1413The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1414the indentation of preceding statements. E.g., assuming
1415py-indent-offset is 4, after you enter
1416\tif a > 0: \\[py-newline-and-indent]
1417the cursor will be moved to the position of the `_' (_ is not a
1418character in the file, it's just used here to indicate the location of
1419the cursor):
1420\tif a > 0:
1421\t _
1422If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1423to
1424\tif a > 0:
1425\t c = d
1426\t _
1427Python-mode cannot know whether that's what you intended, or whether
1428\tif a > 0:
1429\t c = d
1430\t_
1431was your intent. In general, Python-mode either reproduces the
1432indentation of the (closest code or indenting-comment) preceding
1433statement, or adds an extra py-indent-offset blanks if the preceding
1434statement has `:' as its last significant (non-whitespace and non-
1435comment) character. If the suggested indentation is too much, use
1436\\[py-delete-char] to reduce it.
1437
1438Continuation lines are given extra indentation. If you don't like the
1439suggested indentation, change it to something you do like, and Python-
1440mode will strive to indent later lines of the statement in the same way.
1441
1442If a line is a continuation line by virtue of being in an unclosed
1443paren/bracket/brace structure (`list', for short), the suggested
1444indentation depends on whether the current line contains the first item
1445in the list. If it does, it's indented py-indent-offset columns beyond
1446the indentation of the line containing the open bracket. If you don't
1447like that, change it by hand. The remaining items in the list will mimic
1448whatever indentation you give to the first item.
1449
1450If a line is a continuation line because the line preceding it ends with
1451a backslash, the third and following lines of the statement inherit their
1452indentation from the line preceding them. The indentation of the second
1453line in the statement depends on the form of the first (base) line: if
1454the base line is an assignment statement with anything more interesting
1455than the backslash following the leftmost assigning `=', the second line
1456is indented two columns beyond that `='. Else it's indented to two
1457columns beyond the leftmost solid chunk of non-whitespace characters on
1458the base line.
1459
1460Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1461repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1462structure you intend.
1463%c:indent-for-tab-command
1464%c:py-newline-and-indent
1465%c:py-delete-char
1466
1467
1468The next function may be handy when editing code you didn't write:
1469%c:py-guess-indent-offset
1470
1471
1472The remaining `indent' functions apply to a region of Python code. They
1473assume the block structure (equals indentation, in Python) of the region
1474is correct, and alter the indentation in various ways while preserving
1475the block structure:
1476%c:py-indent-region
1477%c:py-shift-region-left
1478%c:py-shift-region-right
1479
1480@MARKING & MANIPULATING REGIONS OF CODE
1481
1482\\[py-mark-block]\t mark block of lines
1483\\[mark-python-def-or-class]\t mark smallest enclosing def
1484\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1485\\[py-comment-region]\t comment out region of code
1486\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1487%c:py-mark-block
1488%c:mark-python-def-or-class
1489%c:py-comment-region
1490
1491@MOVING POINT
1492
1493\\[py-previous-statement]\t move to statement preceding point
1494\\[py-next-statement]\t move to statement following point
1495\\[py-goto-block-up]\t move up to start of current block
1496\\[beginning-of-python-def-or-class]\t move to start of def
1497\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1498\\[end-of-python-def-or-class]\t move to end of def
1499\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1500
1501The first two move to one statement beyond the statement that contains
1502point. A numeric prefix argument tells them to move that many
1503statements instead. Blank lines, comment lines, and continuation lines
1504do not count as `statements' for these commands. So, e.g., you can go
1505to the first code statement in a file by entering
1506\t\\[beginning-of-buffer]\t to move to the top of the file
1507\t\\[py-next-statement]\t to skip over initial comments and blank lines
1508Or do `\\[py-previous-statement]' with a huge prefix argument.
1509%c:py-previous-statement
1510%c:py-next-statement
1511%c:py-goto-block-up
1512%c:beginning-of-python-def-or-class
1513%c:end-of-python-def-or-class
1514
1515@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1516
1517`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1518
1519`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1520overall class and def structure of a module.
1521
1522`\\[back-to-indentation]' moves point to a line's first non-blank character.
1523
1524`\\[indent-relative]' is handy for creating odd indentation.
1525
1526@OTHER EMACS HINTS
1527
1528If you don't like the default value of a variable, change its value to
1529whatever you do like by putting a `setq' line in your .emacs file.
1530E.g., to set the indentation increment to 4, put this line in your
1531.emacs:
1532\t(setq py-indent-offset 4)
1533To see the value of a variable, do `\\[describe-variable]' and enter the variable
1534name at the prompt.
1535
1536When entering a key sequence like `C-c C-n', it is not necessary to
1537release the CONTROL key after doing the `C-c' part -- it suffices to
1538press the CONTROL key, press and release `c' (while still holding down
1539CONTROL), press and release `n' (while still holding down CONTROL), &
1540then release CONTROL.
1541
1542Entering Python mode calls with no arguments the value of the variable
1543`python-mode-hook', if that value exists and is not nil; for backward
1544compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1545the Elisp manual for details.
1546
1547Obscure: When python-mode is first loaded, it looks for all bindings
1548to newline-and-indent in the global keymap, and shadows them with
1549local bindings to py-newline-and-indent."))
1550
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551
1552;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001553(defvar py-parse-state-re
1554 (concat
1555 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1556 "\\|"
1557 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001558
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559;; returns the parse state at point (see parse-partial-sexp docs)
1560(defun py-parse-state ()
1561 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001562 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001563 ;; back up to the first preceding line (if any; else start of
1564 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001565 ;; whitespace and non-comment character. These are good places
1566 ;; to start parsing to see whether where we started is at a
1567 ;; non-zero nesting level. It may be slow for people who write
1568 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569 (re-search-backward py-parse-state-re nil 'move)
1570 (beginning-of-line)
1571 (parse-partial-sexp (point) here))))
1572
1573;; if point is at a non-zero nesting level, returns the number of the
1574;; character that opens the smallest enclosing unclosed list; else
1575;; returns nil.
1576(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001577 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578 (if (zerop (car status))
1579 nil ; not in a nest
1580 (car (cdr status))))) ; char# of open bracket
1581
1582;; t iff preceding line ends with backslash that's not in a comment
1583(defun py-backslash-continuation-line-p ()
1584 (save-excursion
1585 (beginning-of-line)
1586 (and
1587 ;; use a cheap test first to avoid the regexp if possible
1588 ;; use 'eq' because char-after may return nil
1589 (eq (char-after (- (point) 2)) ?\\ )
1590 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001591 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001592 (looking-at py-continued-re))))
1593
1594;; t iff current line is a continuation line
1595(defun py-continuation-line-p ()
1596 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001597 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001598 (or (py-backslash-continuation-line-p)
1599 (py-nesting-level))))
1600
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001601;; go to initial line of current statement; usually this is the line
1602;; we're on, but if we're on the 2nd or following lines of a
1603;; continuation block, we need to go up to the first line of the
1604;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001605;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001606;; Tricky: We want to avoid quadratic-time behavior for long continued
1607;; blocks, whether of the backslash or open-bracket varieties, or a
1608;; mix of the two. The following manages to do that in the usual
1609;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001610(defun py-goto-initial-line ()
1611 (let ( open-bracket-pos )
1612 (while (py-continuation-line-p)
1613 (beginning-of-line)
1614 (if (py-backslash-continuation-line-p)
1615 (while (py-backslash-continuation-line-p)
1616 (forward-line -1))
1617 ;; else zip out of nested brackets/braces/parens
1618 (while (setq open-bracket-pos (py-nesting-level))
1619 (goto-char open-bracket-pos)))))
1620 (beginning-of-line))
1621
1622;; go to point right beyond final line of current statement; usually
1623;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001624;; statement we need to skip over the continuation lines. Tricky:
1625;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001626(defun py-goto-beyond-final-line ()
1627 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001629 (while (and (py-continuation-line-p)
1630 (not (eobp)))
1631 ;; skip over the backslash flavor
1632 (while (and (py-backslash-continuation-line-p)
1633 (not (eobp)))
1634 (forward-line 1))
1635 ;; if in nest, zip to the end of the nest
1636 (setq state (py-parse-state))
1637 (if (and (not (zerop (car state)))
1638 (not (eobp)))
1639 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001640 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641 ;; the 3rd argument should be plain 0
1642 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1643 nil state)
1644 (forward-line 1))))))
1645
1646;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001647;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001648(defun py-statement-opens-block-p ()
1649 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001650 (let ((start (point))
1651 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1652 (searching t)
1653 (answer nil)
1654 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001655 (goto-char start)
1656 (while searching
1657 ;; look for a colon with nothing after it except whitespace, and
1658 ;; maybe a comment
1659 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1660 finish t)
1661 (if (eq (point) finish) ; note: no `else' clause; just
1662 ; keep searching if we're not at
1663 ; the end yet
1664 ;; sure looks like it opens a block -- but it might
1665 ;; be in a comment
1666 (progn
1667 (setq searching nil) ; search is done either way
1668 (setq state (parse-partial-sexp start
1669 (match-beginning 0)))
1670 (setq answer (not (nth 4 state)))))
1671 ;; search failed: couldn't find another interesting colon
1672 (setq searching nil)))
1673 answer)))
1674
1675;; go to point right beyond final line of block begun by the current
1676;; line. This is the same as where py-goto-beyond-final-line goes
1677;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001678;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679(defun py-goto-beyond-block ()
1680 (if (py-statement-opens-block-p)
1681 (py-mark-block nil 'just-move)
1682 (py-goto-beyond-final-line)))
1683
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001684;; go to start of first statement (not blank or comment or
1685;; continuation line) at or preceding point. returns t if there is
1686;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001687(defun py-goto-statement-at-or-above ()
1688 (py-goto-initial-line)
1689 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001690 ;; skip back over blank & comment lines
1691 ;; note: will skip a blank or comment line that happens to be
1692 ;; a continuation line too
1693 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1694 (progn (py-goto-initial-line) t)
1695 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001696 t))
1697
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001698;; go to start of first statement (not blank or comment or
1699;; continuation line) following the statement containing point returns
1700;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001701(defun py-goto-statement-below ()
1702 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001703 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001704 (py-goto-beyond-final-line)
1705 (while (and
1706 (looking-at py-blank-or-comment-re)
1707 (not (eobp)))
1708 (forward-line 1))
1709 (if (eobp)
1710 (progn (goto-char start) nil)
1711 t)))
1712
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001713;; go to start of statement, at or preceding point, starting with
1714;; keyword KEY. Skips blank lines and non-indenting comments upward
1715;; first. If that statement starts with KEY, done, else go back to
1716;; first enclosing block starting with KEY. If successful, leaves
1717;; point at the start of the KEY line & returns t. Else leaves point
1718;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001719(defun py-go-up-tree-to-keyword (key)
1720 ;; skip blanks and non-indenting #
1721 (py-goto-initial-line)
1722 (while (and
1723 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1724 (zerop (forward-line -1))) ; go back
1725 nil)
1726 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001727 (let* ((re (concat "[ \t]*" key "\\b"))
1728 (case-fold-search nil) ; let* so looking-at sees this
1729 (found (looking-at re))
1730 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001731 (while (not (or found dead))
1732 (condition-case nil ; in case no enclosing block
1733 (py-goto-block-up 'no-mark)
1734 (error (setq dead t)))
1735 (or dead (setq found (looking-at re))))
1736 (beginning-of-line)
1737 found))
1738
1739;; return string in buffer from start of indentation to end of line;
1740;; prefix "..." if leading whitespace was skipped
1741(defun py-suck-up-leading-text ()
1742 (save-excursion
1743 (back-to-indentation)
1744 (concat
1745 (if (bolp) "" "...")
1746 (buffer-substring (point) (progn (end-of-line) (point))))))
1747
1748;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1749;; as a Lisp symbol; return nil if none
1750(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1753 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1754 nil)))
1755
1756(defun py-make-temp-name ()
1757 (make-temp-name
1758 (concat (file-name-as-directory py-temp-directory) "python")))
1759
1760(defun py-delete-file-silently (fname)
1761 (condition-case nil
1762 (delete-file fname)
1763 (error nil)))
1764
1765(defun py-kill-emacs-hook ()
1766 ;; delete our temp files
1767 (while py-file-queue
1768 (py-delete-file-silently (car py-file-queue))
1769 (setq py-file-queue (cdr py-file-queue)))
1770 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1771 ;; run the hook we inherited, if any
1772 (and py-inherited-kill-emacs-hook
1773 (funcall py-inherited-kill-emacs-hook))))
1774
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001775;; make PROCESS's buffer visible, append STRING to it, and force
1776;; display; also make shell-mode believe the user typed this string,
1777;; so that kill-output-from-shell and show-output-from-shell work
1778;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780 (let ((cbuf (current-buffer))
1781 (pbuf (process-buffer process))
1782 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001783 (set-buffer pbuf)
1784 (goto-char (point-max))
1785 (move-marker (process-mark process) (point))
1786 (if (not py-this-is-emacs-19-p)
1787 (move-marker last-input-start (point))) ; muck w/ shell-mode
1788 (funcall (process-filter process) process string)
1789 (if (not py-this-is-emacs-19-p)
1790 (move-marker last-input-end (point))) ; muck w/ shell-mode
1791 (set-buffer cbuf))
1792 (sit-for 0))
1793
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001794(defun py-keep-region-active ()
1795 ;; do whatever is necessary to keep the region active in XEmacs.
1796 ;; Ignore byte-compiler warnings you might see. Also note that
1797 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1798 ;; require us to take explicit action.
1799 (and (boundp 'zmacs-region-stays)
1800 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001801
1802
Barry Warsaw850437a1995-03-08 21:50:28 +00001803(defconst py-version "$Revision$"
1804 "`python-mode' version number.")
1805(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1806 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807
Barry Warsaw850437a1995-03-08 21:50:28 +00001808(defun py-version ()
1809 "Echo the current version of `python-mode' in the minibuffer."
1810 (interactive)
1811 (message "Using `python-mode' version %s" py-version)
1812 (py-keep-region-active))
1813
1814;; only works under Emacs 19
1815;(eval-when-compile
1816; (require 'reporter))
1817
1818(defun py-submit-bug-report (enhancement-p)
1819 "Submit via mail a bug report on `python-mode'.
1820With \\[universal-argument] just submit an enhancement request."
1821 (interactive
1822 (list (not (y-or-n-p
1823 "Is this a bug report? (hit `n' to send other comments) "))))
1824 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1825 (require 'reporter)
1826 (reporter-submit-bug-report
1827 py-help-address ;address
1828 "python-mode" ;pkgname
1829 ;; varlist
1830 (if enhancement-p nil
1831 '(py-python-command
1832 py-indent-offset
1833 py-block-comment-prefix
1834 py-scroll-process-buffer
1835 py-temp-directory
1836 py-beep-if-tab-change))
1837 nil ;pre-hooks
1838 nil ;post-hooks
1839 "Dear Barry,") ;salutation
1840 (if enhancement-p nil
1841 (set-mark (point))
1842 (insert
1843"Please replace this text with a sufficiently large code sample\n\
1844and an exact recipe so that I can reproduce your problem. Failure\n\
1845to do so may mean a greater delay in fixing your bug.\n\n")
1846 (exchange-point-and-mark)
1847 (py-keep-region-active))))
1848
1849
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001850;; arrange to kill temp files when Emacs exists
1851(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1852 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1853 ;; have to trust that other people are as respectful of our hook
1854 ;; fiddling as we are of theirs
1855 (if (boundp 'py-inherited-kill-emacs-hook)
1856 ;; we were loaded before -- trust others not to have screwed us
1857 ;; in the meantime (no choice, really)
1858 nil
1859 ;; else arrange for our hook to run theirs
1860 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1861 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1862
1863
1864
1865(provide 'python-mode)
1866;;; python-mode.el ends here