blob: cdba45a38712f5d95a05385dfe4168090330f638 [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
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
11;; Keywords: python editing language major-mode
12
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
22;; by Tim Peters <tim@ksr.com> after an original idea by Michael
23;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
Barry Warsawcfec3591995-03-10 15:58:16 +000024;; have undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
27;; line with GNU Emacs Lisp coding standards. But all in all, the
28;; mode works exceedingly well.
29
30;; The following statements, placed in your .emacs file or
31;; site-init.el, will cause this file to be autoloaded, and
32;; python-mode invoked, when visiting .py files (assuming this file is
33;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000034;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000035;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;; (setq auto-mode-alist
37;; (cons '("\\.py$" . python-mode) auto-mode-alist))
38
Barry Warsaw7b0f5681995-03-08 21:33:04 +000039;; Here's a brief to do list:
40;;
41;; 1. Better integration with gud-mode for debugging.
42;; 2. Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw7ae77681994-12-12 20:38:05 +000043
Barry Warsaw7b0f5681995-03-08 21:33:04 +000044;; If you can think of more things you'd like to see, drop me a line.
45;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
46;;
47;; Note that I only test things on XEmacs (currently 19.11). If you
48;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
49;; patches.
Barry Warsaw7ae77681994-12-12 20:38:05 +000050
Barry Warsaw7b0f5681995-03-08 21:33:04 +000051;; LCD Archive Entry:
52;; python-mode|Barry A. Warsaw|bwarsaw@cnri.reston.va.us
53;; |Major mode for editing Python programs
54;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000055
Barry Warsaw7b0f5681995-03-08 21:33:04 +000056;;; Code:
57
58
59;; user definable variables
60;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000061
62(defvar py-python-command "python"
63 "*Shell command used to start Python interpreter.")
64
65(defvar py-indent-offset 8 ; argue with Guido <grin>
66 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000067Note that `\\[py-guess-indent-offset]' can usually guess a good value
68when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000069
70(defvar py-block-comment-prefix "##"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000071 "*String used by `py-comment-region' to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000072This should follow the convention for non-indenting comment lines so
73that the indentation commands won't get confused (i.e., the string
74should be of the form `#x...' where `x' is not a blank or a tab, and
75`...' is arbitrary).")
76
77(defvar py-scroll-process-buffer t
78 "*Scroll Python process buffer as output arrives.
79If nil, the Python process buffer acts, with respect to scrolling, like
80Shell-mode buffers normally act. This is surprisingly complicated and
81so won't be explained here; in fact, you can't get the whole story
82without studying the Emacs C code.
83
84If non-nil, the behavior is different in two respects (which are
85slightly inaccurate in the interest of brevity):
86
87 - If the buffer is in a window, and you left point at its end, the
88 window will scroll as new output arrives, and point will move to the
89 buffer's end, even if the window is not the selected window (that
90 being the one the cursor is in). The usual behavior for shell-mode
91 windows is not to scroll, and to leave point where it was, if the
92 buffer is in a window other than the selected window.
93
94 - If the buffer is not visible in any window, and you left point at
95 its end, the buffer will be popped into a window as soon as more
96 output arrives. This is handy if you have a long-running
97 computation and don't want to tie up screen area waiting for the
98 output. The usual behavior for a shell-mode buffer is to stay
99 invisible until you explicitly visit it.
100
101Note the `and if you left point at its end' clauses in both of the
102above: you can `turn off' the special behaviors while output is in
103progress, by visiting the Python buffer and moving point to anywhere
104besides the end. Then the buffer won't scroll, point will remain where
105you leave it, and if you hide the buffer it will stay hidden until you
106visit it again. You can enable and disable the special behaviors as
107often as you like, while output is in progress, by (respectively) moving
108point to, or away from, the end of the buffer.
109
110Warning: If you expect a large amount of output, you'll probably be
111happier setting this option to nil.
112
113Obscure: `End of buffer' above should really say `at or beyond the
114process mark', but if you know what that means you didn't need to be
115told <grin>.")
116
117(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000118 (let ((ok '(lambda (x)
119 (and x
120 (setq x (expand-file-name x)) ; always true
121 (file-directory-p x)
122 (file-writable-p x)
123 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000124 (or (funcall ok (getenv "TMPDIR"))
125 (funcall ok "/usr/tmp")
126 (funcall ok "/tmp")
127 (funcall ok ".")
128 (error
129 "Couldn't find a usable temp directory -- set py-temp-directory")))
130 "*Directory used for temp files created by a *Python* process.
131By default, the first directory from this list that exists and that you
132can write into: the value (if any) of the environment variable TMPDIR,
133/usr/tmp, /tmp, or the current directory.")
134
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000135(defvar py-beep-if-tab-change t
136 "*Ring the bell if tab-width is changed.
137If a comment of the form
138
139 \t# vi:set tabsize=<number>:
140
141is found before the first code line when the file is entered, and the
142current value of (the general Emacs variable) `tab-width' does not
143equal <number>, `tab-width' is set to <number>, a message saying so is
144displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
145the Emacs bell is also rung as a warning.")
146
Barry Warsaw4f005cf1995-03-08 22:02:44 +0000147(defvar python-font-lock-keywords
Barry Warsaw65bc7a71995-03-08 22:25:47 +0000148 (list
149 (cons
150 (concat
151 "\\<\\("
152 (mapconcat
153 'identity
154 '("access" "and" "break" "continue"
155 "del" "elif" "else" "except"
156 "exec" "finally" "for" "from"
157 "global" "if" "import" "in"
158 "is" "lambda" "not" "or"
159 "pass" "print" "raise" "return"
160 "try" "while" "def" "class"
161 )
162 "\\|")
163 "\\)\\>")
164 1)
165 ;; functions
166 '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
167 ;; classes
168 '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
169 )
Barry Warsawc723b751995-03-08 22:03:16 +0000170 "*Additional keywords to highlight `python-mode' buffers.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000171
172
173;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
174;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
175
176;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
177;; seems to be the standard way of checking this.
178;; BAW - This is *not* the right solution. When at all possible,
179;; instead of testing for the version of Emacs, use feature tests.
180
181(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
182(setq py-this-is-emacs-19-p
183 (and
184 (not py-this-is-lucid-emacs-p)
185 (string-match "^19\\." emacs-version)))
186
Barry Warsaw7ae77681994-12-12 20:38:05 +0000187;; have to bind py-file-queue before installing the kill-emacs hook
188(defvar py-file-queue nil
189 "Queue of Python temp files awaiting execution.
190Currently-active file is at the head of the list.")
191
192;; define a mode-specific abbrev table for those who use such things
193(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000194 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000195(define-abbrev-table 'python-mode-abbrev-table nil)
196
Barry Warsaw7ae77681994-12-12 20:38:05 +0000197(defvar python-mode-hook nil
198 "*Hook called by `python-mode'.")
199
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000200;; in previous version of python-mode.el, the hook was incorrectly
201;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000202(and (fboundp 'make-obsolete-variable)
203 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
204
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000205(defvar py-mode-map ()
206 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000207
Barry Warsaw7ae77681994-12-12 20:38:05 +0000208(if py-mode-map
209 ()
210 (setq py-mode-map (make-sparse-keymap))
211
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000212 ;; shadow global bindings for newline-and-indent w/ the py- version.
213 ;; BAW - this is extremely bad form, but I'm not going to change it
214 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000215 (mapcar (function (lambda (key)
216 (define-key
217 py-mode-map key 'py-newline-and-indent)))
218 (where-is-internal 'newline-and-indent))
219
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000220 ;; BAW - you could do it this way, but its not considered proper
221 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000222 (mapcar (function
223 (lambda (x)
224 (define-key py-mode-map (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000225 '(("\C-c\C-c" . py-execute-buffer)
226 ("\C-c|" . py-execute-region)
227 ("\C-c!" . py-shell)
228 ("\177" . py-delete-char)
229 ("\n" . py-newline-and-indent)
230 ("\C-c:" . py-guess-indent-offset)
231 ("\C-c\t" . py-indent-region)
232 ("\C-c<" . py-shift-region-left)
233 ("\C-c>" . py-shift-region-right)
234 ("\C-c\C-n" . py-next-statement)
235 ("\C-c\C-p" . py-previous-statement)
236 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000237 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000238 ("\C-c#" . py-comment-region)
239 ("\C-c?" . py-describe-mode)
240 ("\C-c\C-hm" . py-describe-mode)
241 ("\e\C-a" . beginning-of-python-def-or-class)
242 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000243 ( "\e\C-h" . mark-python-def-or-class)))
244 ;; should do all keybindings this way
245 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
246 (define-key py-mode-map "\C-c\C-v" 'py-version)
247 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000248
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000249(defvar py-mode-syntax-table nil
250 "Syntax table used in `python-mode' buffers.")
251
Barry Warsaw7ae77681994-12-12 20:38:05 +0000252(if py-mode-syntax-table
253 ()
254 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000255 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000256 (mapcar (function
257 (lambda (x) (modify-syntax-entry
258 (car x) (cdr x) py-mode-syntax-table)))
259 '(( ?\( . "()" ) ( ?\) . ")(" )
260 ( ?\[ . "(]" ) ( ?\] . ")[" )
261 ( ?\{ . "(}" ) ( ?\} . "){" )
262 ;; fix operator symbols misassigned in the std table
263 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
264 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
265 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
266 ( ?\> . "." ) ( ?\| . "." )
267 ( ?\_ . "w" ) ; underscore is legit in names
268 ( ?\' . "\"") ; single quote is string quote
269 ( ?\" . "\"" ) ; double quote is string quote too
270 ( ?\` . "$") ; backquote is open and close paren
271 ( ?\# . "<") ; hash starts comment
272 ( ?\n . ">")))) ; newline ends comment
273
274(defconst py-stringlit-re
275 (concat
276 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
277 "\\|" ; or
278 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000279 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000280
281;; this is tricky because a trailing backslash does not mean
282;; continuation if it's in a comment
283(defconst py-continued-re
284 (concat
285 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
286 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000287 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000288
289(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000290 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000291
Barry Warsaw7ae77681994-12-12 20:38:05 +0000292
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000293
294;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000295(defun python-mode ()
296 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000297To submit a problem report, enter `\\[py-submit-bug-report]' from a
298`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
299documentation. To see what version of `python-mode' you are running,
300enter `\\[py-version]'.
301
302This mode knows about Python indentation, tokens, comments and
303continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000304
305COMMANDS
306\\{py-mode-map}
307VARIABLES
308
309py-indent-offset\tindentation increment
310py-block-comment-prefix\tcomment string used by py-comment-region
311py-python-command\tshell command to invoke Python interpreter
312py-scroll-process-buffer\talways scroll Python process buffer
313py-temp-directory\tdirectory used for temp files (if needed)
314py-beep-if-tab-change\tring the bell if tab-width is changed"
315 (interactive)
316 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000317 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000318 (setq major-mode 'python-mode
319 mode-name "Python"
320 local-abbrev-table python-mode-abbrev-table)
321 (use-local-map py-mode-map)
322 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000323 (mapcar (function (lambda (x)
324 (make-local-variable (car x))
325 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000326 '((paragraph-separate . "^[ \t]*$")
327 (paragraph-start . "^[ \t]*$")
328 (require-final-newline . t)
329 (comment-start . "# ")
330 (comment-start-skip . "# *")
331 (comment-column . 40)
332 (indent-region-function . py-indent-region)
333 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000334 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000335 ;;
336 ;; not sure where the magic comment has to be; to save time
337 ;; searching for a rarity, we give up if it's not found prior to the
338 ;; first executable statement.
339 ;;
340 ;; BAW - on first glance, this seems like complete hackery. Why was
341 ;; this necessary, and is it still necessary?
342 (let ((case-fold-search nil)
343 (start (point))
344 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000345 (if (re-search-forward
346 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
347 (prog2 (py-next-statement 1) (point) (goto-char 1))
348 t)
349 (progn
350 (setq new-tab-width
351 (string-to-int
352 (buffer-substring (match-beginning 1) (match-end 1))))
353 (if (= tab-width new-tab-width)
354 nil
355 (setq tab-width new-tab-width)
356 (message "Caution: tab-width changed to %d" new-tab-width)
357 (if py-beep-if-tab-change (beep)))))
358 (goto-char start))
359
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000360 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000361 (if python-mode-hook
362 (run-hooks 'python-mode-hook)
363 (run-hooks 'py-mode-hook)))
364
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000365
Barry Warsaw7ae77681994-12-12 20:38:05 +0000366;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000367(defun py-shell ()
368 "Start an interactive Python interpreter in another window.
369This is like Shell mode, except that Python is running in the window
370instead of a shell. See the `Interactive Shell' and `Shell Mode'
371sections of the Emacs manual for details, especially for the key
372bindings active in the `*Python*' buffer.
373
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000374See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000375behavior in the process window.
376
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000377Warning: Don't use an interactive Python if you change sys.ps1 or
378sys.ps2 from their default values, or if you're running code that
379prints `>>> ' or `... ' at the start of a line. `python-mode' can't
380distinguish your output from Python's output, and assumes that `>>> '
381at the start of a line is a prompt from Python. Similarly, the Emacs
382Shell mode code assumes that both `>>> ' and `... ' at the start of a
383line are Python prompts. Bad things can happen if you fool either
384mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000385
386Warning: If you do any editing *in* the process buffer *while* the
387buffer is accepting output from Python, do NOT attempt to `undo' the
388changes. Some of the output (nowhere near the parts you changed!) may
389be lost if you do. This appears to be an Emacs bug, an unfortunate
390interaction between undo and process filters; the same problem exists in
391non-Python process buffers using the default (Emacs-supplied) process
392filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393 ;; BAW - should undo be disabled in the python process buffer, if
394 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000395 (interactive)
396 (if py-this-is-emacs-19-p
397 (progn
398 (require 'comint)
399 (switch-to-buffer-other-window
400 (make-comint "Python" py-python-command)))
401 (progn
402 (require 'shell)
403 (switch-to-buffer-other-window
404 (make-shell "Python" py-python-command))))
405 (make-local-variable 'shell-prompt-pattern)
406 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
407 (set-process-filter (get-buffer-process (current-buffer))
408 'py-process-filter)
409 (set-syntax-table py-mode-syntax-table))
410
411(defun py-execute-region (start end)
412 "Send the region between START and END to a Python interpreter.
413If there is a *Python* process it is used.
414
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000415Hint: If you want to execute part of a Python file several times
416\(e.g., perhaps you're developing a function and want to flesh it out
417a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
418the region of interest, and send the code to a *Python* process via
419`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000420
421Following are subtleties to note when using a *Python* process:
422
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000423If a *Python* process is used, the region is copied into a temporary
424file (in directory `py-temp-directory'), and an `execfile' command is
425sent to Python naming that file. If you send regions faster than
426Python can execute them, `python-mode' will save them into distinct
427temp files, and execute the next one in the queue the next time it
428sees a `>>> ' prompt from Python. Each time this happens, the process
429buffer is popped into a window (if it's not already in some window) so
430you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000431
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000432 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000433
434is inserted at the end.
435
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000436Caution: No more than 26 regions can be pending at any given time.
437This limit is (indirectly) inherited from libc's mktemp(3).
438`python-mode' does not try to protect you from exceeding the limit.
439It's extremely unlikely that you'll get anywhere close to the limit in
440practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000441
442See the `\\[py-shell]' docs for additional warnings."
443 (interactive "r")
444 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000445 (let ((pyproc (get-process "Python"))
446 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000447 (if (null pyproc)
448 (shell-command-on-region start end py-python-command)
449 ;; else feed it thru a temp file
450 (setq fname (py-make-temp-name))
451 (write-region start end fname nil 'no-msg)
452 (setq py-file-queue (append py-file-queue (list fname)))
453 (if (cdr py-file-queue)
454 (message "File %s queued for execution" fname)
455 ;; else
456 (py-execute-file pyproc fname)))))
457
458(defun py-execute-file (pyproc fname)
459 (py-append-to-process-buffer
460 pyproc
461 (format "## working on region in file %s ...\n" fname))
462 (process-send-string pyproc (format "execfile('%s')\n" fname)))
463
464(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000465 (let ((curbuf (current-buffer))
466 (pbuf (process-buffer pyproc))
467 (pmark (process-mark pyproc))
468 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000469
470 ;; make sure we switch to a different buffer at least once. if we
471 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000472 ;; window, and point is before the end, and lots of output is
473 ;; coming at a fast pace, then (a) simple cursor-movement commands
474 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
475 ;; to have a visible effect (the window just doesn't get updated,
476 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
477 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000478 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000479 ;; #b makes no sense to me at all. #a almost makes sense: unless
480 ;; we actually change buffers, set_buffer_internal in buffer.c
481 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
482 ;; seems to make the Emacs command loop reluctant to update the
483 ;; display. Perhaps the default process filter in process.c's
484 ;; read_process_output has update_mode_lines++ for a similar
485 ;; reason? beats me ...
486
487 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000488 (if (eq curbuf pbuf) ; mysterious ugly hack
489 (set-buffer (get-buffer-create "*scratch*")))
490
491 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000492 (let* ((start (point))
493 (goback (< start pmark))
494 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000495 (goto-char pmark)
496 (insert string)
497 (move-marker pmark (point))
498 (setq file-finished
499 (and py-file-queue
500 (equal ">>> "
501 (buffer-substring
502 (prog2 (beginning-of-line) (point)
503 (goto-char pmark))
504 (point)))))
505 (if goback (goto-char start)
506 ;; else
507 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000508 (let* ((pop-up-windows t)
509 (pwin (display-buffer pbuf)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000510 (set-window-point pwin (point))))))
511 (set-buffer curbuf)
512 (if file-finished
513 (progn
514 (py-delete-file-silently (car py-file-queue))
515 (setq py-file-queue (cdr py-file-queue))
516 (if py-file-queue
517 (py-execute-file pyproc (car py-file-queue)))))))
518
519(defun py-execute-buffer ()
520 "Send the contents of the buffer to a Python interpreter.
521If there is a *Python* process buffer it is used. If a clipping
522restriction is in effect, only the accessible portion of the buffer is
523sent. A trailing newline will be supplied if needed.
524
525See the `\\[py-execute-region]' docs for an account of some subtleties."
526 (interactive)
527 (py-execute-region (point-min) (point-max)))
528
529
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000530
531;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000532(defun py-delete-char ()
533 "Reduce indentation or delete character.
534If point is at the leftmost column, deletes the preceding newline.
535
536Else if point is at the leftmost non-blank character of a line that is
537neither a continuation line nor a non-indenting comment line, or if
538point is at the end of a blank line, reduces the indentation to match
539that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000540opened the block is displayed in the echo area to help you keep track
541of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542
543Else the preceding character is deleted, converting a tab to spaces if
544needed so that only a single column position is deleted."
545 (interactive "*")
546 (if (or (/= (current-indentation) (current-column))
547 (bolp)
548 (py-continuation-line-p)
549 (looking-at "#[^ \t\n]")) ; non-indenting #
550 (backward-delete-char-untabify 1)
551 ;; else indent the same as the colon line that opened the block
552
553 ;; force non-blank so py-goto-block-up doesn't ignore it
554 (insert-char ?* 1)
555 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000556 (let ((base-indent 0) ; indentation of base line
557 (base-text "") ; and text of base line
558 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000559 (condition-case nil ; in case no enclosing block
560 (save-excursion
561 (py-goto-block-up 'no-mark)
562 (setq base-indent (current-indentation)
563 base-text (py-suck-up-leading-text)
564 base-found-p t))
565 (error nil))
566 (delete-char 1) ; toss the dummy character
567 (delete-horizontal-space)
568 (indent-to base-indent)
569 (if base-found-p
570 (message "Closes block: %s" base-text)))))
571
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000572;; required for pending-del and delsel modes
573(put 'py-delete-char 'delete-selection 'supersede)
574(put 'py-delete-char 'pending-delete 'supersede)
575
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576(defun py-indent-line ()
577 "Fix the indentation of the current line according to Python rules."
578 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000579 (let* ((ci (current-indentation))
580 (move-to-indentation-p (<= (current-column) ci))
581 (need (py-compute-indentation)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000582 (if (/= ci need)
583 (save-excursion
584 (beginning-of-line)
585 (delete-horizontal-space)
586 (indent-to need)))
587 (if move-to-indentation-p (back-to-indentation))))
588
589(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000590 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000591This is just `strives to' because correct indentation can't be computed
592from scratch for Python code. In general, deletes the whitespace before
593point, inserts a newline, and takes an educated guess as to how you want
594the new line indented."
595 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000596 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000597 (if (< ci (current-column)) ; if point beyond indentation
598 (newline-and-indent)
599 ;; else try to act like newline-and-indent "normally" acts
600 (beginning-of-line)
601 (insert-char ?\n 1)
602 (move-to-column ci))))
603
604(defun py-compute-indentation ()
605 (save-excursion
606 (beginning-of-line)
607 (cond
608 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000609 ((py-continuation-line-p)
610 (let ((startpos (point))
611 (open-bracket-pos (py-nesting-level))
612 endpos searching found)
613 (if open-bracket-pos
614 (progn
615 ;; align with first item in list; else a normal
616 ;; indent beyond the line with the open bracket
617 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
618 ;; is the first list item on the same line?
619 (skip-chars-forward " \t")
620 (if (null (memq (following-char) '(?\n ?# ?\\)))
621 ; yes, so line up with it
622 (current-column)
623 ;; first list item on another line, or doesn't exist yet
624 (forward-line 1)
625 (while (and (< (point) startpos)
626 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
627 (forward-line 1))
628 (if (< (point) startpos)
629 ;; again mimic the first list item
630 (current-indentation)
631 ;; else they're about to enter the first item
632 (goto-char open-bracket-pos)
633 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000634
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000635 ;; else on backslash continuation line
636 (forward-line -1)
637 (if (py-continuation-line-p) ; on at least 3rd line in block
638 (current-indentation) ; so just continue the pattern
639 ;; else started on 2nd line in block, so indent more.
640 ;; if base line is an assignment with a start on a RHS,
641 ;; indent to 2 beyond the leftmost "="; else skip first
642 ;; chunk of non-whitespace characters on base line, + 1 more
643 ;; column
644 (end-of-line)
645 (setq endpos (point) searching t)
646 (back-to-indentation)
647 (setq startpos (point))
648 ;; look at all "=" from left to right, stopping at first
649 ;; one not nested in a list or string
650 (while searching
651 (skip-chars-forward "^=" endpos)
652 (if (= (point) endpos)
653 (setq searching nil)
654 (forward-char 1)
655 (setq state (parse-partial-sexp startpos (point)))
656 (if (and (zerop (car state)) ; not in a bracket
657 (null (nth 3 state))) ; & not in a string
658 (progn
659 (setq searching nil) ; done searching in any case
660 (setq found
661 (not (or
662 (eq (following-char) ?=)
663 (memq (char-after (- (point) 2))
664 '(?< ?> ?!)))))))))
665 (if (or (not found) ; not an assignment
666 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
667 (progn
668 (goto-char startpos)
669 (skip-chars-forward "^ \t\n")))
670 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000671
672 ;; not on a continuation line
673
674 ;; if at start of restriction, or on a non-indenting comment line,
675 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000676 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
677 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000678
679 ;; else indentation based on that of the statement that precedes
680 ;; us; use the first line of that statement to establish the base,
681 ;; in case the user forced a non-std indentation for the
682 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683 (t
684 ;; skip back over blank & non-indenting comment lines
685 ;; note: will skip a blank or non-indenting comment line that
686 ;; happens to be a continuation line too
687 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
688 nil 'move)
689 ;; if we landed inside a string, go to the beginning of that
690 ;; string. this handles triple quoted, multi-line spanning
691 ;; strings.
692 (let ((state (parse-partial-sexp
693 (save-excursion (beginning-of-python-def-or-class)
694 (point))
695 (point))))
696 (if (nth 3 state)
697 (goto-char (nth 2 state))))
698 (py-goto-initial-line)
699 (if (py-statement-opens-block-p)
700 (+ (current-indentation) py-indent-offset)
701 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000702
703(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000704 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000705By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000706`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000707Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000709their own buffer-local copy), both those currently existing and those
710created later in the Emacs session.
711
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000712Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000713There's no excuse for such foolishness, but sometimes you have to deal
714with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000715`py-indent-offset' to what it thinks it was when they created the
716mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000717
718Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000719looking for a line that opens a block of code. `py-indent-offset' is
720set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000721statement following it. If the search doesn't succeed going forward,
722it's tried again going backward."
723 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000724 (let (new-value
725 (start (point))
726 restart
727 (found nil)
728 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000729 (py-goto-initial-line)
730 (while (not (or found (eobp)))
731 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
732 (progn
733 (setq restart (point))
734 (py-goto-initial-line)
735 (if (py-statement-opens-block-p)
736 (setq found t)
737 (goto-char restart)))))
738 (if found
739 ()
740 (goto-char start)
741 (py-goto-initial-line)
742 (while (not (or found (bobp)))
743 (setq found
744 (and
745 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
746 (or (py-goto-initial-line) t) ; always true -- side effect
747 (py-statement-opens-block-p)))))
748 (setq colon-indent (current-indentation)
749 found (and found (zerop (py-next-statement 1)))
750 new-value (- (current-indentation) colon-indent))
751 (goto-char start)
752 (if found
753 (progn
754 (funcall (if global 'kill-local-variable 'make-local-variable)
755 'py-indent-offset)
756 (setq py-indent-offset new-value)
757 (message "%s value of py-indent-offset set to %d"
758 (if global "Global" "Local")
759 py-indent-offset))
760 (error "Sorry, couldn't guess a value for py-indent-offset"))))
761
762(defun py-shift-region (start end count)
763 (save-excursion
764 (goto-char end) (beginning-of-line) (setq end (point))
765 (goto-char start) (beginning-of-line) (setq start (point))
766 (indent-rigidly start end count)))
767
768(defun py-shift-region-left (start end &optional count)
769 "Shift region of Python code to the left.
770The lines from the line containing the start of the current region up
771to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000772shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000773
774If a prefix argument is given, the region is instead shifted by that
775many columns."
776 (interactive "*r\nP") ; region; raw prefix arg
777 (py-shift-region start end
778 (- (prefix-numeric-value
779 (or count py-indent-offset)))))
780
781(defun py-shift-region-right (start end &optional count)
782 "Shift region of Python code to the right.
783The lines from the line containing the start of the current region up
784to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000785shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000786
787If a prefix argument is given, the region is instead shifted by that
788many columns."
789 (interactive "*r\nP") ; region; raw prefix arg
790 (py-shift-region start end (prefix-numeric-value
791 (or count py-indent-offset))))
792
793(defun py-indent-region (start end &optional indent-offset)
794 "Reindent a region of Python code.
795The lines from the line containing the start of the current region up
796to (but not including) the line containing the end of the region are
797reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000798character in the first column, the first line is left alone and the
799rest of the region is reindented with respect to it. Else the entire
800region is reindented with respect to the (closest code or
801indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000802
803This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000804control structures are introduced or removed, or to reformat code
805using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000806
807If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000808the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000809used.
810
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000811Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812is called! This function does not compute proper indentation from
813scratch (that's impossible in Python), it merely adjusts the existing
814indentation to be correct in context.
815
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000816Warning: This function really has no idea what to do with
817non-indenting comment lines, and shifts them as if they were indenting
818comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000819
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000820Special cases: whitespace is deleted from blank lines; continuation
821lines are shifted by the same amount their initial line was shifted,
822in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000823initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000824 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000825 (save-excursion
826 (goto-char end) (beginning-of-line) (setq end (point-marker))
827 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000828 (let ((py-indent-offset (prefix-numeric-value
829 (or indent-offset py-indent-offset)))
830 (indents '(-1)) ; stack of active indent levels
831 (target-column 0) ; column to which to indent
832 (base-shifted-by 0) ; amount last base line was shifted
833 (indent-base (if (looking-at "[ \t\n]")
834 (py-compute-indentation)
835 0))
836 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000837 (while (< (point) end)
838 (setq ci (current-indentation))
839 ;; figure out appropriate target column
840 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000841 ((or (eq (following-char) ?#) ; comment in column 1
842 (looking-at "[ \t]*$")) ; entirely blank
843 (setq target-column 0))
844 ((py-continuation-line-p) ; shift relative to base line
845 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000846 (t ; new base line
847 (if (> ci (car indents)) ; going deeper; push it
848 (setq indents (cons ci indents))
849 ;; else we should have seen this indent before
850 (setq indents (memq ci indents)) ; pop deeper indents
851 (if (null indents)
852 (error "Bad indentation in region, at line %d"
853 (save-restriction
854 (widen)
855 (1+ (count-lines 1 (point)))))))
856 (setq target-column (+ indent-base
857 (* py-indent-offset
858 (- (length indents) 2))))
859 (setq base-shifted-by (- target-column ci))))
860 ;; shift as needed
861 (if (/= ci target-column)
862 (progn
863 (delete-horizontal-space)
864 (indent-to target-column)))
865 (forward-line 1))))
866 (set-marker end nil))
867
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000868
869;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000870(defun py-previous-statement (count)
871 "Go to the start of previous Python statement.
872If the statement at point is the i'th Python statement, goes to the
873start of statement i-COUNT. If there is no such statement, goes to the
874first statement. Returns count of statements left to move.
875`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000876 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877 (if (< count 0) (py-next-statement (- count))
878 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000879 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000880 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000881 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882 (> count 0)
883 (zerop (forward-line -1))
884 (py-goto-statement-at-or-above))
885 (setq count (1- count)))
886 (if (> count 0) (goto-char start)))
887 count))
888
889(defun py-next-statement (count)
890 "Go to the start of next Python statement.
891If the statement at point is the i'th Python statement, goes to the
892start of statement i+COUNT. If there is no such statement, goes to the
893last statement. Returns count of statements left to move. `Statements'
894do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000895 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896 (if (< count 0) (py-previous-statement (- count))
897 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000898 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000899 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000900 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901 (> count 0)
902 (py-goto-statement-below))
903 (setq count (1- count)))
904 (if (> count 0) (goto-char start)))
905 count))
906
907(defun py-goto-block-up (&optional nomark)
908 "Move up to start of current block.
909Go to the statement that starts the smallest enclosing block; roughly
910speaking, this will be the closest preceding statement that ends with a
911colon and is indented less than the statement you started on. If
912successful, also sets the mark to the starting point.
913
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000914`\\[py-mark-block]' can be used afterward to mark the whole code
915block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916
917If called from a program, the mark will not be set if optional argument
918NOMARK is not nil."
919 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920 (let ((start (point))
921 (found nil)
922 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000923 (py-goto-initial-line)
924 ;; if on blank or non-indenting comment line, use the preceding stmt
925 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
926 (progn
927 (py-goto-statement-at-or-above)
928 (setq found (py-statement-opens-block-p))))
929 ;; search back for colon line indented less
930 (setq initial-indent (current-indentation))
931 (if (zerop initial-indent)
932 ;; force fast exit
933 (goto-char (point-min)))
934 (while (not (or found (bobp)))
935 (setq found
936 (and
937 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
938 (or (py-goto-initial-line) t) ; always true -- side effect
939 (< (current-indentation) initial-indent)
940 (py-statement-opens-block-p))))
941 (if found
942 (progn
943 (or nomark (push-mark start))
944 (back-to-indentation))
945 (goto-char start)
946 (error "Enclosing block not found"))))
947
948(defun beginning-of-python-def-or-class (&optional class)
949 "Move point to start of def (or class, with prefix arg).
950
951Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000952arg, looks for a `class' instead. The docs assume the `def' case;
953just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000954
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000955If point is in a def statement already, and after the `d', simply
956moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000957
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000958Else (point is not in a def statement, or at or before the `d' of a
959def statement), searches for the closest preceding def statement, and
960leaves point at its start. If no such statement can be found, leaves
961point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000962
963Returns t iff a def statement is found by these rules.
964
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000965Note that doing this command repeatedly will take you closer to the
966start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000967
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000968If you want to mark the current def/class, see
969`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000970 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000971 (let ((at-or-before-p (<= (current-column) (current-indentation)))
972 (start-of-line (progn (beginning-of-line) (point)))
973 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000974 (if (or (/= start-of-stmt start-of-line)
975 (not at-or-before-p))
976 (end-of-line)) ; OK to match on this line
977 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000978 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000979
980(defun end-of-python-def-or-class (&optional class)
981 "Move point beyond end of def (or class, with prefix arg) body.
982
983By default, looks for an appropriate `def'. If you supply a prefix arg,
984looks for a `class' instead. The docs assume the `def' case; just
985substitute `class' for `def' for the other case.
986
987If point is in a def statement already, this is the def we use.
988
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000989Else if the def found by `\\[beginning-of-python-def-or-class]'
990contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000991
992Else we search forward for the closest following def, and use that.
993
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994If a def can be found by these rules, point is moved to the start of
995the line immediately following the def block, and the position of the
996start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000997
998Else point is moved to the end of the buffer, and nil is returned.
999
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001000Note that doing this command repeatedly will take you closer to the
1001end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001002
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001003If you want to mark the current def/class, see
1004`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001006 (let ((start (progn (py-goto-initial-line) (point)))
1007 (which (if class "class" "def"))
1008 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001009 ;; move point to start of appropriate def/class
1010 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1011 (setq state 'at-beginning)
1012 ;; else see if beginning-of-python-def-or-class hits container
1013 (if (and (beginning-of-python-def-or-class class)
1014 (progn (py-goto-beyond-block)
1015 (> (point) start)))
1016 (setq state 'at-end)
1017 ;; else search forward
1018 (goto-char start)
1019 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1020 (progn (setq state 'at-beginning)
1021 (beginning-of-line)))))
1022 (cond
1023 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1024 ((eq state 'at-end) t)
1025 ((eq state 'not-found) nil)
1026 (t (error "internal error in end-of-python-def-or-class")))))
1027
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028
1029;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030(defun py-mark-block (&optional extend just-move)
1031 "Mark following block of lines. With prefix arg, mark structure.
1032Easier to use than explain. It sets the region to an `interesting'
1033block of succeeding lines. If point is on a blank line, it goes down to
1034the next non-blank line. That will be the start of the region. The end
1035of the region depends on the kind of line at the start:
1036
1037 - If a comment, the region will include all succeeding comment lines up
1038 to (but not including) the next non-comment line (if any).
1039
1040 - Else if a prefix arg is given, and the line begins one of these
1041 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001042
1043 if elif else try except finally for while def class
1044
Barry Warsaw7ae77681994-12-12 20:38:05 +00001045 the region will be set to the body of the structure, including
1046 following blocks that `belong' to it, but excluding trailing blank
1047 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001048 and all (if any) of the following `except' and `finally' blocks
1049 that belong to the `try' structure will be in the region. Ditto
1050 for if/elif/else, for/else and while/else structures, and (a bit
1051 degenerate, since they're always one-block structures) def and
1052 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001053
1054 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001055 block (see list above), and the block is not a `one-liner' (i.e.,
1056 the statement ends with a colon, not with code), the region will
1057 include all succeeding lines up to (but not including) the next
1058 code statement (if any) that's indented no more than the starting
1059 line, except that trailing blank and comment lines are excluded.
1060 E.g., if the starting line begins a multi-statement `def'
1061 structure, the region will be set to the full function definition,
1062 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001063
1064 - Else the region will include all succeeding lines up to (but not
1065 including) the next blank line, or code or indenting-comment line
1066 indented strictly less than the starting line. Trailing indenting
1067 comment lines are included in this case, but not trailing blank
1068 lines.
1069
1070A msg identifying the location of the mark is displayed in the echo
1071area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1072
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001073If called from a program, optional argument EXTEND plays the role of
1074the prefix arg, and if optional argument JUST-MOVE is not nil, just
1075moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (interactive "P") ; raw prefix arg
1077 (py-goto-initial-line)
1078 ;; skip over blank lines
1079 (while (and
1080 (looking-at "[ \t]*$") ; while blank line
1081 (not (eobp))) ; & somewhere to go
1082 (forward-line 1))
1083 (if (eobp)
1084 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 (let ((initial-pos (point))
1086 (initial-indent (current-indentation))
1087 last-pos ; position of last stmt in region
1088 (followers
1089 '((if elif else) (elif elif else) (else)
1090 (try except finally) (except except) (finally)
1091 (for else) (while else)
1092 (def) (class) ) )
1093 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094
1095 (cond
1096 ;; if comment line, suck up the following comment lines
1097 ((looking-at "[ \t]*#")
1098 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1099 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1100 (setq last-pos (point)))
1101
1102 ;; else if line is a block line and EXTEND given, suck up
1103 ;; the whole structure
1104 ((and extend
1105 (setq first-symbol (py-suck-up-first-keyword) )
1106 (assq first-symbol followers))
1107 (while (and
1108 (or (py-goto-beyond-block) t) ; side effect
1109 (forward-line -1) ; side effect
1110 (setq last-pos (point)) ; side effect
1111 (py-goto-statement-below)
1112 (= (current-indentation) initial-indent)
1113 (setq next-symbol (py-suck-up-first-keyword))
1114 (memq next-symbol (cdr (assq first-symbol followers))))
1115 (setq first-symbol next-symbol)))
1116
1117 ;; else if line *opens* a block, search for next stmt indented <=
1118 ((py-statement-opens-block-p)
1119 (while (and
1120 (setq last-pos (point)) ; always true -- side effect
1121 (py-goto-statement-below)
1122 (> (current-indentation) initial-indent))
1123 nil))
1124
1125 ;; else plain code line; stop at next blank line, or stmt or
1126 ;; indenting comment line indented <
1127 (t
1128 (while (and
1129 (setq last-pos (point)) ; always true -- side effect
1130 (or (py-goto-beyond-final-line) t)
1131 (not (looking-at "[ \t]*$")) ; stop at blank line
1132 (or
1133 (>= (current-indentation) initial-indent)
1134 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1135 nil)))
1136
1137 ;; skip to end of last stmt
1138 (goto-char last-pos)
1139 (py-goto-beyond-final-line)
1140
1141 ;; set mark & display
1142 (if just-move
1143 () ; just return
1144 (push-mark (point) 'no-msg)
1145 (forward-line -1)
1146 (message "Mark set after: %s" (py-suck-up-leading-text))
1147 (goto-char initial-pos))))
1148
1149(defun mark-python-def-or-class (&optional class)
1150 "Set region to body of def (or class, with prefix arg) enclosing point.
1151Pushes the current mark, then point, on the mark ring (all language
1152modes do this, but although it's handy it's never documented ...).
1153
1154In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001155hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1156`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001157
1158And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001159Turned out that was more confusing than useful: the `goto start' and
1160`goto end' commands are usually used to search through a file, and
1161people expect them to act a lot like `search backward' and `search
1162forward' string-search commands. But because Python `def' and `class'
1163can nest to arbitrary levels, finding the smallest def containing
1164point cannot be done via a simple backward search: the def containing
1165point may not be the closest preceding def, or even the closest
1166preceding def that's indented less. The fancy algorithm required is
1167appropriate for the usual uses of this `mark' command, but not for the
1168`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001170So the def marked by this command may not be the one either of the
1171`goto' commands find: If point is on a blank or non-indenting comment
1172line, moves back to start of the closest preceding code statement or
1173indenting comment line. If this is a `def' statement, that's the def
1174we use. Else searches for the smallest enclosing `def' block and uses
1175that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001176
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001177When an enclosing def is found: The mark is left immediately beyond
1178the last line of the def block. Point is left at the start of the
1179def, except that: if the def is preceded by a number of comment lines
1180followed by (at most) one optional blank line, point is left at the
1181start of the comments; else if the def is preceded by a blank line,
1182point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183
1184The intent is to mark the containing def/class and its associated
1185documentation, to make moving and duplicating functions and classes
1186pleasant."
1187 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001188 (let ((start (point))
1189 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190 (push-mark start)
1191 (if (not (py-go-up-tree-to-keyword which))
1192 (progn (goto-char start)
1193 (error "Enclosing %s not found" which))
1194 ;; else enclosing def/class found
1195 (setq start (point))
1196 (py-goto-beyond-block)
1197 (push-mark (point))
1198 (goto-char start)
1199 (if (zerop (forward-line -1)) ; if there is a preceding line
1200 (progn
1201 (if (looking-at "[ \t]*$") ; it's blank
1202 (setq start (point)) ; so reset start point
1203 (goto-char start)) ; else try again
1204 (if (zerop (forward-line -1))
1205 (if (looking-at "[ \t]*#") ; a comment
1206 ;; look back for non-comment line
1207 ;; tricky: note that the regexp matches a blank
1208 ;; line, cuz \n is in the 2nd character class
1209 (and
1210 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1211 (forward-line 1))
1212 ;; no comment, so go back
1213 (goto-char start))))))))
1214
1215(defun py-comment-region (start end &optional uncomment-p)
1216 "Comment out region of code; with prefix arg, uncomment region.
1217The lines from the line containing the start of the current region up
1218to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001219commented out, by inserting the string `py-block-comment-prefix' at
1220the start of each line. With a prefix arg, removes
1221`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001222 (interactive "*r\nP") ; region; raw prefix arg
1223 (goto-char end) (beginning-of-line) (setq end (point))
1224 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001225 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001226 (save-excursion
1227 (save-restriction
1228 (narrow-to-region start end)
1229 (while (not (eobp))
1230 (if uncomment-p
1231 (and (string= py-block-comment-prefix
1232 (buffer-substring
1233 (point) (+ (point) prefix-len)))
1234 (delete-char prefix-len))
1235 (insert py-block-comment-prefix))
1236 (forward-line 1))))))
1237
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001238
1239;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001240
1241;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001242;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1243;; out of the right places, along with the keys they're on & current
1244;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001245(defun py-dump-help-string (str)
1246 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001247 (let ((locals (buffer-local-variables))
1248 funckind funcname func funcdoc
1249 (start 0) mstart end
1250 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001251 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1252 (setq mstart (match-beginning 0) end (match-end 0)
1253 funckind (substring str (match-beginning 1) (match-end 1))
1254 funcname (substring str (match-beginning 2) (match-end 2))
1255 func (intern funcname))
1256 (princ (substitute-command-keys (substring str start mstart)))
1257 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001258 ((equal funckind "c") ; command
1259 (setq funcdoc (documentation func)
1260 keys (concat
1261 "Key(s): "
1262 (mapconcat 'key-description
1263 (where-is-internal func py-mode-map)
1264 ", "))))
1265 ((equal funckind "v") ; variable
1266 (setq funcdoc (substitute-command-keys
1267 (get func 'variable-documentation))
1268 keys (if (assq func locals)
1269 (concat
1270 "Local/Global values: "
1271 (prin1-to-string (symbol-value func))
1272 " / "
1273 (prin1-to-string (default-value func)))
1274 (concat
1275 "Value: "
1276 (prin1-to-string (symbol-value func))))))
1277 (t ; unexpected
1278 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001279 (princ (format "\n-> %s:\t%s\t%s\n\n"
1280 (if (equal funckind "c") "Command" "Variable")
1281 funcname keys))
1282 (princ funcdoc)
1283 (terpri)
1284 (setq start end))
1285 (princ (substitute-command-keys (substring str start))))
1286 (print-help-return-message)))
1287
1288(defun py-describe-mode ()
1289 "Dump long form of Python-mode docs."
1290 (interactive)
1291 (py-dump-help-string "Major mode for editing Python files.
1292Knows about Python indentation, tokens, comments and continuation lines.
1293Paragraphs are separated by blank lines only.
1294
1295Major sections below begin with the string `@'; specific function and
1296variable docs begin with `->'.
1297
1298@EXECUTING PYTHON CODE
1299
1300\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1301\\[py-execute-region]\tsends the current region
1302\\[py-shell]\tstarts a Python interpreter window; this will be used by
1303\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1304%c:py-execute-buffer
1305%c:py-execute-region
1306%c:py-shell
1307
1308@VARIABLES
1309
1310py-indent-offset\tindentation increment
1311py-block-comment-prefix\tcomment string used by py-comment-region
1312
1313py-python-command\tshell command to invoke Python interpreter
1314py-scroll-process-buffer\talways scroll Python process buffer
1315py-temp-directory\tdirectory used for temp files (if needed)
1316
1317py-beep-if-tab-change\tring the bell if tab-width is changed
1318%v:py-indent-offset
1319%v:py-block-comment-prefix
1320%v:py-python-command
1321%v:py-scroll-process-buffer
1322%v:py-temp-directory
1323%v:py-beep-if-tab-change
1324
1325@KINDS OF LINES
1326
1327Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001328preceding line ends with a backslash that's not part of a comment, or
1329the paren/bracket/brace nesting level at the start of the line is
1330non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001331
1332An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001333possibly blanks or tabs), a `comment line' (leftmost non-blank
1334character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001335
1336Comment Lines
1337
1338Although all comment lines are treated alike by Python, Python mode
1339recognizes two kinds that act differently with respect to indentation.
1340
1341An `indenting comment line' is a comment line with a blank, tab or
1342nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001343treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001344indenting comment line will be indented like the comment line. All
1345other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001346following the initial `#') are `non-indenting comment lines', and
1347their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001348
1349Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001350whenever possible. Non-indenting comment lines are useful in cases
1351like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
1353\ta = b # a very wordy single-line comment that ends up being
1354\t #... continued onto another line
1355
1356\tif a == b:
1357##\t\tprint 'panic!' # old code we've `commented out'
1358\t\treturn a
1359
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001360Since the `#...' and `##' comment lines have a non-whitespace
1361character following the initial `#', Python mode ignores them when
1362computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001363
1364Continuation Lines and Statements
1365
1366The Python-mode commands generally work on statements instead of on
1367individual lines, where a `statement' is a comment or blank line, or a
1368code line and all of its following continuation lines (if any)
1369considered as a single logical unit. The commands in this mode
1370generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371statement containing point, even if point happens to be in the middle
1372of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
1374
1375@INDENTATION
1376
1377Primarily for entering new code:
1378\t\\[indent-for-tab-command]\t indent line appropriately
1379\t\\[py-newline-and-indent]\t insert newline, then indent
1380\t\\[py-delete-char]\t reduce indentation, or delete single character
1381
1382Primarily for reindenting existing code:
1383\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1384\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1385
1386\t\\[py-indent-region]\t reindent region to match its context
1387\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1388\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1389
1390Unlike most programming languages, Python uses indentation, and only
1391indentation, to specify block structure. Hence the indentation supplied
1392automatically by Python-mode is just an educated guess: only you know
1393the block structure you intend, so only you can supply correct
1394indentation.
1395
1396The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1397the indentation of preceding statements. E.g., assuming
1398py-indent-offset is 4, after you enter
1399\tif a > 0: \\[py-newline-and-indent]
1400the cursor will be moved to the position of the `_' (_ is not a
1401character in the file, it's just used here to indicate the location of
1402the cursor):
1403\tif a > 0:
1404\t _
1405If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1406to
1407\tif a > 0:
1408\t c = d
1409\t _
1410Python-mode cannot know whether that's what you intended, or whether
1411\tif a > 0:
1412\t c = d
1413\t_
1414was your intent. In general, Python-mode either reproduces the
1415indentation of the (closest code or indenting-comment) preceding
1416statement, or adds an extra py-indent-offset blanks if the preceding
1417statement has `:' as its last significant (non-whitespace and non-
1418comment) character. If the suggested indentation is too much, use
1419\\[py-delete-char] to reduce it.
1420
1421Continuation lines are given extra indentation. If you don't like the
1422suggested indentation, change it to something you do like, and Python-
1423mode will strive to indent later lines of the statement in the same way.
1424
1425If a line is a continuation line by virtue of being in an unclosed
1426paren/bracket/brace structure (`list', for short), the suggested
1427indentation depends on whether the current line contains the first item
1428in the list. If it does, it's indented py-indent-offset columns beyond
1429the indentation of the line containing the open bracket. If you don't
1430like that, change it by hand. The remaining items in the list will mimic
1431whatever indentation you give to the first item.
1432
1433If a line is a continuation line because the line preceding it ends with
1434a backslash, the third and following lines of the statement inherit their
1435indentation from the line preceding them. The indentation of the second
1436line in the statement depends on the form of the first (base) line: if
1437the base line is an assignment statement with anything more interesting
1438than the backslash following the leftmost assigning `=', the second line
1439is indented two columns beyond that `='. Else it's indented to two
1440columns beyond the leftmost solid chunk of non-whitespace characters on
1441the base line.
1442
1443Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1444repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1445structure you intend.
1446%c:indent-for-tab-command
1447%c:py-newline-and-indent
1448%c:py-delete-char
1449
1450
1451The next function may be handy when editing code you didn't write:
1452%c:py-guess-indent-offset
1453
1454
1455The remaining `indent' functions apply to a region of Python code. They
1456assume the block structure (equals indentation, in Python) of the region
1457is correct, and alter the indentation in various ways while preserving
1458the block structure:
1459%c:py-indent-region
1460%c:py-shift-region-left
1461%c:py-shift-region-right
1462
1463@MARKING & MANIPULATING REGIONS OF CODE
1464
1465\\[py-mark-block]\t mark block of lines
1466\\[mark-python-def-or-class]\t mark smallest enclosing def
1467\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1468\\[py-comment-region]\t comment out region of code
1469\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1470%c:py-mark-block
1471%c:mark-python-def-or-class
1472%c:py-comment-region
1473
1474@MOVING POINT
1475
1476\\[py-previous-statement]\t move to statement preceding point
1477\\[py-next-statement]\t move to statement following point
1478\\[py-goto-block-up]\t move up to start of current block
1479\\[beginning-of-python-def-or-class]\t move to start of def
1480\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1481\\[end-of-python-def-or-class]\t move to end of def
1482\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1483
1484The first two move to one statement beyond the statement that contains
1485point. A numeric prefix argument tells them to move that many
1486statements instead. Blank lines, comment lines, and continuation lines
1487do not count as `statements' for these commands. So, e.g., you can go
1488to the first code statement in a file by entering
1489\t\\[beginning-of-buffer]\t to move to the top of the file
1490\t\\[py-next-statement]\t to skip over initial comments and blank lines
1491Or do `\\[py-previous-statement]' with a huge prefix argument.
1492%c:py-previous-statement
1493%c:py-next-statement
1494%c:py-goto-block-up
1495%c:beginning-of-python-def-or-class
1496%c:end-of-python-def-or-class
1497
1498@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1499
1500`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1501
1502`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1503overall class and def structure of a module.
1504
1505`\\[back-to-indentation]' moves point to a line's first non-blank character.
1506
1507`\\[indent-relative]' is handy for creating odd indentation.
1508
1509@OTHER EMACS HINTS
1510
1511If you don't like the default value of a variable, change its value to
1512whatever you do like by putting a `setq' line in your .emacs file.
1513E.g., to set the indentation increment to 4, put this line in your
1514.emacs:
1515\t(setq py-indent-offset 4)
1516To see the value of a variable, do `\\[describe-variable]' and enter the variable
1517name at the prompt.
1518
1519When entering a key sequence like `C-c C-n', it is not necessary to
1520release the CONTROL key after doing the `C-c' part -- it suffices to
1521press the CONTROL key, press and release `c' (while still holding down
1522CONTROL), press and release `n' (while still holding down CONTROL), &
1523then release CONTROL.
1524
1525Entering Python mode calls with no arguments the value of the variable
1526`python-mode-hook', if that value exists and is not nil; for backward
1527compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1528the Elisp manual for details.
1529
1530Obscure: When python-mode is first loaded, it looks for all bindings
1531to newline-and-indent in the global keymap, and shadows them with
1532local bindings to py-newline-and-indent."))
1533
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001534
1535;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536(defvar py-parse-state-re
1537 (concat
1538 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1539 "\\|"
1540 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541
Barry Warsaw7ae77681994-12-12 20:38:05 +00001542;; returns the parse state at point (see parse-partial-sexp docs)
1543(defun py-parse-state ()
1544 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001545 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001546 ;; back up to the first preceding line (if any; else start of
1547 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001548 ;; whitespace and non-comment character. These are good places
1549 ;; to start parsing to see whether where we started is at a
1550 ;; non-zero nesting level. It may be slow for people who write
1551 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552 (re-search-backward py-parse-state-re nil 'move)
1553 (beginning-of-line)
1554 (parse-partial-sexp (point) here))))
1555
1556;; if point is at a non-zero nesting level, returns the number of the
1557;; character that opens the smallest enclosing unclosed list; else
1558;; returns nil.
1559(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001561 (if (zerop (car status))
1562 nil ; not in a nest
1563 (car (cdr status))))) ; char# of open bracket
1564
1565;; t iff preceding line ends with backslash that's not in a comment
1566(defun py-backslash-continuation-line-p ()
1567 (save-excursion
1568 (beginning-of-line)
1569 (and
1570 ;; use a cheap test first to avoid the regexp if possible
1571 ;; use 'eq' because char-after may return nil
1572 (eq (char-after (- (point) 2)) ?\\ )
1573 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001574 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001575 (looking-at py-continued-re))))
1576
1577;; t iff current line is a continuation line
1578(defun py-continuation-line-p ()
1579 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581 (or (py-backslash-continuation-line-p)
1582 (py-nesting-level))))
1583
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001584;; go to initial line of current statement; usually this is the line
1585;; we're on, but if we're on the 2nd or following lines of a
1586;; continuation block, we need to go up to the first line of the
1587;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001589;; Tricky: We want to avoid quadratic-time behavior for long continued
1590;; blocks, whether of the backslash or open-bracket varieties, or a
1591;; mix of the two. The following manages to do that in the usual
1592;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001593(defun py-goto-initial-line ()
1594 (let ( open-bracket-pos )
1595 (while (py-continuation-line-p)
1596 (beginning-of-line)
1597 (if (py-backslash-continuation-line-p)
1598 (while (py-backslash-continuation-line-p)
1599 (forward-line -1))
1600 ;; else zip out of nested brackets/braces/parens
1601 (while (setq open-bracket-pos (py-nesting-level))
1602 (goto-char open-bracket-pos)))))
1603 (beginning-of-line))
1604
1605;; go to point right beyond final line of current statement; usually
1606;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001607;; statement we need to skip over the continuation lines. Tricky:
1608;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001609(defun py-goto-beyond-final-line ()
1610 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001611 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001612 (while (and (py-continuation-line-p)
1613 (not (eobp)))
1614 ;; skip over the backslash flavor
1615 (while (and (py-backslash-continuation-line-p)
1616 (not (eobp)))
1617 (forward-line 1))
1618 ;; if in nest, zip to the end of the nest
1619 (setq state (py-parse-state))
1620 (if (and (not (zerop (car state)))
1621 (not (eobp)))
1622 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001623 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001624 ;; the 3rd argument should be plain 0
1625 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1626 nil state)
1627 (forward-line 1))))))
1628
1629;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001630;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001631(defun py-statement-opens-block-p ()
1632 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001633 (let ((start (point))
1634 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1635 (searching t)
1636 (answer nil)
1637 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001638 (goto-char start)
1639 (while searching
1640 ;; look for a colon with nothing after it except whitespace, and
1641 ;; maybe a comment
1642 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1643 finish t)
1644 (if (eq (point) finish) ; note: no `else' clause; just
1645 ; keep searching if we're not at
1646 ; the end yet
1647 ;; sure looks like it opens a block -- but it might
1648 ;; be in a comment
1649 (progn
1650 (setq searching nil) ; search is done either way
1651 (setq state (parse-partial-sexp start
1652 (match-beginning 0)))
1653 (setq answer (not (nth 4 state)))))
1654 ;; search failed: couldn't find another interesting colon
1655 (setq searching nil)))
1656 answer)))
1657
1658;; go to point right beyond final line of block begun by the current
1659;; line. This is the same as where py-goto-beyond-final-line goes
1660;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001661;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001662(defun py-goto-beyond-block ()
1663 (if (py-statement-opens-block-p)
1664 (py-mark-block nil 'just-move)
1665 (py-goto-beyond-final-line)))
1666
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667;; go to start of first statement (not blank or comment or
1668;; continuation line) at or preceding point. returns t if there is
1669;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001670(defun py-goto-statement-at-or-above ()
1671 (py-goto-initial-line)
1672 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673 ;; skip back over blank & comment lines
1674 ;; note: will skip a blank or comment line that happens to be
1675 ;; a continuation line too
1676 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1677 (progn (py-goto-initial-line) t)
1678 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679 t))
1680
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001681;; go to start of first statement (not blank or comment or
1682;; continuation line) following the statement containing point returns
1683;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001684(defun py-goto-statement-below ()
1685 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001686 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001687 (py-goto-beyond-final-line)
1688 (while (and
1689 (looking-at py-blank-or-comment-re)
1690 (not (eobp)))
1691 (forward-line 1))
1692 (if (eobp)
1693 (progn (goto-char start) nil)
1694 t)))
1695
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001696;; go to start of statement, at or preceding point, starting with
1697;; keyword KEY. Skips blank lines and non-indenting comments upward
1698;; first. If that statement starts with KEY, done, else go back to
1699;; first enclosing block starting with KEY. If successful, leaves
1700;; point at the start of the KEY line & returns t. Else leaves point
1701;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001702(defun py-go-up-tree-to-keyword (key)
1703 ;; skip blanks and non-indenting #
1704 (py-goto-initial-line)
1705 (while (and
1706 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1707 (zerop (forward-line -1))) ; go back
1708 nil)
1709 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001710 (let* ((re (concat "[ \t]*" key "\\b"))
1711 (case-fold-search nil) ; let* so looking-at sees this
1712 (found (looking-at re))
1713 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001714 (while (not (or found dead))
1715 (condition-case nil ; in case no enclosing block
1716 (py-goto-block-up 'no-mark)
1717 (error (setq dead t)))
1718 (or dead (setq found (looking-at re))))
1719 (beginning-of-line)
1720 found))
1721
1722;; return string in buffer from start of indentation to end of line;
1723;; prefix "..." if leading whitespace was skipped
1724(defun py-suck-up-leading-text ()
1725 (save-excursion
1726 (back-to-indentation)
1727 (concat
1728 (if (bolp) "" "...")
1729 (buffer-substring (point) (progn (end-of-line) (point))))))
1730
1731;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1732;; as a Lisp symbol; return nil if none
1733(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001734 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001735 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1736 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1737 nil)))
1738
1739(defun py-make-temp-name ()
1740 (make-temp-name
1741 (concat (file-name-as-directory py-temp-directory) "python")))
1742
1743(defun py-delete-file-silently (fname)
1744 (condition-case nil
1745 (delete-file fname)
1746 (error nil)))
1747
1748(defun py-kill-emacs-hook ()
1749 ;; delete our temp files
1750 (while py-file-queue
1751 (py-delete-file-silently (car py-file-queue))
1752 (setq py-file-queue (cdr py-file-queue)))
1753 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1754 ;; run the hook we inherited, if any
1755 (and py-inherited-kill-emacs-hook
1756 (funcall py-inherited-kill-emacs-hook))))
1757
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001758;; make PROCESS's buffer visible, append STRING to it, and force
1759;; display; also make shell-mode believe the user typed this string,
1760;; so that kill-output-from-shell and show-output-from-shell work
1761;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001763 (let ((cbuf (current-buffer))
1764 (pbuf (process-buffer process))
1765 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766 (set-buffer pbuf)
1767 (goto-char (point-max))
1768 (move-marker (process-mark process) (point))
1769 (if (not py-this-is-emacs-19-p)
1770 (move-marker last-input-start (point))) ; muck w/ shell-mode
1771 (funcall (process-filter process) process string)
1772 (if (not py-this-is-emacs-19-p)
1773 (move-marker last-input-end (point))) ; muck w/ shell-mode
1774 (set-buffer cbuf))
1775 (sit-for 0))
1776
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001777(defun py-keep-region-active ()
1778 ;; do whatever is necessary to keep the region active in XEmacs.
1779 ;; Ignore byte-compiler warnings you might see. Also note that
1780 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1781 ;; require us to take explicit action.
1782 (and (boundp 'zmacs-region-stays)
1783 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001784
1785
Barry Warsaw850437a1995-03-08 21:50:28 +00001786(defconst py-version "$Revision$"
1787 "`python-mode' version number.")
1788(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1789 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790
Barry Warsaw850437a1995-03-08 21:50:28 +00001791(defun py-version ()
1792 "Echo the current version of `python-mode' in the minibuffer."
1793 (interactive)
1794 (message "Using `python-mode' version %s" py-version)
1795 (py-keep-region-active))
1796
1797;; only works under Emacs 19
1798;(eval-when-compile
1799; (require 'reporter))
1800
1801(defun py-submit-bug-report (enhancement-p)
1802 "Submit via mail a bug report on `python-mode'.
1803With \\[universal-argument] just submit an enhancement request."
1804 (interactive
1805 (list (not (y-or-n-p
1806 "Is this a bug report? (hit `n' to send other comments) "))))
1807 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1808 (require 'reporter)
1809 (reporter-submit-bug-report
1810 py-help-address ;address
1811 "python-mode" ;pkgname
1812 ;; varlist
1813 (if enhancement-p nil
1814 '(py-python-command
1815 py-indent-offset
1816 py-block-comment-prefix
1817 py-scroll-process-buffer
1818 py-temp-directory
1819 py-beep-if-tab-change))
1820 nil ;pre-hooks
1821 nil ;post-hooks
1822 "Dear Barry,") ;salutation
1823 (if enhancement-p nil
1824 (set-mark (point))
1825 (insert
1826"Please replace this text with a sufficiently large code sample\n\
1827and an exact recipe so that I can reproduce your problem. Failure\n\
1828to do so may mean a greater delay in fixing your bug.\n\n")
1829 (exchange-point-and-mark)
1830 (py-keep-region-active))))
1831
1832
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833;; arrange to kill temp files when Emacs exists
1834(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1835 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1836 ;; have to trust that other people are as respectful of our hook
1837 ;; fiddling as we are of theirs
1838 (if (boundp 'py-inherited-kill-emacs-hook)
1839 ;; we were loaded before -- trust others not to have screwed us
1840 ;; in the meantime (no choice, really)
1841 nil
1842 ;; else arrange for our hook to run theirs
1843 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1844 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1845
1846
1847
1848(provide 'python-mode)
1849;;; python-mode.el ends here