blob: 128641e1e72fa98c14cb0245943f6f88ffac201f [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
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000593;; required for pending-del and delsel modes
594(put 'py-delete-char 'delete-selection 'supersede)
595(put 'py-delete-char 'pending-delete 'supersede)
596
Barry Warsaw7ae77681994-12-12 20:38:05 +0000597(defun py-indent-line ()
598 "Fix the indentation of the current line according to Python rules."
599 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000600 (let* ((ci (current-indentation))
601 (move-to-indentation-p (<= (current-column) ci))
602 (need (py-compute-indentation)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000603 (if (/= ci need)
604 (save-excursion
605 (beginning-of-line)
606 (delete-horizontal-space)
607 (indent-to need)))
608 (if move-to-indentation-p (back-to-indentation))))
609
610(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000611 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000612This is just `strives to' because correct indentation can't be computed
613from scratch for Python code. In general, deletes the whitespace before
614point, inserts a newline, and takes an educated guess as to how you want
615the new line indented."
616 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000617 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000618 (if (< ci (current-column)) ; if point beyond indentation
619 (newline-and-indent)
620 ;; else try to act like newline-and-indent "normally" acts
621 (beginning-of-line)
622 (insert-char ?\n 1)
623 (move-to-column ci))))
624
625(defun py-compute-indentation ()
626 (save-excursion
627 (beginning-of-line)
628 (cond
629 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000630 ((py-continuation-line-p)
631 (let ((startpos (point))
632 (open-bracket-pos (py-nesting-level))
633 endpos searching found)
634 (if open-bracket-pos
635 (progn
636 ;; align with first item in list; else a normal
637 ;; indent beyond the line with the open bracket
638 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
639 ;; is the first list item on the same line?
640 (skip-chars-forward " \t")
641 (if (null (memq (following-char) '(?\n ?# ?\\)))
642 ; yes, so line up with it
643 (current-column)
644 ;; first list item on another line, or doesn't exist yet
645 (forward-line 1)
646 (while (and (< (point) startpos)
647 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
648 (forward-line 1))
649 (if (< (point) startpos)
650 ;; again mimic the first list item
651 (current-indentation)
652 ;; else they're about to enter the first item
653 (goto-char open-bracket-pos)
654 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000655
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000656 ;; else on backslash continuation line
657 (forward-line -1)
658 (if (py-continuation-line-p) ; on at least 3rd line in block
659 (current-indentation) ; so just continue the pattern
660 ;; else started on 2nd line in block, so indent more.
661 ;; if base line is an assignment with a start on a RHS,
662 ;; indent to 2 beyond the leftmost "="; else skip first
663 ;; chunk of non-whitespace characters on base line, + 1 more
664 ;; column
665 (end-of-line)
666 (setq endpos (point) searching t)
667 (back-to-indentation)
668 (setq startpos (point))
669 ;; look at all "=" from left to right, stopping at first
670 ;; one not nested in a list or string
671 (while searching
672 (skip-chars-forward "^=" endpos)
673 (if (= (point) endpos)
674 (setq searching nil)
675 (forward-char 1)
676 (setq state (parse-partial-sexp startpos (point)))
677 (if (and (zerop (car state)) ; not in a bracket
678 (null (nth 3 state))) ; & not in a string
679 (progn
680 (setq searching nil) ; done searching in any case
681 (setq found
682 (not (or
683 (eq (following-char) ?=)
684 (memq (char-after (- (point) 2))
685 '(?< ?> ?!)))))))))
686 (if (or (not found) ; not an assignment
687 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
688 (progn
689 (goto-char startpos)
690 (skip-chars-forward "^ \t\n")))
691 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000692
693 ;; not on a continuation line
694
695 ;; if at start of restriction, or on a non-indenting comment line,
696 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000697 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
698 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000699
700 ;; else indentation based on that of the statement that precedes
701 ;; us; use the first line of that statement to establish the base,
702 ;; in case the user forced a non-std indentation for the
703 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000704 (t
705 ;; skip back over blank & non-indenting comment lines
706 ;; note: will skip a blank or non-indenting comment line that
707 ;; happens to be a continuation line too
708 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
709 nil 'move)
710 ;; if we landed inside a string, go to the beginning of that
711 ;; string. this handles triple quoted, multi-line spanning
712 ;; strings.
713 (let ((state (parse-partial-sexp
714 (save-excursion (beginning-of-python-def-or-class)
715 (point))
716 (point))))
717 (if (nth 3 state)
718 (goto-char (nth 2 state))))
719 (py-goto-initial-line)
720 (if (py-statement-opens-block-p)
721 (+ (current-indentation) py-indent-offset)
722 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000723
724(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000725 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000726By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000727`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000728Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000729`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000730their own buffer-local copy), both those currently existing and those
731created later in the Emacs session.
732
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000733Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000734There's no excuse for such foolishness, but sometimes you have to deal
735with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000736`py-indent-offset' to what it thinks it was when they created the
737mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738
739Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000740looking for a line that opens a block of code. `py-indent-offset' is
741set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000742statement following it. If the search doesn't succeed going forward,
743it's tried again going backward."
744 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000745 (let (new-value
746 (start (point))
747 restart
748 (found nil)
749 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000750 (py-goto-initial-line)
751 (while (not (or found (eobp)))
752 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
753 (progn
754 (setq restart (point))
755 (py-goto-initial-line)
756 (if (py-statement-opens-block-p)
757 (setq found t)
758 (goto-char restart)))))
759 (if found
760 ()
761 (goto-char start)
762 (py-goto-initial-line)
763 (while (not (or found (bobp)))
764 (setq found
765 (and
766 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
767 (or (py-goto-initial-line) t) ; always true -- side effect
768 (py-statement-opens-block-p)))))
769 (setq colon-indent (current-indentation)
770 found (and found (zerop (py-next-statement 1)))
771 new-value (- (current-indentation) colon-indent))
772 (goto-char start)
773 (if found
774 (progn
775 (funcall (if global 'kill-local-variable 'make-local-variable)
776 'py-indent-offset)
777 (setq py-indent-offset new-value)
778 (message "%s value of py-indent-offset set to %d"
779 (if global "Global" "Local")
780 py-indent-offset))
781 (error "Sorry, couldn't guess a value for py-indent-offset"))))
782
783(defun py-shift-region (start end count)
784 (save-excursion
785 (goto-char end) (beginning-of-line) (setq end (point))
786 (goto-char start) (beginning-of-line) (setq start (point))
787 (indent-rigidly start end count)))
788
789(defun py-shift-region-left (start end &optional count)
790 "Shift region of Python code to the left.
791The lines from the line containing the start of the current region up
792to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000793shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000794
795If a prefix argument is given, the region is instead shifted by that
796many columns."
797 (interactive "*r\nP") ; region; raw prefix arg
798 (py-shift-region start end
799 (- (prefix-numeric-value
800 (or count py-indent-offset)))))
801
802(defun py-shift-region-right (start end &optional count)
803 "Shift region of Python code to the right.
804The lines from the line containing the start of the current region up
805to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000806shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000807
808If a prefix argument is given, the region is instead shifted by that
809many columns."
810 (interactive "*r\nP") ; region; raw prefix arg
811 (py-shift-region start end (prefix-numeric-value
812 (or count py-indent-offset))))
813
814(defun py-indent-region (start end &optional indent-offset)
815 "Reindent a region of Python code.
816The lines from the line containing the start of the current region up
817to (but not including) the line containing the end of the region are
818reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000819character in the first column, the first line is left alone and the
820rest of the region is reindented with respect to it. Else the entire
821region is reindented with respect to the (closest code or
822indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000823
824This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000825control structures are introduced or removed, or to reformat code
826using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000827
828If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000829the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000830used.
831
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000832Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000833is called! This function does not compute proper indentation from
834scratch (that's impossible in Python), it merely adjusts the existing
835indentation to be correct in context.
836
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000837Warning: This function really has no idea what to do with
838non-indenting comment lines, and shifts them as if they were indenting
839comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000840
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000841Special cases: whitespace is deleted from blank lines; continuation
842lines are shifted by the same amount their initial line was shifted,
843in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000844initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000845 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000846 (save-excursion
847 (goto-char end) (beginning-of-line) (setq end (point-marker))
848 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000849 (let ((py-indent-offset (prefix-numeric-value
850 (or indent-offset py-indent-offset)))
851 (indents '(-1)) ; stack of active indent levels
852 (target-column 0) ; column to which to indent
853 (base-shifted-by 0) ; amount last base line was shifted
854 (indent-base (if (looking-at "[ \t\n]")
855 (py-compute-indentation)
856 0))
857 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000858 (while (< (point) end)
859 (setq ci (current-indentation))
860 ;; figure out appropriate target column
861 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000862 ((or (eq (following-char) ?#) ; comment in column 1
863 (looking-at "[ \t]*$")) ; entirely blank
864 (setq target-column 0))
865 ((py-continuation-line-p) ; shift relative to base line
866 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000867 (t ; new base line
868 (if (> ci (car indents)) ; going deeper; push it
869 (setq indents (cons ci indents))
870 ;; else we should have seen this indent before
871 (setq indents (memq ci indents)) ; pop deeper indents
872 (if (null indents)
873 (error "Bad indentation in region, at line %d"
874 (save-restriction
875 (widen)
876 (1+ (count-lines 1 (point)))))))
877 (setq target-column (+ indent-base
878 (* py-indent-offset
879 (- (length indents) 2))))
880 (setq base-shifted-by (- target-column ci))))
881 ;; shift as needed
882 (if (/= ci target-column)
883 (progn
884 (delete-horizontal-space)
885 (indent-to target-column)))
886 (forward-line 1))))
887 (set-marker end nil))
888
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889
890;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000891(defun py-previous-statement (count)
892 "Go to the start of previous Python statement.
893If the statement at point is the i'th Python statement, goes to the
894start of statement i-COUNT. If there is no such statement, goes to the
895first statement. Returns count of statements left to move.
896`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000898 (if (< count 0) (py-next-statement (- count))
899 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000900 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000902 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000903 (> count 0)
904 (zerop (forward-line -1))
905 (py-goto-statement-at-or-above))
906 (setq count (1- count)))
907 (if (> count 0) (goto-char start)))
908 count))
909
910(defun py-next-statement (count)
911 "Go to the start of next Python statement.
912If the statement at point is the i'th Python statement, goes to the
913start of statement i+COUNT. If there is no such statement, goes to the
914last statement. Returns count of statements left to move. `Statements'
915do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000916 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000917 (if (< count 0) (py-previous-statement (- count))
918 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000919 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000920 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000921 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000922 (> count 0)
923 (py-goto-statement-below))
924 (setq count (1- count)))
925 (if (> count 0) (goto-char start)))
926 count))
927
928(defun py-goto-block-up (&optional nomark)
929 "Move up to start of current block.
930Go to the statement that starts the smallest enclosing block; roughly
931speaking, this will be the closest preceding statement that ends with a
932colon and is indented less than the statement you started on. If
933successful, also sets the mark to the starting point.
934
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000935`\\[py-mark-block]' can be used afterward to mark the whole code
936block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000937
938If called from a program, the mark will not be set if optional argument
939NOMARK is not nil."
940 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000941 (let ((start (point))
942 (found nil)
943 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000944 (py-goto-initial-line)
945 ;; if on blank or non-indenting comment line, use the preceding stmt
946 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
947 (progn
948 (py-goto-statement-at-or-above)
949 (setq found (py-statement-opens-block-p))))
950 ;; search back for colon line indented less
951 (setq initial-indent (current-indentation))
952 (if (zerop initial-indent)
953 ;; force fast exit
954 (goto-char (point-min)))
955 (while (not (or found (bobp)))
956 (setq found
957 (and
958 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
959 (or (py-goto-initial-line) t) ; always true -- side effect
960 (< (current-indentation) initial-indent)
961 (py-statement-opens-block-p))))
962 (if found
963 (progn
964 (or nomark (push-mark start))
965 (back-to-indentation))
966 (goto-char start)
967 (error "Enclosing block not found"))))
968
969(defun beginning-of-python-def-or-class (&optional class)
970 "Move point to start of def (or class, with prefix arg).
971
972Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000973arg, looks for a `class' instead. The docs assume the `def' case;
974just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000975
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000976If point is in a def statement already, and after the `d', simply
977moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000979Else (point is not in a def statement, or at or before the `d' of a
980def statement), searches for the closest preceding def statement, and
981leaves point at its start. If no such statement can be found, leaves
982point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000983
984Returns t iff a def statement is found by these rules.
985
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000986Note that doing this command repeatedly will take you closer to the
987start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000989If you want to mark the current def/class, see
990`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000991 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000992 (let ((at-or-before-p (<= (current-column) (current-indentation)))
993 (start-of-line (progn (beginning-of-line) (point)))
994 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995 (if (or (/= start-of-stmt start-of-line)
996 (not at-or-before-p))
997 (end-of-line)) ; OK to match on this line
998 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000999 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001000
1001(defun end-of-python-def-or-class (&optional class)
1002 "Move point beyond end of def (or class, with prefix arg) body.
1003
1004By default, looks for an appropriate `def'. If you supply a prefix arg,
1005looks for a `class' instead. The docs assume the `def' case; just
1006substitute `class' for `def' for the other case.
1007
1008If point is in a def statement already, this is the def we use.
1009
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001010Else if the def found by `\\[beginning-of-python-def-or-class]'
1011contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001012
1013Else we search forward for the closest following def, and use that.
1014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001015If a def can be found by these rules, point is moved to the start of
1016the line immediately following the def block, and the position of the
1017start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018
1019Else point is moved to the end of the buffer, and nil is returned.
1020
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001021Note that doing this command repeatedly will take you closer to the
1022end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024If you want to mark the current def/class, see
1025`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001026 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001027 (let ((start (progn (py-goto-initial-line) (point)))
1028 (which (if class "class" "def"))
1029 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030 ;; move point to start of appropriate def/class
1031 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1032 (setq state 'at-beginning)
1033 ;; else see if beginning-of-python-def-or-class hits container
1034 (if (and (beginning-of-python-def-or-class class)
1035 (progn (py-goto-beyond-block)
1036 (> (point) start)))
1037 (setq state 'at-end)
1038 ;; else search forward
1039 (goto-char start)
1040 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1041 (progn (setq state 'at-beginning)
1042 (beginning-of-line)))))
1043 (cond
1044 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1045 ((eq state 'at-end) t)
1046 ((eq state 'not-found) nil)
1047 (t (error "internal error in end-of-python-def-or-class")))))
1048
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001049
1050;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001051(defun py-mark-block (&optional extend just-move)
1052 "Mark following block of lines. With prefix arg, mark structure.
1053Easier to use than explain. It sets the region to an `interesting'
1054block of succeeding lines. If point is on a blank line, it goes down to
1055the next non-blank line. That will be the start of the region. The end
1056of the region depends on the kind of line at the start:
1057
1058 - If a comment, the region will include all succeeding comment lines up
1059 to (but not including) the next non-comment line (if any).
1060
1061 - Else if a prefix arg is given, and the line begins one of these
1062 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001063
1064 if elif else try except finally for while def class
1065
Barry Warsaw7ae77681994-12-12 20:38:05 +00001066 the region will be set to the body of the structure, including
1067 following blocks that `belong' to it, but excluding trailing blank
1068 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 and all (if any) of the following `except' and `finally' blocks
1070 that belong to the `try' structure will be in the region. Ditto
1071 for if/elif/else, for/else and while/else structures, and (a bit
1072 degenerate, since they're always one-block structures) def and
1073 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001074
1075 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001076 block (see list above), and the block is not a `one-liner' (i.e.,
1077 the statement ends with a colon, not with code), the region will
1078 include all succeeding lines up to (but not including) the next
1079 code statement (if any) that's indented no more than the starting
1080 line, except that trailing blank and comment lines are excluded.
1081 E.g., if the starting line begins a multi-statement `def'
1082 structure, the region will be set to the full function definition,
1083 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084
1085 - Else the region will include all succeeding lines up to (but not
1086 including) the next blank line, or code or indenting-comment line
1087 indented strictly less than the starting line. Trailing indenting
1088 comment lines are included in this case, but not trailing blank
1089 lines.
1090
1091A msg identifying the location of the mark is displayed in the echo
1092area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1093
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094If called from a program, optional argument EXTEND plays the role of
1095the prefix arg, and if optional argument JUST-MOVE is not nil, just
1096moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001097 (interactive "P") ; raw prefix arg
1098 (py-goto-initial-line)
1099 ;; skip over blank lines
1100 (while (and
1101 (looking-at "[ \t]*$") ; while blank line
1102 (not (eobp))) ; & somewhere to go
1103 (forward-line 1))
1104 (if (eobp)
1105 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001106 (let ((initial-pos (point))
1107 (initial-indent (current-indentation))
1108 last-pos ; position of last stmt in region
1109 (followers
1110 '((if elif else) (elif elif else) (else)
1111 (try except finally) (except except) (finally)
1112 (for else) (while else)
1113 (def) (class) ) )
1114 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115
1116 (cond
1117 ;; if comment line, suck up the following comment lines
1118 ((looking-at "[ \t]*#")
1119 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1120 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1121 (setq last-pos (point)))
1122
1123 ;; else if line is a block line and EXTEND given, suck up
1124 ;; the whole structure
1125 ((and extend
1126 (setq first-symbol (py-suck-up-first-keyword) )
1127 (assq first-symbol followers))
1128 (while (and
1129 (or (py-goto-beyond-block) t) ; side effect
1130 (forward-line -1) ; side effect
1131 (setq last-pos (point)) ; side effect
1132 (py-goto-statement-below)
1133 (= (current-indentation) initial-indent)
1134 (setq next-symbol (py-suck-up-first-keyword))
1135 (memq next-symbol (cdr (assq first-symbol followers))))
1136 (setq first-symbol next-symbol)))
1137
1138 ;; else if line *opens* a block, search for next stmt indented <=
1139 ((py-statement-opens-block-p)
1140 (while (and
1141 (setq last-pos (point)) ; always true -- side effect
1142 (py-goto-statement-below)
1143 (> (current-indentation) initial-indent))
1144 nil))
1145
1146 ;; else plain code line; stop at next blank line, or stmt or
1147 ;; indenting comment line indented <
1148 (t
1149 (while (and
1150 (setq last-pos (point)) ; always true -- side effect
1151 (or (py-goto-beyond-final-line) t)
1152 (not (looking-at "[ \t]*$")) ; stop at blank line
1153 (or
1154 (>= (current-indentation) initial-indent)
1155 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1156 nil)))
1157
1158 ;; skip to end of last stmt
1159 (goto-char last-pos)
1160 (py-goto-beyond-final-line)
1161
1162 ;; set mark & display
1163 (if just-move
1164 () ; just return
1165 (push-mark (point) 'no-msg)
1166 (forward-line -1)
1167 (message "Mark set after: %s" (py-suck-up-leading-text))
1168 (goto-char initial-pos))))
1169
1170(defun mark-python-def-or-class (&optional class)
1171 "Set region to body of def (or class, with prefix arg) enclosing point.
1172Pushes the current mark, then point, on the mark ring (all language
1173modes do this, but although it's handy it's never documented ...).
1174
1175In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001176hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1177`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001178
1179And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001180Turned out that was more confusing than useful: the `goto start' and
1181`goto end' commands are usually used to search through a file, and
1182people expect them to act a lot like `search backward' and `search
1183forward' string-search commands. But because Python `def' and `class'
1184can nest to arbitrary levels, finding the smallest def containing
1185point cannot be done via a simple backward search: the def containing
1186point may not be the closest preceding def, or even the closest
1187preceding def that's indented less. The fancy algorithm required is
1188appropriate for the usual uses of this `mark' command, but not for the
1189`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001191So the def marked by this command may not be the one either of the
1192`goto' commands find: If point is on a blank or non-indenting comment
1193line, moves back to start of the closest preceding code statement or
1194indenting comment line. If this is a `def' statement, that's the def
1195we use. Else searches for the smallest enclosing `def' block and uses
1196that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198When an enclosing def is found: The mark is left immediately beyond
1199the last line of the def block. Point is left at the start of the
1200def, except that: if the def is preceded by a number of comment lines
1201followed by (at most) one optional blank line, point is left at the
1202start of the comments; else if the def is preceded by a blank line,
1203point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001204
1205The intent is to mark the containing def/class and its associated
1206documentation, to make moving and duplicating functions and classes
1207pleasant."
1208 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001209 (let ((start (point))
1210 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001211 (push-mark start)
1212 (if (not (py-go-up-tree-to-keyword which))
1213 (progn (goto-char start)
1214 (error "Enclosing %s not found" which))
1215 ;; else enclosing def/class found
1216 (setq start (point))
1217 (py-goto-beyond-block)
1218 (push-mark (point))
1219 (goto-char start)
1220 (if (zerop (forward-line -1)) ; if there is a preceding line
1221 (progn
1222 (if (looking-at "[ \t]*$") ; it's blank
1223 (setq start (point)) ; so reset start point
1224 (goto-char start)) ; else try again
1225 (if (zerop (forward-line -1))
1226 (if (looking-at "[ \t]*#") ; a comment
1227 ;; look back for non-comment line
1228 ;; tricky: note that the regexp matches a blank
1229 ;; line, cuz \n is in the 2nd character class
1230 (and
1231 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1232 (forward-line 1))
1233 ;; no comment, so go back
1234 (goto-char start))))))))
1235
1236(defun py-comment-region (start end &optional uncomment-p)
1237 "Comment out region of code; with prefix arg, uncomment region.
1238The lines from the line containing the start of the current region up
1239to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001240commented out, by inserting the string `py-block-comment-prefix' at
1241the start of each line. With a prefix arg, removes
1242`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001243 (interactive "*r\nP") ; region; raw prefix arg
1244 (goto-char end) (beginning-of-line) (setq end (point))
1245 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001246 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001247 (save-excursion
1248 (save-restriction
1249 (narrow-to-region start end)
1250 (while (not (eobp))
1251 (if uncomment-p
1252 (and (string= py-block-comment-prefix
1253 (buffer-substring
1254 (point) (+ (point) prefix-len)))
1255 (delete-char prefix-len))
1256 (insert py-block-comment-prefix))
1257 (forward-line 1))))))
1258
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001259
1260;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001261
1262;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001263;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1264;; out of the right places, along with the keys they're on & current
1265;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001266(defun py-dump-help-string (str)
1267 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001268 (let ((locals (buffer-local-variables))
1269 funckind funcname func funcdoc
1270 (start 0) mstart end
1271 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001272 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1273 (setq mstart (match-beginning 0) end (match-end 0)
1274 funckind (substring str (match-beginning 1) (match-end 1))
1275 funcname (substring str (match-beginning 2) (match-end 2))
1276 func (intern funcname))
1277 (princ (substitute-command-keys (substring str start mstart)))
1278 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001279 ((equal funckind "c") ; command
1280 (setq funcdoc (documentation func)
1281 keys (concat
1282 "Key(s): "
1283 (mapconcat 'key-description
1284 (where-is-internal func py-mode-map)
1285 ", "))))
1286 ((equal funckind "v") ; variable
1287 (setq funcdoc (substitute-command-keys
1288 (get func 'variable-documentation))
1289 keys (if (assq func locals)
1290 (concat
1291 "Local/Global values: "
1292 (prin1-to-string (symbol-value func))
1293 " / "
1294 (prin1-to-string (default-value func)))
1295 (concat
1296 "Value: "
1297 (prin1-to-string (symbol-value func))))))
1298 (t ; unexpected
1299 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001300 (princ (format "\n-> %s:\t%s\t%s\n\n"
1301 (if (equal funckind "c") "Command" "Variable")
1302 funcname keys))
1303 (princ funcdoc)
1304 (terpri)
1305 (setq start end))
1306 (princ (substitute-command-keys (substring str start))))
1307 (print-help-return-message)))
1308
1309(defun py-describe-mode ()
1310 "Dump long form of Python-mode docs."
1311 (interactive)
1312 (py-dump-help-string "Major mode for editing Python files.
1313Knows about Python indentation, tokens, comments and continuation lines.
1314Paragraphs are separated by blank lines only.
1315
1316Major sections below begin with the string `@'; specific function and
1317variable docs begin with `->'.
1318
1319@EXECUTING PYTHON CODE
1320
1321\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1322\\[py-execute-region]\tsends the current region
1323\\[py-shell]\tstarts a Python interpreter window; this will be used by
1324\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1325%c:py-execute-buffer
1326%c:py-execute-region
1327%c:py-shell
1328
1329@VARIABLES
1330
1331py-indent-offset\tindentation increment
1332py-block-comment-prefix\tcomment string used by py-comment-region
1333
1334py-python-command\tshell command to invoke Python interpreter
1335py-scroll-process-buffer\talways scroll Python process buffer
1336py-temp-directory\tdirectory used for temp files (if needed)
1337
1338py-beep-if-tab-change\tring the bell if tab-width is changed
1339%v:py-indent-offset
1340%v:py-block-comment-prefix
1341%v:py-python-command
1342%v:py-scroll-process-buffer
1343%v:py-temp-directory
1344%v:py-beep-if-tab-change
1345
1346@KINDS OF LINES
1347
1348Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001349preceding line ends with a backslash that's not part of a comment, or
1350the paren/bracket/brace nesting level at the start of the line is
1351non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
1353An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001354possibly blanks or tabs), a `comment line' (leftmost non-blank
1355character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356
1357Comment Lines
1358
1359Although all comment lines are treated alike by Python, Python mode
1360recognizes two kinds that act differently with respect to indentation.
1361
1362An `indenting comment line' is a comment line with a blank, tab or
1363nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001364treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365indenting comment line will be indented like the comment line. All
1366other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001367following the initial `#') are `non-indenting comment lines', and
1368their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
1370Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371whenever possible. Non-indenting comment lines are useful in cases
1372like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
1374\ta = b # a very wordy single-line comment that ends up being
1375\t #... continued onto another line
1376
1377\tif a == b:
1378##\t\tprint 'panic!' # old code we've `commented out'
1379\t\treturn a
1380
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381Since the `#...' and `##' comment lines have a non-whitespace
1382character following the initial `#', Python mode ignores them when
1383computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001384
1385Continuation Lines and Statements
1386
1387The Python-mode commands generally work on statements instead of on
1388individual lines, where a `statement' is a comment or blank line, or a
1389code line and all of its following continuation lines (if any)
1390considered as a single logical unit. The commands in this mode
1391generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392statement containing point, even if point happens to be in the middle
1393of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001394
1395
1396@INDENTATION
1397
1398Primarily for entering new code:
1399\t\\[indent-for-tab-command]\t indent line appropriately
1400\t\\[py-newline-and-indent]\t insert newline, then indent
1401\t\\[py-delete-char]\t reduce indentation, or delete single character
1402
1403Primarily for reindenting existing code:
1404\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1405\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1406
1407\t\\[py-indent-region]\t reindent region to match its context
1408\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1409\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1410
1411Unlike most programming languages, Python uses indentation, and only
1412indentation, to specify block structure. Hence the indentation supplied
1413automatically by Python-mode is just an educated guess: only you know
1414the block structure you intend, so only you can supply correct
1415indentation.
1416
1417The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1418the indentation of preceding statements. E.g., assuming
1419py-indent-offset is 4, after you enter
1420\tif a > 0: \\[py-newline-and-indent]
1421the cursor will be moved to the position of the `_' (_ is not a
1422character in the file, it's just used here to indicate the location of
1423the cursor):
1424\tif a > 0:
1425\t _
1426If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1427to
1428\tif a > 0:
1429\t c = d
1430\t _
1431Python-mode cannot know whether that's what you intended, or whether
1432\tif a > 0:
1433\t c = d
1434\t_
1435was your intent. In general, Python-mode either reproduces the
1436indentation of the (closest code or indenting-comment) preceding
1437statement, or adds an extra py-indent-offset blanks if the preceding
1438statement has `:' as its last significant (non-whitespace and non-
1439comment) character. If the suggested indentation is too much, use
1440\\[py-delete-char] to reduce it.
1441
1442Continuation lines are given extra indentation. If you don't like the
1443suggested indentation, change it to something you do like, and Python-
1444mode will strive to indent later lines of the statement in the same way.
1445
1446If a line is a continuation line by virtue of being in an unclosed
1447paren/bracket/brace structure (`list', for short), the suggested
1448indentation depends on whether the current line contains the first item
1449in the list. If it does, it's indented py-indent-offset columns beyond
1450the indentation of the line containing the open bracket. If you don't
1451like that, change it by hand. The remaining items in the list will mimic
1452whatever indentation you give to the first item.
1453
1454If a line is a continuation line because the line preceding it ends with
1455a backslash, the third and following lines of the statement inherit their
1456indentation from the line preceding them. The indentation of the second
1457line in the statement depends on the form of the first (base) line: if
1458the base line is an assignment statement with anything more interesting
1459than the backslash following the leftmost assigning `=', the second line
1460is indented two columns beyond that `='. Else it's indented to two
1461columns beyond the leftmost solid chunk of non-whitespace characters on
1462the base line.
1463
1464Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1465repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1466structure you intend.
1467%c:indent-for-tab-command
1468%c:py-newline-and-indent
1469%c:py-delete-char
1470
1471
1472The next function may be handy when editing code you didn't write:
1473%c:py-guess-indent-offset
1474
1475
1476The remaining `indent' functions apply to a region of Python code. They
1477assume the block structure (equals indentation, in Python) of the region
1478is correct, and alter the indentation in various ways while preserving
1479the block structure:
1480%c:py-indent-region
1481%c:py-shift-region-left
1482%c:py-shift-region-right
1483
1484@MARKING & MANIPULATING REGIONS OF CODE
1485
1486\\[py-mark-block]\t mark block of lines
1487\\[mark-python-def-or-class]\t mark smallest enclosing def
1488\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1489\\[py-comment-region]\t comment out region of code
1490\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1491%c:py-mark-block
1492%c:mark-python-def-or-class
1493%c:py-comment-region
1494
1495@MOVING POINT
1496
1497\\[py-previous-statement]\t move to statement preceding point
1498\\[py-next-statement]\t move to statement following point
1499\\[py-goto-block-up]\t move up to start of current block
1500\\[beginning-of-python-def-or-class]\t move to start of def
1501\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1502\\[end-of-python-def-or-class]\t move to end of def
1503\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1504
1505The first two move to one statement beyond the statement that contains
1506point. A numeric prefix argument tells them to move that many
1507statements instead. Blank lines, comment lines, and continuation lines
1508do not count as `statements' for these commands. So, e.g., you can go
1509to the first code statement in a file by entering
1510\t\\[beginning-of-buffer]\t to move to the top of the file
1511\t\\[py-next-statement]\t to skip over initial comments and blank lines
1512Or do `\\[py-previous-statement]' with a huge prefix argument.
1513%c:py-previous-statement
1514%c:py-next-statement
1515%c:py-goto-block-up
1516%c:beginning-of-python-def-or-class
1517%c:end-of-python-def-or-class
1518
1519@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1520
1521`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1522
1523`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1524overall class and def structure of a module.
1525
1526`\\[back-to-indentation]' moves point to a line's first non-blank character.
1527
1528`\\[indent-relative]' is handy for creating odd indentation.
1529
1530@OTHER EMACS HINTS
1531
1532If you don't like the default value of a variable, change its value to
1533whatever you do like by putting a `setq' line in your .emacs file.
1534E.g., to set the indentation increment to 4, put this line in your
1535.emacs:
1536\t(setq py-indent-offset 4)
1537To see the value of a variable, do `\\[describe-variable]' and enter the variable
1538name at the prompt.
1539
1540When entering a key sequence like `C-c C-n', it is not necessary to
1541release the CONTROL key after doing the `C-c' part -- it suffices to
1542press the CONTROL key, press and release `c' (while still holding down
1543CONTROL), press and release `n' (while still holding down CONTROL), &
1544then release CONTROL.
1545
1546Entering Python mode calls with no arguments the value of the variable
1547`python-mode-hook', if that value exists and is not nil; for backward
1548compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1549the Elisp manual for details.
1550
1551Obscure: When python-mode is first loaded, it looks for all bindings
1552to newline-and-indent in the global keymap, and shadows them with
1553local bindings to py-newline-and-indent."))
1554
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001555
1556;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001557(defvar py-parse-state-re
1558 (concat
1559 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1560 "\\|"
1561 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001562
Barry Warsaw7ae77681994-12-12 20:38:05 +00001563;; returns the parse state at point (see parse-partial-sexp docs)
1564(defun py-parse-state ()
1565 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001566 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567 ;; back up to the first preceding line (if any; else start of
1568 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001569 ;; whitespace and non-comment character. These are good places
1570 ;; to start parsing to see whether where we started is at a
1571 ;; non-zero nesting level. It may be slow for people who write
1572 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573 (re-search-backward py-parse-state-re nil 'move)
1574 (beginning-of-line)
1575 (parse-partial-sexp (point) here))))
1576
1577;; if point is at a non-zero nesting level, returns the number of the
1578;; character that opens the smallest enclosing unclosed list; else
1579;; returns nil.
1580(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001581 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001582 (if (zerop (car status))
1583 nil ; not in a nest
1584 (car (cdr status))))) ; char# of open bracket
1585
1586;; t iff preceding line ends with backslash that's not in a comment
1587(defun py-backslash-continuation-line-p ()
1588 (save-excursion
1589 (beginning-of-line)
1590 (and
1591 ;; use a cheap test first to avoid the regexp if possible
1592 ;; use 'eq' because char-after may return nil
1593 (eq (char-after (- (point) 2)) ?\\ )
1594 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001595 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001596 (looking-at py-continued-re))))
1597
1598;; t iff current line is a continuation line
1599(defun py-continuation-line-p ()
1600 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001601 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001602 (or (py-backslash-continuation-line-p)
1603 (py-nesting-level))))
1604
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001605;; go to initial line of current statement; usually this is the line
1606;; we're on, but if we're on the 2nd or following lines of a
1607;; continuation block, we need to go up to the first line of the
1608;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001609;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001610;; Tricky: We want to avoid quadratic-time behavior for long continued
1611;; blocks, whether of the backslash or open-bracket varieties, or a
1612;; mix of the two. The following manages to do that in the usual
1613;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001614(defun py-goto-initial-line ()
1615 (let ( open-bracket-pos )
1616 (while (py-continuation-line-p)
1617 (beginning-of-line)
1618 (if (py-backslash-continuation-line-p)
1619 (while (py-backslash-continuation-line-p)
1620 (forward-line -1))
1621 ;; else zip out of nested brackets/braces/parens
1622 (while (setq open-bracket-pos (py-nesting-level))
1623 (goto-char open-bracket-pos)))))
1624 (beginning-of-line))
1625
1626;; go to point right beyond final line of current statement; usually
1627;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628;; statement we need to skip over the continuation lines. Tricky:
1629;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001630(defun py-goto-beyond-final-line ()
1631 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001632 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001633 (while (and (py-continuation-line-p)
1634 (not (eobp)))
1635 ;; skip over the backslash flavor
1636 (while (and (py-backslash-continuation-line-p)
1637 (not (eobp)))
1638 (forward-line 1))
1639 ;; if in nest, zip to the end of the nest
1640 (setq state (py-parse-state))
1641 (if (and (not (zerop (car state)))
1642 (not (eobp)))
1643 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001644 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001645 ;; the 3rd argument should be plain 0
1646 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1647 nil state)
1648 (forward-line 1))))))
1649
1650;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001651;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001652(defun py-statement-opens-block-p ()
1653 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001654 (let ((start (point))
1655 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1656 (searching t)
1657 (answer nil)
1658 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001659 (goto-char start)
1660 (while searching
1661 ;; look for a colon with nothing after it except whitespace, and
1662 ;; maybe a comment
1663 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1664 finish t)
1665 (if (eq (point) finish) ; note: no `else' clause; just
1666 ; keep searching if we're not at
1667 ; the end yet
1668 ;; sure looks like it opens a block -- but it might
1669 ;; be in a comment
1670 (progn
1671 (setq searching nil) ; search is done either way
1672 (setq state (parse-partial-sexp start
1673 (match-beginning 0)))
1674 (setq answer (not (nth 4 state)))))
1675 ;; search failed: couldn't find another interesting colon
1676 (setq searching nil)))
1677 answer)))
1678
1679;; go to point right beyond final line of block begun by the current
1680;; line. This is the same as where py-goto-beyond-final-line goes
1681;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001682;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683(defun py-goto-beyond-block ()
1684 (if (py-statement-opens-block-p)
1685 (py-mark-block nil 'just-move)
1686 (py-goto-beyond-final-line)))
1687
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001688;; go to start of first statement (not blank or comment or
1689;; continuation line) at or preceding point. returns t if there is
1690;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001691(defun py-goto-statement-at-or-above ()
1692 (py-goto-initial-line)
1693 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001694 ;; skip back over blank & comment lines
1695 ;; note: will skip a blank or comment line that happens to be
1696 ;; a continuation line too
1697 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1698 (progn (py-goto-initial-line) t)
1699 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001700 t))
1701
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001702;; go to start of first statement (not blank or comment or
1703;; continuation line) following the statement containing point returns
1704;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001705(defun py-goto-statement-below ()
1706 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001707 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001708 (py-goto-beyond-final-line)
1709 (while (and
1710 (looking-at py-blank-or-comment-re)
1711 (not (eobp)))
1712 (forward-line 1))
1713 (if (eobp)
1714 (progn (goto-char start) nil)
1715 t)))
1716
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001717;; go to start of statement, at or preceding point, starting with
1718;; keyword KEY. Skips blank lines and non-indenting comments upward
1719;; first. If that statement starts with KEY, done, else go back to
1720;; first enclosing block starting with KEY. If successful, leaves
1721;; point at the start of the KEY line & returns t. Else leaves point
1722;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723(defun py-go-up-tree-to-keyword (key)
1724 ;; skip blanks and non-indenting #
1725 (py-goto-initial-line)
1726 (while (and
1727 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1728 (zerop (forward-line -1))) ; go back
1729 nil)
1730 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001731 (let* ((re (concat "[ \t]*" key "\\b"))
1732 (case-fold-search nil) ; let* so looking-at sees this
1733 (found (looking-at re))
1734 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001735 (while (not (or found dead))
1736 (condition-case nil ; in case no enclosing block
1737 (py-goto-block-up 'no-mark)
1738 (error (setq dead t)))
1739 (or dead (setq found (looking-at re))))
1740 (beginning-of-line)
1741 found))
1742
1743;; return string in buffer from start of indentation to end of line;
1744;; prefix "..." if leading whitespace was skipped
1745(defun py-suck-up-leading-text ()
1746 (save-excursion
1747 (back-to-indentation)
1748 (concat
1749 (if (bolp) "" "...")
1750 (buffer-substring (point) (progn (end-of-line) (point))))))
1751
1752;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1753;; as a Lisp symbol; return nil if none
1754(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1757 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1758 nil)))
1759
1760(defun py-make-temp-name ()
1761 (make-temp-name
1762 (concat (file-name-as-directory py-temp-directory) "python")))
1763
1764(defun py-delete-file-silently (fname)
1765 (condition-case nil
1766 (delete-file fname)
1767 (error nil)))
1768
1769(defun py-kill-emacs-hook ()
1770 ;; delete our temp files
1771 (while py-file-queue
1772 (py-delete-file-silently (car py-file-queue))
1773 (setq py-file-queue (cdr py-file-queue)))
1774 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1775 ;; run the hook we inherited, if any
1776 (and py-inherited-kill-emacs-hook
1777 (funcall py-inherited-kill-emacs-hook))))
1778
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001779;; make PROCESS's buffer visible, append STRING to it, and force
1780;; display; also make shell-mode believe the user typed this string,
1781;; so that kill-output-from-shell and show-output-from-shell work
1782;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001783(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784 (let ((cbuf (current-buffer))
1785 (pbuf (process-buffer process))
1786 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001787 (set-buffer pbuf)
1788 (goto-char (point-max))
1789 (move-marker (process-mark process) (point))
1790 (if (not py-this-is-emacs-19-p)
1791 (move-marker last-input-start (point))) ; muck w/ shell-mode
1792 (funcall (process-filter process) process string)
1793 (if (not py-this-is-emacs-19-p)
1794 (move-marker last-input-end (point))) ; muck w/ shell-mode
1795 (set-buffer cbuf))
1796 (sit-for 0))
1797
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001798(defun py-keep-region-active ()
1799 ;; do whatever is necessary to keep the region active in XEmacs.
1800 ;; Ignore byte-compiler warnings you might see. Also note that
1801 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1802 ;; require us to take explicit action.
1803 (and (boundp 'zmacs-region-stays)
1804 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001805
1806
Barry Warsaw850437a1995-03-08 21:50:28 +00001807(defconst py-version "$Revision$"
1808 "`python-mode' version number.")
1809(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1810 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811
Barry Warsaw850437a1995-03-08 21:50:28 +00001812(defun py-version ()
1813 "Echo the current version of `python-mode' in the minibuffer."
1814 (interactive)
1815 (message "Using `python-mode' version %s" py-version)
1816 (py-keep-region-active))
1817
1818;; only works under Emacs 19
1819;(eval-when-compile
1820; (require 'reporter))
1821
1822(defun py-submit-bug-report (enhancement-p)
1823 "Submit via mail a bug report on `python-mode'.
1824With \\[universal-argument] just submit an enhancement request."
1825 (interactive
1826 (list (not (y-or-n-p
1827 "Is this a bug report? (hit `n' to send other comments) "))))
1828 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1829 (require 'reporter)
1830 (reporter-submit-bug-report
1831 py-help-address ;address
1832 "python-mode" ;pkgname
1833 ;; varlist
1834 (if enhancement-p nil
1835 '(py-python-command
1836 py-indent-offset
1837 py-block-comment-prefix
1838 py-scroll-process-buffer
1839 py-temp-directory
1840 py-beep-if-tab-change))
1841 nil ;pre-hooks
1842 nil ;post-hooks
1843 "Dear Barry,") ;salutation
1844 (if enhancement-p nil
1845 (set-mark (point))
1846 (insert
1847"Please replace this text with a sufficiently large code sample\n\
1848and an exact recipe so that I can reproduce your problem. Failure\n\
1849to do so may mean a greater delay in fixing your bug.\n\n")
1850 (exchange-point-and-mark)
1851 (py-keep-region-active))))
1852
1853
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854;; arrange to kill temp files when Emacs exists
1855(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1856 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1857 ;; have to trust that other people are as respectful of our hook
1858 ;; fiddling as we are of theirs
1859 (if (boundp 'py-inherited-kill-emacs-hook)
1860 ;; we were loaded before -- trust others not to have screwed us
1861 ;; in the meantime (no choice, really)
1862 nil
1863 ;; else arrange for our hook to run theirs
1864 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1865 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1866
1867
1868
1869(provide 'python-mode)
1870;;; python-mode.el ends here