blob: 84be62ec9478b763b756b6b93869c2a96dcf8581 [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
168
169
170;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
171;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
172
173;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
174;; seems to be the standard way of checking this.
175;; BAW - This is *not* the right solution. When at all possible,
176;; instead of testing for the version of Emacs, use feature tests.
177
178(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
179(setq py-this-is-emacs-19-p
180 (and
181 (not py-this-is-lucid-emacs-p)
182 (string-match "^19\\." emacs-version)))
183
Barry Warsaw7ae77681994-12-12 20:38:05 +0000184;; have to bind py-file-queue before installing the kill-emacs hook
185(defvar py-file-queue nil
186 "Queue of Python temp files awaiting execution.
187Currently-active file is at the head of the list.")
188
189;; define a mode-specific abbrev table for those who use such things
190(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000191 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000192(define-abbrev-table 'python-mode-abbrev-table nil)
193
Barry Warsaw7ae77681994-12-12 20:38:05 +0000194(defvar python-mode-hook nil
195 "*Hook called by `python-mode'.")
196
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000197;; in previous version of python-mode.el, the hook was incorrectly
198;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000199(and (fboundp 'make-obsolete-variable)
200 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
201
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000202(defvar py-mode-map ()
203 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000204
Barry Warsaw7ae77681994-12-12 20:38:05 +0000205(if py-mode-map
206 ()
207 (setq py-mode-map (make-sparse-keymap))
208
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000209 ;; shadow global bindings for newline-and-indent w/ the py- version.
210 ;; BAW - this is extremely bad form, but I'm not going to change it
211 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000212 (mapcar (function (lambda (key)
213 (define-key
214 py-mode-map key 'py-newline-and-indent)))
215 (where-is-internal 'newline-and-indent))
216
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000217 ;; BAW - you could do it this way, but its not considered proper
218 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000219 (mapcar (function
220 (lambda (x)
221 (define-key py-mode-map (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000222 '(("\C-c\C-c" . py-execute-buffer)
223 ("\C-c|" . py-execute-region)
224 ("\C-c!" . py-shell)
225 ("\177" . py-delete-char)
226 ("\n" . py-newline-and-indent)
227 ("\C-c:" . py-guess-indent-offset)
228 ("\C-c\t" . py-indent-region)
229 ("\C-c<" . py-shift-region-left)
230 ("\C-c>" . py-shift-region-right)
231 ("\C-c\C-n" . py-next-statement)
232 ("\C-c\C-p" . py-previous-statement)
233 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000234 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000235 ("\C-c#" . py-comment-region)
236 ("\C-c?" . py-describe-mode)
237 ("\C-c\C-hm" . py-describe-mode)
238 ("\e\C-a" . beginning-of-python-def-or-class)
239 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000240 ( "\e\C-h" . mark-python-def-or-class)))
241 ;; should do all keybindings this way
242 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
243 (define-key py-mode-map "\C-c\C-v" 'py-version)
244 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000245
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000246(defvar py-mode-syntax-table nil
247 "Syntax table used in `python-mode' buffers.")
248
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249(if py-mode-syntax-table
250 ()
251 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000252 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253 (mapcar (function
254 (lambda (x) (modify-syntax-entry
255 (car x) (cdr x) py-mode-syntax-table)))
256 '(( ?\( . "()" ) ( ?\) . ")(" )
257 ( ?\[ . "(]" ) ( ?\] . ")[" )
258 ( ?\{ . "(}" ) ( ?\} . "){" )
259 ;; fix operator symbols misassigned in the std table
260 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
261 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
262 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
263 ( ?\> . "." ) ( ?\| . "." )
264 ( ?\_ . "w" ) ; underscore is legit in names
265 ( ?\' . "\"") ; single quote is string quote
266 ( ?\" . "\"" ) ; double quote is string quote too
267 ( ?\` . "$") ; backquote is open and close paren
268 ( ?\# . "<") ; hash starts comment
269 ( ?\n . ">")))) ; newline ends comment
270
271(defconst py-stringlit-re
272 (concat
273 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
274 "\\|" ; or
275 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000277
278;; this is tricky because a trailing backslash does not mean
279;; continuation if it's in a comment
280(defconst py-continued-re
281 (concat
282 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
283 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000284 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285
286(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000287 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000288
Barry Warsaw7ae77681994-12-12 20:38:05 +0000289
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000290
291;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000292(defun python-mode ()
293 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000294To submit a problem report, enter `\\[py-submit-bug-report]' from a
295`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
296documentation. To see what version of `python-mode' you are running,
297enter `\\[py-version]'.
298
299This mode knows about Python indentation, tokens, comments and
300continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000301
302COMMANDS
303\\{py-mode-map}
304VARIABLES
305
306py-indent-offset\tindentation increment
307py-block-comment-prefix\tcomment string used by py-comment-region
308py-python-command\tshell command to invoke Python interpreter
309py-scroll-process-buffer\talways scroll Python process buffer
310py-temp-directory\tdirectory used for temp files (if needed)
311py-beep-if-tab-change\tring the bell if tab-width is changed"
312 (interactive)
313 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000314 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000315 (setq major-mode 'python-mode
316 mode-name "Python"
317 local-abbrev-table python-mode-abbrev-table)
318 (use-local-map py-mode-map)
319 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000320 (mapcar (function (lambda (x)
321 (make-local-variable (car x))
322 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000323 '((paragraph-separate . "^[ \t]*$")
324 (paragraph-start . "^[ \t]*$")
325 (require-final-newline . t)
326 (comment-start . "# ")
327 (comment-start-skip . "# *")
328 (comment-column . 40)
329 (indent-region-function . py-indent-region)
330 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000331 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000332 ;;
333 ;; not sure where the magic comment has to be; to save time
334 ;; searching for a rarity, we give up if it's not found prior to the
335 ;; first executable statement.
336 ;;
337 ;; BAW - on first glance, this seems like complete hackery. Why was
338 ;; this necessary, and is it still necessary?
339 (let ((case-fold-search nil)
340 (start (point))
341 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000342 (if (re-search-forward
343 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
344 (prog2 (py-next-statement 1) (point) (goto-char 1))
345 t)
346 (progn
347 (setq new-tab-width
348 (string-to-int
349 (buffer-substring (match-beginning 1) (match-end 1))))
350 (if (= tab-width new-tab-width)
351 nil
352 (setq tab-width new-tab-width)
353 (message "Caution: tab-width changed to %d" new-tab-width)
354 (if py-beep-if-tab-change (beep)))))
355 (goto-char start))
356
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000357 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000358 (if python-mode-hook
359 (run-hooks 'python-mode-hook)
360 (run-hooks 'py-mode-hook)))
361
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000362
Barry Warsaw7ae77681994-12-12 20:38:05 +0000363;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000364(defun py-shell ()
365 "Start an interactive Python interpreter in another window.
366This is like Shell mode, except that Python is running in the window
367instead of a shell. See the `Interactive Shell' and `Shell Mode'
368sections of the Emacs manual for details, especially for the key
369bindings active in the `*Python*' buffer.
370
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000371See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000372behavior in the process window.
373
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000374Warning: Don't use an interactive Python if you change sys.ps1 or
375sys.ps2 from their default values, or if you're running code that
376prints `>>> ' or `... ' at the start of a line. `python-mode' can't
377distinguish your output from Python's output, and assumes that `>>> '
378at the start of a line is a prompt from Python. Similarly, the Emacs
379Shell mode code assumes that both `>>> ' and `... ' at the start of a
380line are Python prompts. Bad things can happen if you fool either
381mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000382
383Warning: If you do any editing *in* the process buffer *while* the
384buffer is accepting output from Python, do NOT attempt to `undo' the
385changes. Some of the output (nowhere near the parts you changed!) may
386be lost if you do. This appears to be an Emacs bug, an unfortunate
387interaction between undo and process filters; the same problem exists in
388non-Python process buffers using the default (Emacs-supplied) process
389filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000390 ;; BAW - should undo be disabled in the python process buffer, if
391 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000392 (interactive)
393 (if py-this-is-emacs-19-p
394 (progn
395 (require 'comint)
396 (switch-to-buffer-other-window
397 (make-comint "Python" py-python-command)))
398 (progn
399 (require 'shell)
400 (switch-to-buffer-other-window
401 (make-shell "Python" py-python-command))))
402 (make-local-variable 'shell-prompt-pattern)
403 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
404 (set-process-filter (get-buffer-process (current-buffer))
405 'py-process-filter)
406 (set-syntax-table py-mode-syntax-table))
407
408(defun py-execute-region (start end)
409 "Send the region between START and END to a Python interpreter.
410If there is a *Python* process it is used.
411
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000412Hint: If you want to execute part of a Python file several times
413\(e.g., perhaps you're developing a function and want to flesh it out
414a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
415the region of interest, and send the code to a *Python* process via
416`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000417
418Following are subtleties to note when using a *Python* process:
419
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000420If a *Python* process is used, the region is copied into a temporary
421file (in directory `py-temp-directory'), and an `execfile' command is
422sent to Python naming that file. If you send regions faster than
423Python can execute them, `python-mode' will save them into distinct
424temp files, and execute the next one in the queue the next time it
425sees a `>>> ' prompt from Python. Each time this happens, the process
426buffer is popped into a window (if it's not already in some window) so
427you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000428
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000429 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000430
431is inserted at the end.
432
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000433Caution: No more than 26 regions can be pending at any given time.
434This limit is (indirectly) inherited from libc's mktemp(3).
435`python-mode' does not try to protect you from exceeding the limit.
436It's extremely unlikely that you'll get anywhere close to the limit in
437practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000438
439See the `\\[py-shell]' docs for additional warnings."
440 (interactive "r")
441 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000442 (let ((pyproc (get-process "Python"))
443 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000444 (if (null pyproc)
445 (shell-command-on-region start end py-python-command)
446 ;; else feed it thru a temp file
447 (setq fname (py-make-temp-name))
448 (write-region start end fname nil 'no-msg)
449 (setq py-file-queue (append py-file-queue (list fname)))
450 (if (cdr py-file-queue)
451 (message "File %s queued for execution" fname)
452 ;; else
453 (py-execute-file pyproc fname)))))
454
455(defun py-execute-file (pyproc fname)
456 (py-append-to-process-buffer
457 pyproc
458 (format "## working on region in file %s ...\n" fname))
459 (process-send-string pyproc (format "execfile('%s')\n" fname)))
460
461(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000462 (let ((curbuf (current-buffer))
463 (pbuf (process-buffer pyproc))
464 (pmark (process-mark pyproc))
465 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000466
467 ;; make sure we switch to a different buffer at least once. if we
468 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000469 ;; window, and point is before the end, and lots of output is
470 ;; coming at a fast pace, then (a) simple cursor-movement commands
471 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
472 ;; to have a visible effect (the window just doesn't get updated,
473 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
474 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000475 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000476 ;; #b makes no sense to me at all. #a almost makes sense: unless
477 ;; we actually change buffers, set_buffer_internal in buffer.c
478 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
479 ;; seems to make the Emacs command loop reluctant to update the
480 ;; display. Perhaps the default process filter in process.c's
481 ;; read_process_output has update_mode_lines++ for a similar
482 ;; reason? beats me ...
483
484 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000485 (if (eq curbuf pbuf) ; mysterious ugly hack
486 (set-buffer (get-buffer-create "*scratch*")))
487
488 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000489 (let* ((start (point))
490 (goback (< start pmark))
491 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000492 (goto-char pmark)
493 (insert string)
494 (move-marker pmark (point))
495 (setq file-finished
496 (and py-file-queue
497 (equal ">>> "
498 (buffer-substring
499 (prog2 (beginning-of-line) (point)
500 (goto-char pmark))
501 (point)))))
502 (if goback (goto-char start)
503 ;; else
504 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000505 (let* ((pop-up-windows t)
506 (pwin (display-buffer pbuf)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000507 (set-window-point pwin (point))))))
508 (set-buffer curbuf)
509 (if file-finished
510 (progn
511 (py-delete-file-silently (car py-file-queue))
512 (setq py-file-queue (cdr py-file-queue))
513 (if py-file-queue
514 (py-execute-file pyproc (car py-file-queue)))))))
515
516(defun py-execute-buffer ()
517 "Send the contents of the buffer to a Python interpreter.
518If there is a *Python* process buffer it is used. If a clipping
519restriction is in effect, only the accessible portion of the buffer is
520sent. A trailing newline will be supplied if needed.
521
522See the `\\[py-execute-region]' docs for an account of some subtleties."
523 (interactive)
524 (py-execute-region (point-min) (point-max)))
525
526
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000527
528;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000529(defun py-delete-char ()
530 "Reduce indentation or delete character.
531If point is at the leftmost column, deletes the preceding newline.
532
533Else if point is at the leftmost non-blank character of a line that is
534neither a continuation line nor a non-indenting comment line, or if
535point is at the end of a blank line, reduces the indentation to match
536that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000537opened the block is displayed in the echo area to help you keep track
538of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539
540Else the preceding character is deleted, converting a tab to spaces if
541needed so that only a single column position is deleted."
542 (interactive "*")
543 (if (or (/= (current-indentation) (current-column))
544 (bolp)
545 (py-continuation-line-p)
546 (looking-at "#[^ \t\n]")) ; non-indenting #
547 (backward-delete-char-untabify 1)
548 ;; else indent the same as the colon line that opened the block
549
550 ;; force non-blank so py-goto-block-up doesn't ignore it
551 (insert-char ?* 1)
552 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000553 (let ((base-indent 0) ; indentation of base line
554 (base-text "") ; and text of base line
555 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (condition-case nil ; in case no enclosing block
557 (save-excursion
558 (py-goto-block-up 'no-mark)
559 (setq base-indent (current-indentation)
560 base-text (py-suck-up-leading-text)
561 base-found-p t))
562 (error nil))
563 (delete-char 1) ; toss the dummy character
564 (delete-horizontal-space)
565 (indent-to base-indent)
566 (if base-found-p
567 (message "Closes block: %s" base-text)))))
568
569(defun py-indent-line ()
570 "Fix the indentation of the current line according to Python rules."
571 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000572 (let* ((ci (current-indentation))
573 (move-to-indentation-p (<= (current-column) ci))
574 (need (py-compute-indentation)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000575 (if (/= ci need)
576 (save-excursion
577 (beginning-of-line)
578 (delete-horizontal-space)
579 (indent-to need)))
580 (if move-to-indentation-p (back-to-indentation))))
581
582(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000583 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000584This is just `strives to' because correct indentation can't be computed
585from scratch for Python code. In general, deletes the whitespace before
586point, inserts a newline, and takes an educated guess as to how you want
587the new line indented."
588 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000589 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000590 (if (< ci (current-column)) ; if point beyond indentation
591 (newline-and-indent)
592 ;; else try to act like newline-and-indent "normally" acts
593 (beginning-of-line)
594 (insert-char ?\n 1)
595 (move-to-column ci))))
596
597(defun py-compute-indentation ()
598 (save-excursion
599 (beginning-of-line)
600 (cond
601 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000602 ((py-continuation-line-p)
603 (let ((startpos (point))
604 (open-bracket-pos (py-nesting-level))
605 endpos searching found)
606 (if open-bracket-pos
607 (progn
608 ;; align with first item in list; else a normal
609 ;; indent beyond the line with the open bracket
610 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
611 ;; is the first list item on the same line?
612 (skip-chars-forward " \t")
613 (if (null (memq (following-char) '(?\n ?# ?\\)))
614 ; yes, so line up with it
615 (current-column)
616 ;; first list item on another line, or doesn't exist yet
617 (forward-line 1)
618 (while (and (< (point) startpos)
619 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
620 (forward-line 1))
621 (if (< (point) startpos)
622 ;; again mimic the first list item
623 (current-indentation)
624 ;; else they're about to enter the first item
625 (goto-char open-bracket-pos)
626 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000627
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000628 ;; else on backslash continuation line
629 (forward-line -1)
630 (if (py-continuation-line-p) ; on at least 3rd line in block
631 (current-indentation) ; so just continue the pattern
632 ;; else started on 2nd line in block, so indent more.
633 ;; if base line is an assignment with a start on a RHS,
634 ;; indent to 2 beyond the leftmost "="; else skip first
635 ;; chunk of non-whitespace characters on base line, + 1 more
636 ;; column
637 (end-of-line)
638 (setq endpos (point) searching t)
639 (back-to-indentation)
640 (setq startpos (point))
641 ;; look at all "=" from left to right, stopping at first
642 ;; one not nested in a list or string
643 (while searching
644 (skip-chars-forward "^=" endpos)
645 (if (= (point) endpos)
646 (setq searching nil)
647 (forward-char 1)
648 (setq state (parse-partial-sexp startpos (point)))
649 (if (and (zerop (car state)) ; not in a bracket
650 (null (nth 3 state))) ; & not in a string
651 (progn
652 (setq searching nil) ; done searching in any case
653 (setq found
654 (not (or
655 (eq (following-char) ?=)
656 (memq (char-after (- (point) 2))
657 '(?< ?> ?!)))))))))
658 (if (or (not found) ; not an assignment
659 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
660 (progn
661 (goto-char startpos)
662 (skip-chars-forward "^ \t\n")))
663 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000664
665 ;; not on a continuation line
666
667 ;; if at start of restriction, or on a non-indenting comment line,
668 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000669 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
670 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000671
672 ;; else indentation based on that of the statement that precedes
673 ;; us; use the first line of that statement to establish the base,
674 ;; in case the user forced a non-std indentation for the
675 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000676 (t
677 ;; skip back over blank & non-indenting comment lines
678 ;; note: will skip a blank or non-indenting comment line that
679 ;; happens to be a continuation line too
680 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
681 nil 'move)
682 ;; if we landed inside a string, go to the beginning of that
683 ;; string. this handles triple quoted, multi-line spanning
684 ;; strings.
685 (let ((state (parse-partial-sexp
686 (save-excursion (beginning-of-python-def-or-class)
687 (point))
688 (point))))
689 (if (nth 3 state)
690 (goto-char (nth 2 state))))
691 (py-goto-initial-line)
692 (if (py-statement-opens-block-p)
693 (+ (current-indentation) py-indent-offset)
694 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000695
696(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000697 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000698By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000699`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000700Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000701`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000702their own buffer-local copy), both those currently existing and those
703created later in the Emacs session.
704
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000705Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000706There's no excuse for such foolishness, but sometimes you have to deal
707with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708`py-indent-offset' to what it thinks it was when they created the
709mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000710
711Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000712looking for a line that opens a block of code. `py-indent-offset' is
713set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000714statement following it. If the search doesn't succeed going forward,
715it's tried again going backward."
716 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000717 (let (new-value
718 (start (point))
719 restart
720 (found nil)
721 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000722 (py-goto-initial-line)
723 (while (not (or found (eobp)))
724 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
725 (progn
726 (setq restart (point))
727 (py-goto-initial-line)
728 (if (py-statement-opens-block-p)
729 (setq found t)
730 (goto-char restart)))))
731 (if found
732 ()
733 (goto-char start)
734 (py-goto-initial-line)
735 (while (not (or found (bobp)))
736 (setq found
737 (and
738 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
739 (or (py-goto-initial-line) t) ; always true -- side effect
740 (py-statement-opens-block-p)))))
741 (setq colon-indent (current-indentation)
742 found (and found (zerop (py-next-statement 1)))
743 new-value (- (current-indentation) colon-indent))
744 (goto-char start)
745 (if found
746 (progn
747 (funcall (if global 'kill-local-variable 'make-local-variable)
748 'py-indent-offset)
749 (setq py-indent-offset new-value)
750 (message "%s value of py-indent-offset set to %d"
751 (if global "Global" "Local")
752 py-indent-offset))
753 (error "Sorry, couldn't guess a value for py-indent-offset"))))
754
755(defun py-shift-region (start end count)
756 (save-excursion
757 (goto-char end) (beginning-of-line) (setq end (point))
758 (goto-char start) (beginning-of-line) (setq start (point))
759 (indent-rigidly start end count)))
760
761(defun py-shift-region-left (start end &optional count)
762 "Shift region of Python code to the left.
763The lines from the line containing the start of the current region up
764to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000765shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000766
767If a prefix argument is given, the region is instead shifted by that
768many columns."
769 (interactive "*r\nP") ; region; raw prefix arg
770 (py-shift-region start end
771 (- (prefix-numeric-value
772 (or count py-indent-offset)))))
773
774(defun py-shift-region-right (start end &optional count)
775 "Shift region of Python code to the right.
776The lines from the line containing the start of the current region up
777to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000778shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000779
780If a prefix argument is given, the region is instead shifted by that
781many columns."
782 (interactive "*r\nP") ; region; raw prefix arg
783 (py-shift-region start end (prefix-numeric-value
784 (or count py-indent-offset))))
785
786(defun py-indent-region (start end &optional indent-offset)
787 "Reindent a region of Python code.
788The lines from the line containing the start of the current region up
789to (but not including) the line containing the end of the region are
790reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000791character in the first column, the first line is left alone and the
792rest of the region is reindented with respect to it. Else the entire
793region is reindented with respect to the (closest code or
794indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000795
796This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000797control structures are introduced or removed, or to reformat code
798using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000799
800If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000801the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000802used.
803
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000804Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000805is called! This function does not compute proper indentation from
806scratch (that's impossible in Python), it merely adjusts the existing
807indentation to be correct in context.
808
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000809Warning: This function really has no idea what to do with
810non-indenting comment lines, and shifts them as if they were indenting
811comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000813Special cases: whitespace is deleted from blank lines; continuation
814lines are shifted by the same amount their initial line was shifted,
815in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000816initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000817 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000818 (save-excursion
819 (goto-char end) (beginning-of-line) (setq end (point-marker))
820 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000821 (let ((py-indent-offset (prefix-numeric-value
822 (or indent-offset py-indent-offset)))
823 (indents '(-1)) ; stack of active indent levels
824 (target-column 0) ; column to which to indent
825 (base-shifted-by 0) ; amount last base line was shifted
826 (indent-base (if (looking-at "[ \t\n]")
827 (py-compute-indentation)
828 0))
829 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000830 (while (< (point) end)
831 (setq ci (current-indentation))
832 ;; figure out appropriate target column
833 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000834 ((or (eq (following-char) ?#) ; comment in column 1
835 (looking-at "[ \t]*$")) ; entirely blank
836 (setq target-column 0))
837 ((py-continuation-line-p) ; shift relative to base line
838 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000839 (t ; new base line
840 (if (> ci (car indents)) ; going deeper; push it
841 (setq indents (cons ci indents))
842 ;; else we should have seen this indent before
843 (setq indents (memq ci indents)) ; pop deeper indents
844 (if (null indents)
845 (error "Bad indentation in region, at line %d"
846 (save-restriction
847 (widen)
848 (1+ (count-lines 1 (point)))))))
849 (setq target-column (+ indent-base
850 (* py-indent-offset
851 (- (length indents) 2))))
852 (setq base-shifted-by (- target-column ci))))
853 ;; shift as needed
854 (if (/= ci target-column)
855 (progn
856 (delete-horizontal-space)
857 (indent-to target-column)))
858 (forward-line 1))))
859 (set-marker end nil))
860
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000861
862;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000863(defun py-previous-statement (count)
864 "Go to the start of previous Python statement.
865If the statement at point is the i'th Python statement, goes to the
866start of statement i-COUNT. If there is no such statement, goes to the
867first statement. Returns count of statements left to move.
868`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000869 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000870 (if (< count 0) (py-next-statement (- count))
871 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000872 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000873 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000874 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000875 (> count 0)
876 (zerop (forward-line -1))
877 (py-goto-statement-at-or-above))
878 (setq count (1- count)))
879 (if (> count 0) (goto-char start)))
880 count))
881
882(defun py-next-statement (count)
883 "Go to the start of next Python statement.
884If the statement at point is the i'th Python statement, goes to the
885start of statement i+COUNT. If there is no such statement, goes to the
886last statement. Returns count of statements left to move. `Statements'
887do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000888 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000889 (if (< count 0) (py-previous-statement (- count))
890 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000891 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000892 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000893 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000894 (> count 0)
895 (py-goto-statement-below))
896 (setq count (1- count)))
897 (if (> count 0) (goto-char start)))
898 count))
899
900(defun py-goto-block-up (&optional nomark)
901 "Move up to start of current block.
902Go to the statement that starts the smallest enclosing block; roughly
903speaking, this will be the closest preceding statement that ends with a
904colon and is indented less than the statement you started on. If
905successful, also sets the mark to the starting point.
906
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000907`\\[py-mark-block]' can be used afterward to mark the whole code
908block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909
910If called from a program, the mark will not be set if optional argument
911NOMARK is not nil."
912 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000913 (let ((start (point))
914 (found nil)
915 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916 (py-goto-initial-line)
917 ;; if on blank or non-indenting comment line, use the preceding stmt
918 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
919 (progn
920 (py-goto-statement-at-or-above)
921 (setq found (py-statement-opens-block-p))))
922 ;; search back for colon line indented less
923 (setq initial-indent (current-indentation))
924 (if (zerop initial-indent)
925 ;; force fast exit
926 (goto-char (point-min)))
927 (while (not (or found (bobp)))
928 (setq found
929 (and
930 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
931 (or (py-goto-initial-line) t) ; always true -- side effect
932 (< (current-indentation) initial-indent)
933 (py-statement-opens-block-p))))
934 (if found
935 (progn
936 (or nomark (push-mark start))
937 (back-to-indentation))
938 (goto-char start)
939 (error "Enclosing block not found"))))
940
941(defun beginning-of-python-def-or-class (&optional class)
942 "Move point to start of def (or class, with prefix arg).
943
944Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945arg, looks for a `class' instead. The docs assume the `def' case;
946just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000947
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000948If point is in a def statement already, and after the `d', simply
949moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000950
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000951Else (point is not in a def statement, or at or before the `d' of a
952def statement), searches for the closest preceding def statement, and
953leaves point at its start. If no such statement can be found, leaves
954point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000955
956Returns t iff a def statement is found by these rules.
957
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000958Note that doing this command repeatedly will take you closer to the
959start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000961If you want to mark the current def/class, see
962`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000963 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000964 (let ((at-or-before-p (<= (current-column) (current-indentation)))
965 (start-of-line (progn (beginning-of-line) (point)))
966 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000967 (if (or (/= start-of-stmt start-of-line)
968 (not at-or-before-p))
969 (end-of-line)) ; OK to match on this line
970 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000971 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000972
973(defun end-of-python-def-or-class (&optional class)
974 "Move point beyond end of def (or class, with prefix arg) body.
975
976By default, looks for an appropriate `def'. If you supply a prefix arg,
977looks for a `class' instead. The docs assume the `def' case; just
978substitute `class' for `def' for the other case.
979
980If point is in a def statement already, this is the def we use.
981
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000982Else if the def found by `\\[beginning-of-python-def-or-class]'
983contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000984
985Else we search forward for the closest following def, and use that.
986
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000987If a def can be found by these rules, point is moved to the start of
988the line immediately following the def block, and the position of the
989start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000990
991Else point is moved to the end of the buffer, and nil is returned.
992
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000993Note that doing this command repeatedly will take you closer to the
994end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000996If you want to mark the current def/class, see
997`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000998 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000999 (let ((start (progn (py-goto-initial-line) (point)))
1000 (which (if class "class" "def"))
1001 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002 ;; move point to start of appropriate def/class
1003 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1004 (setq state 'at-beginning)
1005 ;; else see if beginning-of-python-def-or-class hits container
1006 (if (and (beginning-of-python-def-or-class class)
1007 (progn (py-goto-beyond-block)
1008 (> (point) start)))
1009 (setq state 'at-end)
1010 ;; else search forward
1011 (goto-char start)
1012 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1013 (progn (setq state 'at-beginning)
1014 (beginning-of-line)))))
1015 (cond
1016 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1017 ((eq state 'at-end) t)
1018 ((eq state 'not-found) nil)
1019 (t (error "internal error in end-of-python-def-or-class")))))
1020
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001021
1022;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023(defun py-mark-block (&optional extend just-move)
1024 "Mark following block of lines. With prefix arg, mark structure.
1025Easier to use than explain. It sets the region to an `interesting'
1026block of succeeding lines. If point is on a blank line, it goes down to
1027the next non-blank line. That will be the start of the region. The end
1028of the region depends on the kind of line at the start:
1029
1030 - If a comment, the region will include all succeeding comment lines up
1031 to (but not including) the next non-comment line (if any).
1032
1033 - Else if a prefix arg is given, and the line begins one of these
1034 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001035
1036 if elif else try except finally for while def class
1037
Barry Warsaw7ae77681994-12-12 20:38:05 +00001038 the region will be set to the body of the structure, including
1039 following blocks that `belong' to it, but excluding trailing blank
1040 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001041 and all (if any) of the following `except' and `finally' blocks
1042 that belong to the `try' structure will be in the region. Ditto
1043 for if/elif/else, for/else and while/else structures, and (a bit
1044 degenerate, since they're always one-block structures) def and
1045 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001046
1047 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001048 block (see list above), and the block is not a `one-liner' (i.e.,
1049 the statement ends with a colon, not with code), the region will
1050 include all succeeding lines up to (but not including) the next
1051 code statement (if any) that's indented no more than the starting
1052 line, except that trailing blank and comment lines are excluded.
1053 E.g., if the starting line begins a multi-statement `def'
1054 structure, the region will be set to the full function definition,
1055 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001056
1057 - Else the region will include all succeeding lines up to (but not
1058 including) the next blank line, or code or indenting-comment line
1059 indented strictly less than the starting line. Trailing indenting
1060 comment lines are included in this case, but not trailing blank
1061 lines.
1062
1063A msg identifying the location of the mark is displayed in the echo
1064area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1065
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001066If called from a program, optional argument EXTEND plays the role of
1067the prefix arg, and if optional argument JUST-MOVE is not nil, just
1068moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001069 (interactive "P") ; raw prefix arg
1070 (py-goto-initial-line)
1071 ;; skip over blank lines
1072 (while (and
1073 (looking-at "[ \t]*$") ; while blank line
1074 (not (eobp))) ; & somewhere to go
1075 (forward-line 1))
1076 (if (eobp)
1077 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 (let ((initial-pos (point))
1079 (initial-indent (current-indentation))
1080 last-pos ; position of last stmt in region
1081 (followers
1082 '((if elif else) (elif elif else) (else)
1083 (try except finally) (except except) (finally)
1084 (for else) (while else)
1085 (def) (class) ) )
1086 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001087
1088 (cond
1089 ;; if comment line, suck up the following comment lines
1090 ((looking-at "[ \t]*#")
1091 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1092 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1093 (setq last-pos (point)))
1094
1095 ;; else if line is a block line and EXTEND given, suck up
1096 ;; the whole structure
1097 ((and extend
1098 (setq first-symbol (py-suck-up-first-keyword) )
1099 (assq first-symbol followers))
1100 (while (and
1101 (or (py-goto-beyond-block) t) ; side effect
1102 (forward-line -1) ; side effect
1103 (setq last-pos (point)) ; side effect
1104 (py-goto-statement-below)
1105 (= (current-indentation) initial-indent)
1106 (setq next-symbol (py-suck-up-first-keyword))
1107 (memq next-symbol (cdr (assq first-symbol followers))))
1108 (setq first-symbol next-symbol)))
1109
1110 ;; else if line *opens* a block, search for next stmt indented <=
1111 ((py-statement-opens-block-p)
1112 (while (and
1113 (setq last-pos (point)) ; always true -- side effect
1114 (py-goto-statement-below)
1115 (> (current-indentation) initial-indent))
1116 nil))
1117
1118 ;; else plain code line; stop at next blank line, or stmt or
1119 ;; indenting comment line indented <
1120 (t
1121 (while (and
1122 (setq last-pos (point)) ; always true -- side effect
1123 (or (py-goto-beyond-final-line) t)
1124 (not (looking-at "[ \t]*$")) ; stop at blank line
1125 (or
1126 (>= (current-indentation) initial-indent)
1127 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1128 nil)))
1129
1130 ;; skip to end of last stmt
1131 (goto-char last-pos)
1132 (py-goto-beyond-final-line)
1133
1134 ;; set mark & display
1135 (if just-move
1136 () ; just return
1137 (push-mark (point) 'no-msg)
1138 (forward-line -1)
1139 (message "Mark set after: %s" (py-suck-up-leading-text))
1140 (goto-char initial-pos))))
1141
1142(defun mark-python-def-or-class (&optional class)
1143 "Set region to body of def (or class, with prefix arg) enclosing point.
1144Pushes the current mark, then point, on the mark ring (all language
1145modes do this, but although it's handy it's never documented ...).
1146
1147In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001148hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1149`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
1151And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001152Turned out that was more confusing than useful: the `goto start' and
1153`goto end' commands are usually used to search through a file, and
1154people expect them to act a lot like `search backward' and `search
1155forward' string-search commands. But because Python `def' and `class'
1156can nest to arbitrary levels, finding the smallest def containing
1157point cannot be done via a simple backward search: the def containing
1158point may not be the closest preceding def, or even the closest
1159preceding def that's indented less. The fancy algorithm required is
1160appropriate for the usual uses of this `mark' command, but not for the
1161`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001163So the def marked by this command may not be the one either of the
1164`goto' commands find: If point is on a blank or non-indenting comment
1165line, moves back to start of the closest preceding code statement or
1166indenting comment line. If this is a `def' statement, that's the def
1167we use. Else searches for the smallest enclosing `def' block and uses
1168that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001170When an enclosing def is found: The mark is left immediately beyond
1171the last line of the def block. Point is left at the start of the
1172def, except that: if the def is preceded by a number of comment lines
1173followed by (at most) one optional blank line, point is left at the
1174start of the comments; else if the def is preceded by a blank line,
1175point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001176
1177The intent is to mark the containing def/class and its associated
1178documentation, to make moving and duplicating functions and classes
1179pleasant."
1180 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001181 (let ((start (point))
1182 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183 (push-mark start)
1184 (if (not (py-go-up-tree-to-keyword which))
1185 (progn (goto-char start)
1186 (error "Enclosing %s not found" which))
1187 ;; else enclosing def/class found
1188 (setq start (point))
1189 (py-goto-beyond-block)
1190 (push-mark (point))
1191 (goto-char start)
1192 (if (zerop (forward-line -1)) ; if there is a preceding line
1193 (progn
1194 (if (looking-at "[ \t]*$") ; it's blank
1195 (setq start (point)) ; so reset start point
1196 (goto-char start)) ; else try again
1197 (if (zerop (forward-line -1))
1198 (if (looking-at "[ \t]*#") ; a comment
1199 ;; look back for non-comment line
1200 ;; tricky: note that the regexp matches a blank
1201 ;; line, cuz \n is in the 2nd character class
1202 (and
1203 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1204 (forward-line 1))
1205 ;; no comment, so go back
1206 (goto-char start))))))))
1207
1208(defun py-comment-region (start end &optional uncomment-p)
1209 "Comment out region of code; with prefix arg, uncomment region.
1210The lines from the line containing the start of the current region up
1211to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001212commented out, by inserting the string `py-block-comment-prefix' at
1213the start of each line. With a prefix arg, removes
1214`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001215 (interactive "*r\nP") ; region; raw prefix arg
1216 (goto-char end) (beginning-of-line) (setq end (point))
1217 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001218 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001219 (save-excursion
1220 (save-restriction
1221 (narrow-to-region start end)
1222 (while (not (eobp))
1223 (if uncomment-p
1224 (and (string= py-block-comment-prefix
1225 (buffer-substring
1226 (point) (+ (point) prefix-len)))
1227 (delete-char prefix-len))
1228 (insert py-block-comment-prefix))
1229 (forward-line 1))))))
1230
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001231
1232;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001233
1234;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001235;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1236;; out of the right places, along with the keys they're on & current
1237;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001238(defun py-dump-help-string (str)
1239 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001240 (let ((locals (buffer-local-variables))
1241 funckind funcname func funcdoc
1242 (start 0) mstart end
1243 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001244 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1245 (setq mstart (match-beginning 0) end (match-end 0)
1246 funckind (substring str (match-beginning 1) (match-end 1))
1247 funcname (substring str (match-beginning 2) (match-end 2))
1248 func (intern funcname))
1249 (princ (substitute-command-keys (substring str start mstart)))
1250 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001251 ((equal funckind "c") ; command
1252 (setq funcdoc (documentation func)
1253 keys (concat
1254 "Key(s): "
1255 (mapconcat 'key-description
1256 (where-is-internal func py-mode-map)
1257 ", "))))
1258 ((equal funckind "v") ; variable
1259 (setq funcdoc (substitute-command-keys
1260 (get func 'variable-documentation))
1261 keys (if (assq func locals)
1262 (concat
1263 "Local/Global values: "
1264 (prin1-to-string (symbol-value func))
1265 " / "
1266 (prin1-to-string (default-value func)))
1267 (concat
1268 "Value: "
1269 (prin1-to-string (symbol-value func))))))
1270 (t ; unexpected
1271 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001272 (princ (format "\n-> %s:\t%s\t%s\n\n"
1273 (if (equal funckind "c") "Command" "Variable")
1274 funcname keys))
1275 (princ funcdoc)
1276 (terpri)
1277 (setq start end))
1278 (princ (substitute-command-keys (substring str start))))
1279 (print-help-return-message)))
1280
1281(defun py-describe-mode ()
1282 "Dump long form of Python-mode docs."
1283 (interactive)
1284 (py-dump-help-string "Major mode for editing Python files.
1285Knows about Python indentation, tokens, comments and continuation lines.
1286Paragraphs are separated by blank lines only.
1287
1288Major sections below begin with the string `@'; specific function and
1289variable docs begin with `->'.
1290
1291@EXECUTING PYTHON CODE
1292
1293\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1294\\[py-execute-region]\tsends the current region
1295\\[py-shell]\tstarts a Python interpreter window; this will be used by
1296\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1297%c:py-execute-buffer
1298%c:py-execute-region
1299%c:py-shell
1300
1301@VARIABLES
1302
1303py-indent-offset\tindentation increment
1304py-block-comment-prefix\tcomment string used by py-comment-region
1305
1306py-python-command\tshell command to invoke Python interpreter
1307py-scroll-process-buffer\talways scroll Python process buffer
1308py-temp-directory\tdirectory used for temp files (if needed)
1309
1310py-beep-if-tab-change\tring the bell if tab-width is changed
1311%v:py-indent-offset
1312%v:py-block-comment-prefix
1313%v:py-python-command
1314%v:py-scroll-process-buffer
1315%v:py-temp-directory
1316%v:py-beep-if-tab-change
1317
1318@KINDS OF LINES
1319
1320Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001321preceding line ends with a backslash that's not part of a comment, or
1322the paren/bracket/brace nesting level at the start of the line is
1323non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001324
1325An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001326possibly blanks or tabs), a `comment line' (leftmost non-blank
1327character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001328
1329Comment Lines
1330
1331Although all comment lines are treated alike by Python, Python mode
1332recognizes two kinds that act differently with respect to indentation.
1333
1334An `indenting comment line' is a comment line with a blank, tab or
1335nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001336treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001337indenting comment line will be indented like the comment line. All
1338other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001339following the initial `#') are `non-indenting comment lines', and
1340their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001341
1342Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001343whenever possible. Non-indenting comment lines are useful in cases
1344like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001345
1346\ta = b # a very wordy single-line comment that ends up being
1347\t #... continued onto another line
1348
1349\tif a == b:
1350##\t\tprint 'panic!' # old code we've `commented out'
1351\t\treturn a
1352
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001353Since the `#...' and `##' comment lines have a non-whitespace
1354character following the initial `#', Python mode ignores them when
1355computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356
1357Continuation Lines and Statements
1358
1359The Python-mode commands generally work on statements instead of on
1360individual lines, where a `statement' is a comment or blank line, or a
1361code line and all of its following continuation lines (if any)
1362considered as a single logical unit. The commands in this mode
1363generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001364statement containing point, even if point happens to be in the middle
1365of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001366
1367
1368@INDENTATION
1369
1370Primarily for entering new code:
1371\t\\[indent-for-tab-command]\t indent line appropriately
1372\t\\[py-newline-and-indent]\t insert newline, then indent
1373\t\\[py-delete-char]\t reduce indentation, or delete single character
1374
1375Primarily for reindenting existing code:
1376\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1377\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1378
1379\t\\[py-indent-region]\t reindent region to match its context
1380\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1381\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1382
1383Unlike most programming languages, Python uses indentation, and only
1384indentation, to specify block structure. Hence the indentation supplied
1385automatically by Python-mode is just an educated guess: only you know
1386the block structure you intend, so only you can supply correct
1387indentation.
1388
1389The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1390the indentation of preceding statements. E.g., assuming
1391py-indent-offset is 4, after you enter
1392\tif a > 0: \\[py-newline-and-indent]
1393the cursor will be moved to the position of the `_' (_ is not a
1394character in the file, it's just used here to indicate the location of
1395the cursor):
1396\tif a > 0:
1397\t _
1398If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1399to
1400\tif a > 0:
1401\t c = d
1402\t _
1403Python-mode cannot know whether that's what you intended, or whether
1404\tif a > 0:
1405\t c = d
1406\t_
1407was your intent. In general, Python-mode either reproduces the
1408indentation of the (closest code or indenting-comment) preceding
1409statement, or adds an extra py-indent-offset blanks if the preceding
1410statement has `:' as its last significant (non-whitespace and non-
1411comment) character. If the suggested indentation is too much, use
1412\\[py-delete-char] to reduce it.
1413
1414Continuation lines are given extra indentation. If you don't like the
1415suggested indentation, change it to something you do like, and Python-
1416mode will strive to indent later lines of the statement in the same way.
1417
1418If a line is a continuation line by virtue of being in an unclosed
1419paren/bracket/brace structure (`list', for short), the suggested
1420indentation depends on whether the current line contains the first item
1421in the list. If it does, it's indented py-indent-offset columns beyond
1422the indentation of the line containing the open bracket. If you don't
1423like that, change it by hand. The remaining items in the list will mimic
1424whatever indentation you give to the first item.
1425
1426If a line is a continuation line because the line preceding it ends with
1427a backslash, the third and following lines of the statement inherit their
1428indentation from the line preceding them. The indentation of the second
1429line in the statement depends on the form of the first (base) line: if
1430the base line is an assignment statement with anything more interesting
1431than the backslash following the leftmost assigning `=', the second line
1432is indented two columns beyond that `='. Else it's indented to two
1433columns beyond the leftmost solid chunk of non-whitespace characters on
1434the base line.
1435
1436Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1437repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1438structure you intend.
1439%c:indent-for-tab-command
1440%c:py-newline-and-indent
1441%c:py-delete-char
1442
1443
1444The next function may be handy when editing code you didn't write:
1445%c:py-guess-indent-offset
1446
1447
1448The remaining `indent' functions apply to a region of Python code. They
1449assume the block structure (equals indentation, in Python) of the region
1450is correct, and alter the indentation in various ways while preserving
1451the block structure:
1452%c:py-indent-region
1453%c:py-shift-region-left
1454%c:py-shift-region-right
1455
1456@MARKING & MANIPULATING REGIONS OF CODE
1457
1458\\[py-mark-block]\t mark block of lines
1459\\[mark-python-def-or-class]\t mark smallest enclosing def
1460\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1461\\[py-comment-region]\t comment out region of code
1462\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1463%c:py-mark-block
1464%c:mark-python-def-or-class
1465%c:py-comment-region
1466
1467@MOVING POINT
1468
1469\\[py-previous-statement]\t move to statement preceding point
1470\\[py-next-statement]\t move to statement following point
1471\\[py-goto-block-up]\t move up to start of current block
1472\\[beginning-of-python-def-or-class]\t move to start of def
1473\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1474\\[end-of-python-def-or-class]\t move to end of def
1475\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1476
1477The first two move to one statement beyond the statement that contains
1478point. A numeric prefix argument tells them to move that many
1479statements instead. Blank lines, comment lines, and continuation lines
1480do not count as `statements' for these commands. So, e.g., you can go
1481to the first code statement in a file by entering
1482\t\\[beginning-of-buffer]\t to move to the top of the file
1483\t\\[py-next-statement]\t to skip over initial comments and blank lines
1484Or do `\\[py-previous-statement]' with a huge prefix argument.
1485%c:py-previous-statement
1486%c:py-next-statement
1487%c:py-goto-block-up
1488%c:beginning-of-python-def-or-class
1489%c:end-of-python-def-or-class
1490
1491@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1492
1493`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1494
1495`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1496overall class and def structure of a module.
1497
1498`\\[back-to-indentation]' moves point to a line's first non-blank character.
1499
1500`\\[indent-relative]' is handy for creating odd indentation.
1501
1502@OTHER EMACS HINTS
1503
1504If you don't like the default value of a variable, change its value to
1505whatever you do like by putting a `setq' line in your .emacs file.
1506E.g., to set the indentation increment to 4, put this line in your
1507.emacs:
1508\t(setq py-indent-offset 4)
1509To see the value of a variable, do `\\[describe-variable]' and enter the variable
1510name at the prompt.
1511
1512When entering a key sequence like `C-c C-n', it is not necessary to
1513release the CONTROL key after doing the `C-c' part -- it suffices to
1514press the CONTROL key, press and release `c' (while still holding down
1515CONTROL), press and release `n' (while still holding down CONTROL), &
1516then release CONTROL.
1517
1518Entering Python mode calls with no arguments the value of the variable
1519`python-mode-hook', if that value exists and is not nil; for backward
1520compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1521the Elisp manual for details.
1522
1523Obscure: When python-mode is first loaded, it looks for all bindings
1524to newline-and-indent in the global keymap, and shadows them with
1525local bindings to py-newline-and-indent."))
1526
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001527
1528;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001529
1530(defvar py-parse-state-re
1531 (concat
1532 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1533 "\\|"
1534 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001535
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536;; returns the parse state at point (see parse-partial-sexp docs)
1537(defun py-parse-state ()
1538 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540 ;; back up to the first preceding line (if any; else start of
1541 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542 ;; whitespace and non-comment character. These are good places
1543 ;; to start parsing to see whether where we started is at a
1544 ;; non-zero nesting level. It may be slow for people who write
1545 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001546 (re-search-backward py-parse-state-re nil 'move)
1547 (beginning-of-line)
1548 (parse-partial-sexp (point) here))))
1549
1550;; if point is at a non-zero nesting level, returns the number of the
1551;; character that opens the smallest enclosing unclosed list; else
1552;; returns nil.
1553(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001554 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001555 (if (zerop (car status))
1556 nil ; not in a nest
1557 (car (cdr status))))) ; char# of open bracket
1558
1559;; t iff preceding line ends with backslash that's not in a comment
1560(defun py-backslash-continuation-line-p ()
1561 (save-excursion
1562 (beginning-of-line)
1563 (and
1564 ;; use a cheap test first to avoid the regexp if possible
1565 ;; use 'eq' because char-after may return nil
1566 (eq (char-after (- (point) 2)) ?\\ )
1567 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569 (looking-at py-continued-re))))
1570
1571;; t iff current line is a continuation line
1572(defun py-continuation-line-p ()
1573 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001574 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001575 (or (py-backslash-continuation-line-p)
1576 (py-nesting-level))))
1577
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001578;; go to initial line of current statement; usually this is the line
1579;; we're on, but if we're on the 2nd or following lines of a
1580;; continuation block, we need to go up to the first line of the
1581;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001582;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001583;; Tricky: We want to avoid quadratic-time behavior for long continued
1584;; blocks, whether of the backslash or open-bracket varieties, or a
1585;; mix of the two. The following manages to do that in the usual
1586;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001587(defun py-goto-initial-line ()
1588 (let ( open-bracket-pos )
1589 (while (py-continuation-line-p)
1590 (beginning-of-line)
1591 (if (py-backslash-continuation-line-p)
1592 (while (py-backslash-continuation-line-p)
1593 (forward-line -1))
1594 ;; else zip out of nested brackets/braces/parens
1595 (while (setq open-bracket-pos (py-nesting-level))
1596 (goto-char open-bracket-pos)))))
1597 (beginning-of-line))
1598
1599;; go to point right beyond final line of current statement; usually
1600;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001601;; statement we need to skip over the continuation lines. Tricky:
1602;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001603(defun py-goto-beyond-final-line ()
1604 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001605 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001606 (while (and (py-continuation-line-p)
1607 (not (eobp)))
1608 ;; skip over the backslash flavor
1609 (while (and (py-backslash-continuation-line-p)
1610 (not (eobp)))
1611 (forward-line 1))
1612 ;; if in nest, zip to the end of the nest
1613 (setq state (py-parse-state))
1614 (if (and (not (zerop (car state)))
1615 (not (eobp)))
1616 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001617 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001618 ;; the 3rd argument should be plain 0
1619 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1620 nil state)
1621 (forward-line 1))))))
1622
1623;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001624;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001625(defun py-statement-opens-block-p ()
1626 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001627 (let ((start (point))
1628 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1629 (searching t)
1630 (answer nil)
1631 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632 (goto-char start)
1633 (while searching
1634 ;; look for a colon with nothing after it except whitespace, and
1635 ;; maybe a comment
1636 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1637 finish t)
1638 (if (eq (point) finish) ; note: no `else' clause; just
1639 ; keep searching if we're not at
1640 ; the end yet
1641 ;; sure looks like it opens a block -- but it might
1642 ;; be in a comment
1643 (progn
1644 (setq searching nil) ; search is done either way
1645 (setq state (parse-partial-sexp start
1646 (match-beginning 0)))
1647 (setq answer (not (nth 4 state)))))
1648 ;; search failed: couldn't find another interesting colon
1649 (setq searching nil)))
1650 answer)))
1651
1652;; go to point right beyond final line of block begun by the current
1653;; line. This is the same as where py-goto-beyond-final-line goes
1654;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001655;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656(defun py-goto-beyond-block ()
1657 (if (py-statement-opens-block-p)
1658 (py-mark-block nil 'just-move)
1659 (py-goto-beyond-final-line)))
1660
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001661;; go to start of first statement (not blank or comment or
1662;; continuation line) at or preceding point. returns t if there is
1663;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001664(defun py-goto-statement-at-or-above ()
1665 (py-goto-initial-line)
1666 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667 ;; skip back over blank & comment lines
1668 ;; note: will skip a blank or comment line that happens to be
1669 ;; a continuation line too
1670 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1671 (progn (py-goto-initial-line) t)
1672 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001673 t))
1674
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001675;; go to start of first statement (not blank or comment or
1676;; continuation line) following the statement containing point returns
1677;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001678(defun py-goto-statement-below ()
1679 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001680 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001681 (py-goto-beyond-final-line)
1682 (while (and
1683 (looking-at py-blank-or-comment-re)
1684 (not (eobp)))
1685 (forward-line 1))
1686 (if (eobp)
1687 (progn (goto-char start) nil)
1688 t)))
1689
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001690;; go to start of statement, at or preceding point, starting with
1691;; keyword KEY. Skips blank lines and non-indenting comments upward
1692;; first. If that statement starts with KEY, done, else go back to
1693;; first enclosing block starting with KEY. If successful, leaves
1694;; point at the start of the KEY line & returns t. Else leaves point
1695;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001696(defun py-go-up-tree-to-keyword (key)
1697 ;; skip blanks and non-indenting #
1698 (py-goto-initial-line)
1699 (while (and
1700 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1701 (zerop (forward-line -1))) ; go back
1702 nil)
1703 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001704 (let* ((re (concat "[ \t]*" key "\\b"))
1705 (case-fold-search nil) ; let* so looking-at sees this
1706 (found (looking-at re))
1707 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001708 (while (not (or found dead))
1709 (condition-case nil ; in case no enclosing block
1710 (py-goto-block-up 'no-mark)
1711 (error (setq dead t)))
1712 (or dead (setq found (looking-at re))))
1713 (beginning-of-line)
1714 found))
1715
1716;; return string in buffer from start of indentation to end of line;
1717;; prefix "..." if leading whitespace was skipped
1718(defun py-suck-up-leading-text ()
1719 (save-excursion
1720 (back-to-indentation)
1721 (concat
1722 (if (bolp) "" "...")
1723 (buffer-substring (point) (progn (end-of-line) (point))))))
1724
1725;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1726;; as a Lisp symbol; return nil if none
1727(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001728 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1730 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1731 nil)))
1732
1733(defun py-make-temp-name ()
1734 (make-temp-name
1735 (concat (file-name-as-directory py-temp-directory) "python")))
1736
1737(defun py-delete-file-silently (fname)
1738 (condition-case nil
1739 (delete-file fname)
1740 (error nil)))
1741
1742(defun py-kill-emacs-hook ()
1743 ;; delete our temp files
1744 (while py-file-queue
1745 (py-delete-file-silently (car py-file-queue))
1746 (setq py-file-queue (cdr py-file-queue)))
1747 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1748 ;; run the hook we inherited, if any
1749 (and py-inherited-kill-emacs-hook
1750 (funcall py-inherited-kill-emacs-hook))))
1751
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752;; make PROCESS's buffer visible, append STRING to it, and force
1753;; display; also make shell-mode believe the user typed this string,
1754;; so that kill-output-from-shell and show-output-from-shell work
1755;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757 (let ((cbuf (current-buffer))
1758 (pbuf (process-buffer process))
1759 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760 (set-buffer pbuf)
1761 (goto-char (point-max))
1762 (move-marker (process-mark process) (point))
1763 (if (not py-this-is-emacs-19-p)
1764 (move-marker last-input-start (point))) ; muck w/ shell-mode
1765 (funcall (process-filter process) process string)
1766 (if (not py-this-is-emacs-19-p)
1767 (move-marker last-input-end (point))) ; muck w/ shell-mode
1768 (set-buffer cbuf))
1769 (sit-for 0))
1770
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001771
1772
Barry Warsaw850437a1995-03-08 21:50:28 +00001773(defconst py-version "$Revision$"
1774 "`python-mode' version number.")
1775(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1776 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777
Barry Warsaw850437a1995-03-08 21:50:28 +00001778(defun py-version ()
1779 "Echo the current version of `python-mode' in the minibuffer."
1780 (interactive)
1781 (message "Using `python-mode' version %s" py-version)
1782 (py-keep-region-active))
1783
1784;; only works under Emacs 19
1785;(eval-when-compile
1786; (require 'reporter))
1787
1788(defun py-submit-bug-report (enhancement-p)
1789 "Submit via mail a bug report on `python-mode'.
1790With \\[universal-argument] just submit an enhancement request."
1791 (interactive
1792 (list (not (y-or-n-p
1793 "Is this a bug report? (hit `n' to send other comments) "))))
1794 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1795 (require 'reporter)
1796 (reporter-submit-bug-report
1797 py-help-address ;address
1798 "python-mode" ;pkgname
1799 ;; varlist
1800 (if enhancement-p nil
1801 '(py-python-command
1802 py-indent-offset
1803 py-block-comment-prefix
1804 py-scroll-process-buffer
1805 py-temp-directory
1806 py-beep-if-tab-change))
1807 nil ;pre-hooks
1808 nil ;post-hooks
1809 "Dear Barry,") ;salutation
1810 (if enhancement-p nil
1811 (set-mark (point))
1812 (insert
1813"Please replace this text with a sufficiently large code sample\n\
1814and an exact recipe so that I can reproduce your problem. Failure\n\
1815to do so may mean a greater delay in fixing your bug.\n\n")
1816 (exchange-point-and-mark)
1817 (py-keep-region-active))))
1818
1819
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001820;; arrange to kill temp files when Emacs exists
1821(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1822 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1823 ;; have to trust that other people are as respectful of our hook
1824 ;; fiddling as we are of theirs
1825 (if (boundp 'py-inherited-kill-emacs-hook)
1826 ;; we were loaded before -- trust others not to have screwed us
1827 ;; in the meantime (no choice, really)
1828 nil
1829 ;; else arrange for our hook to run theirs
1830 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1831 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1832
1833
1834
1835(provide 'python-mode)
1836;;; python-mode.el ends here