blob: 9e49ec6cd50a6bf83b876301e7d0764c692e2b5d [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 Warsawb91b7431995-03-14 15:55:20 +0000225 '((":" . py-electric-colon)
226 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000227 ("\C-c|" . py-execute-region)
228 ("\C-c!" . py-shell)
229 ("\177" . py-delete-char)
230 ("\n" . py-newline-and-indent)
231 ("\C-c:" . py-guess-indent-offset)
232 ("\C-c\t" . py-indent-region)
233 ("\C-c<" . py-shift-region-left)
234 ("\C-c>" . py-shift-region-right)
235 ("\C-c\C-n" . py-next-statement)
236 ("\C-c\C-p" . py-previous-statement)
237 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000238 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000239 ("\C-c#" . py-comment-region)
240 ("\C-c?" . py-describe-mode)
241 ("\C-c\C-hm" . py-describe-mode)
242 ("\e\C-a" . beginning-of-python-def-or-class)
243 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000244 ( "\e\C-h" . mark-python-def-or-class)))
245 ;; should do all keybindings this way
246 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
247 (define-key py-mode-map "\C-c\C-v" 'py-version)
248 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250(defvar py-mode-syntax-table nil
251 "Syntax table used in `python-mode' buffers.")
252
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253(if py-mode-syntax-table
254 ()
255 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000257 (mapcar (function
258 (lambda (x) (modify-syntax-entry
259 (car x) (cdr x) py-mode-syntax-table)))
260 '(( ?\( . "()" ) ( ?\) . ")(" )
261 ( ?\[ . "(]" ) ( ?\] . ")[" )
262 ( ?\{ . "(}" ) ( ?\} . "){" )
263 ;; fix operator symbols misassigned in the std table
264 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
265 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
266 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
267 ( ?\> . "." ) ( ?\| . "." )
268 ( ?\_ . "w" ) ; underscore is legit in names
269 ( ?\' . "\"") ; single quote is string quote
270 ( ?\" . "\"" ) ; double quote is string quote too
271 ( ?\` . "$") ; backquote is open and close paren
272 ( ?\# . "<") ; hash starts comment
273 ( ?\n . ">")))) ; newline ends comment
274
275(defconst py-stringlit-re
276 (concat
277 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
278 "\\|" ; or
279 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000280 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000281
282;; this is tricky because a trailing backslash does not mean
283;; continuation if it's in a comment
284(defconst py-continued-re
285 (concat
286 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
287 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000288 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000289
290(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000292
Barry Warsaw7ae77681994-12-12 20:38:05 +0000293
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000294
295;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000296(defun python-mode ()
297 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298To submit a problem report, enter `\\[py-submit-bug-report]' from a
299`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
300documentation. To see what version of `python-mode' you are running,
301enter `\\[py-version]'.
302
303This mode knows about Python indentation, tokens, comments and
304continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000305
306COMMANDS
307\\{py-mode-map}
308VARIABLES
309
310py-indent-offset\tindentation increment
311py-block-comment-prefix\tcomment string used by py-comment-region
312py-python-command\tshell command to invoke Python interpreter
313py-scroll-process-buffer\talways scroll Python process buffer
314py-temp-directory\tdirectory used for temp files (if needed)
315py-beep-if-tab-change\tring the bell if tab-width is changed"
316 (interactive)
317 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000318 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000319 (setq major-mode 'python-mode
320 mode-name "Python"
321 local-abbrev-table python-mode-abbrev-table)
322 (use-local-map py-mode-map)
323 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000324 (mapcar (function (lambda (x)
325 (make-local-variable (car x))
326 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000327 '((paragraph-separate . "^[ \t]*$")
328 (paragraph-start . "^[ \t]*$")
329 (require-final-newline . t)
330 (comment-start . "# ")
331 (comment-start-skip . "# *")
332 (comment-column . 40)
333 (indent-region-function . py-indent-region)
334 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000335 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000336 ;;
337 ;; not sure where the magic comment has to be; to save time
338 ;; searching for a rarity, we give up if it's not found prior to the
339 ;; first executable statement.
340 ;;
341 ;; BAW - on first glance, this seems like complete hackery. Why was
342 ;; this necessary, and is it still necessary?
343 (let ((case-fold-search nil)
344 (start (point))
345 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000346 (if (re-search-forward
347 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
348 (prog2 (py-next-statement 1) (point) (goto-char 1))
349 t)
350 (progn
351 (setq new-tab-width
352 (string-to-int
353 (buffer-substring (match-beginning 1) (match-end 1))))
354 (if (= tab-width new-tab-width)
355 nil
356 (setq tab-width new-tab-width)
357 (message "Caution: tab-width changed to %d" new-tab-width)
358 (if py-beep-if-tab-change (beep)))))
359 (goto-char start))
360
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000361 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000362 (if python-mode-hook
363 (run-hooks 'python-mode-hook)
364 (run-hooks 'py-mode-hook)))
365
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000366
Barry Warsawb91b7431995-03-14 15:55:20 +0000367;; electric characters
368(defun py-electric-colon (arg)
369 "Insert a colon.
370In certain cases the line is outdented appropriately. If a numeric
371argument is provided, that many colons are inserted non-electrically."
372 (interactive "P")
373 (self-insert-command (prefix-numeric-value arg))
374 (let (this-indent)
375 (if (and (not arg)
376 (save-excursion
377 (forward-word -1)
378 (looking-at "\\(else\\|except\\|finally\\elif\\):"))
379 (= (setq this-indent (py-compute-indentation))
380 (save-excursion
381 (forward-line -1)
382 (py-compute-indentation)))
383 )
384 (save-excursion
385 (beginning-of-line)
386 (delete-horizontal-space)
387 (indent-to (- this-indent py-indent-offset)))
388 )))
389
390
Barry Warsaw7ae77681994-12-12 20:38:05 +0000391;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000392(defun py-shell ()
393 "Start an interactive Python interpreter in another window.
394This is like Shell mode, except that Python is running in the window
395instead of a shell. See the `Interactive Shell' and `Shell Mode'
396sections of the Emacs manual for details, especially for the key
397bindings active in the `*Python*' buffer.
398
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000400behavior in the process window.
401
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000402Warning: Don't use an interactive Python if you change sys.ps1 or
403sys.ps2 from their default values, or if you're running code that
404prints `>>> ' or `... ' at the start of a line. `python-mode' can't
405distinguish your output from Python's output, and assumes that `>>> '
406at the start of a line is a prompt from Python. Similarly, the Emacs
407Shell mode code assumes that both `>>> ' and `... ' at the start of a
408line are Python prompts. Bad things can happen if you fool either
409mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000410
411Warning: If you do any editing *in* the process buffer *while* the
412buffer is accepting output from Python, do NOT attempt to `undo' the
413changes. Some of the output (nowhere near the parts you changed!) may
414be lost if you do. This appears to be an Emacs bug, an unfortunate
415interaction between undo and process filters; the same problem exists in
416non-Python process buffers using the default (Emacs-supplied) process
417filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000418 ;; BAW - should undo be disabled in the python process buffer, if
419 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000420 (interactive)
421 (if py-this-is-emacs-19-p
422 (progn
423 (require 'comint)
424 (switch-to-buffer-other-window
425 (make-comint "Python" py-python-command)))
426 (progn
427 (require 'shell)
428 (switch-to-buffer-other-window
429 (make-shell "Python" py-python-command))))
430 (make-local-variable 'shell-prompt-pattern)
431 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
432 (set-process-filter (get-buffer-process (current-buffer))
433 'py-process-filter)
434 (set-syntax-table py-mode-syntax-table))
435
436(defun py-execute-region (start end)
437 "Send the region between START and END to a Python interpreter.
438If there is a *Python* process it is used.
439
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000440Hint: If you want to execute part of a Python file several times
441\(e.g., perhaps you're developing a function and want to flesh it out
442a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
443the region of interest, and send the code to a *Python* process via
444`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445
446Following are subtleties to note when using a *Python* process:
447
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000448If a *Python* process is used, the region is copied into a temporary
449file (in directory `py-temp-directory'), and an `execfile' command is
450sent to Python naming that file. If you send regions faster than
451Python can execute them, `python-mode' will save them into distinct
452temp files, and execute the next one in the queue the next time it
453sees a `>>> ' prompt from Python. Each time this happens, the process
454buffer is popped into a window (if it's not already in some window) so
455you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000456
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000457 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000458
459is inserted at the end.
460
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000461Caution: No more than 26 regions can be pending at any given time.
462This limit is (indirectly) inherited from libc's mktemp(3).
463`python-mode' does not try to protect you from exceeding the limit.
464It's extremely unlikely that you'll get anywhere close to the limit in
465practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000466
467See the `\\[py-shell]' docs for additional warnings."
468 (interactive "r")
469 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000470 (let ((pyproc (get-process "Python"))
471 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000472 (if (null pyproc)
473 (shell-command-on-region start end py-python-command)
474 ;; else feed it thru a temp file
475 (setq fname (py-make-temp-name))
476 (write-region start end fname nil 'no-msg)
477 (setq py-file-queue (append py-file-queue (list fname)))
478 (if (cdr py-file-queue)
479 (message "File %s queued for execution" fname)
480 ;; else
481 (py-execute-file pyproc fname)))))
482
483(defun py-execute-file (pyproc fname)
484 (py-append-to-process-buffer
485 pyproc
486 (format "## working on region in file %s ...\n" fname))
487 (process-send-string pyproc (format "execfile('%s')\n" fname)))
488
489(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000490 (let ((curbuf (current-buffer))
491 (pbuf (process-buffer pyproc))
492 (pmark (process-mark pyproc))
493 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000494
495 ;; make sure we switch to a different buffer at least once. if we
496 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000497 ;; window, and point is before the end, and lots of output is
498 ;; coming at a fast pace, then (a) simple cursor-movement commands
499 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
500 ;; to have a visible effect (the window just doesn't get updated,
501 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
502 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000503 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000504 ;; #b makes no sense to me at all. #a almost makes sense: unless
505 ;; we actually change buffers, set_buffer_internal in buffer.c
506 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
507 ;; seems to make the Emacs command loop reluctant to update the
508 ;; display. Perhaps the default process filter in process.c's
509 ;; read_process_output has update_mode_lines++ for a similar
510 ;; reason? beats me ...
511
512 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000513 (if (eq curbuf pbuf) ; mysterious ugly hack
514 (set-buffer (get-buffer-create "*scratch*")))
515
516 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000517 (let* ((start (point))
518 (goback (< start pmark))
519 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000520 (goto-char pmark)
521 (insert string)
522 (move-marker pmark (point))
523 (setq file-finished
524 (and py-file-queue
525 (equal ">>> "
526 (buffer-substring
527 (prog2 (beginning-of-line) (point)
528 (goto-char pmark))
529 (point)))))
530 (if goback (goto-char start)
531 ;; else
532 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000533 (let* ((pop-up-windows t)
534 (pwin (display-buffer pbuf)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000535 (set-window-point pwin (point))))))
536 (set-buffer curbuf)
537 (if file-finished
538 (progn
539 (py-delete-file-silently (car py-file-queue))
540 (setq py-file-queue (cdr py-file-queue))
541 (if py-file-queue
542 (py-execute-file pyproc (car py-file-queue)))))))
543
544(defun py-execute-buffer ()
545 "Send the contents of the buffer to a Python interpreter.
546If there is a *Python* process buffer it is used. If a clipping
547restriction is in effect, only the accessible portion of the buffer is
548sent. A trailing newline will be supplied if needed.
549
550See the `\\[py-execute-region]' docs for an account of some subtleties."
551 (interactive)
552 (py-execute-region (point-min) (point-max)))
553
554
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000555
556;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557(defun py-delete-char ()
558 "Reduce indentation or delete character.
559If point is at the leftmost column, deletes the preceding newline.
560
561Else if point is at the leftmost non-blank character of a line that is
562neither a continuation line nor a non-indenting comment line, or if
563point is at the end of a blank line, reduces the indentation to match
564that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000565opened the block is displayed in the echo area to help you keep track
566of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000567
568Else the preceding character is deleted, converting a tab to spaces if
569needed so that only a single column position is deleted."
570 (interactive "*")
571 (if (or (/= (current-indentation) (current-column))
572 (bolp)
573 (py-continuation-line-p)
574 (looking-at "#[^ \t\n]")) ; non-indenting #
575 (backward-delete-char-untabify 1)
576 ;; else indent the same as the colon line that opened the block
577
578 ;; force non-blank so py-goto-block-up doesn't ignore it
579 (insert-char ?* 1)
580 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000581 (let ((base-indent 0) ; indentation of base line
582 (base-text "") ; and text of base line
583 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000584 (condition-case nil ; in case no enclosing block
585 (save-excursion
586 (py-goto-block-up 'no-mark)
587 (setq base-indent (current-indentation)
588 base-text (py-suck-up-leading-text)
589 base-found-p t))
590 (error nil))
591 (delete-char 1) ; toss the dummy character
592 (delete-horizontal-space)
593 (indent-to base-indent)
594 (if base-found-p
595 (message "Closes block: %s" base-text)))))
596
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000597;; required for pending-del and delsel modes
598(put 'py-delete-char 'delete-selection 'supersede)
599(put 'py-delete-char 'pending-delete 'supersede)
600
Barry Warsaw7ae77681994-12-12 20:38:05 +0000601(defun py-indent-line ()
602 "Fix the indentation of the current line according to Python rules."
603 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000604 (let* ((ci (current-indentation))
605 (move-to-indentation-p (<= (current-column) ci))
606 (need (py-compute-indentation)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000607 (if (/= ci need)
608 (save-excursion
609 (beginning-of-line)
610 (delete-horizontal-space)
611 (indent-to need)))
612 (if move-to-indentation-p (back-to-indentation))))
613
614(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000615 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000616This is just `strives to' because correct indentation can't be computed
617from scratch for Python code. In general, deletes the whitespace before
618point, inserts a newline, and takes an educated guess as to how you want
619the new line indented."
620 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000621 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000622 (if (< ci (current-column)) ; if point beyond indentation
623 (newline-and-indent)
624 ;; else try to act like newline-and-indent "normally" acts
625 (beginning-of-line)
626 (insert-char ?\n 1)
627 (move-to-column ci))))
628
629(defun py-compute-indentation ()
630 (save-excursion
631 (beginning-of-line)
632 (cond
633 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000634 ((py-continuation-line-p)
635 (let ((startpos (point))
636 (open-bracket-pos (py-nesting-level))
637 endpos searching found)
638 (if open-bracket-pos
639 (progn
640 ;; align with first item in list; else a normal
641 ;; indent beyond the line with the open bracket
642 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
643 ;; is the first list item on the same line?
644 (skip-chars-forward " \t")
645 (if (null (memq (following-char) '(?\n ?# ?\\)))
646 ; yes, so line up with it
647 (current-column)
648 ;; first list item on another line, or doesn't exist yet
649 (forward-line 1)
650 (while (and (< (point) startpos)
651 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
652 (forward-line 1))
653 (if (< (point) startpos)
654 ;; again mimic the first list item
655 (current-indentation)
656 ;; else they're about to enter the first item
657 (goto-char open-bracket-pos)
658 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000659
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000660 ;; else on backslash continuation line
661 (forward-line -1)
662 (if (py-continuation-line-p) ; on at least 3rd line in block
663 (current-indentation) ; so just continue the pattern
664 ;; else started on 2nd line in block, so indent more.
665 ;; if base line is an assignment with a start on a RHS,
666 ;; indent to 2 beyond the leftmost "="; else skip first
667 ;; chunk of non-whitespace characters on base line, + 1 more
668 ;; column
669 (end-of-line)
670 (setq endpos (point) searching t)
671 (back-to-indentation)
672 (setq startpos (point))
673 ;; look at all "=" from left to right, stopping at first
674 ;; one not nested in a list or string
675 (while searching
676 (skip-chars-forward "^=" endpos)
677 (if (= (point) endpos)
678 (setq searching nil)
679 (forward-char 1)
680 (setq state (parse-partial-sexp startpos (point)))
681 (if (and (zerop (car state)) ; not in a bracket
682 (null (nth 3 state))) ; & not in a string
683 (progn
684 (setq searching nil) ; done searching in any case
685 (setq found
686 (not (or
687 (eq (following-char) ?=)
688 (memq (char-after (- (point) 2))
689 '(?< ?> ?!)))))))))
690 (if (or (not found) ; not an assignment
691 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
692 (progn
693 (goto-char startpos)
694 (skip-chars-forward "^ \t\n")))
695 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000696
697 ;; not on a continuation line
698
699 ;; if at start of restriction, or on a non-indenting comment line,
700 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000701 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
702 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000703
704 ;; else indentation based on that of the statement that precedes
705 ;; us; use the first line of that statement to establish the base,
706 ;; in case the user forced a non-std indentation for the
707 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708 (t
709 ;; skip back over blank & non-indenting comment lines
710 ;; note: will skip a blank or non-indenting comment line that
711 ;; happens to be a continuation line too
712 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
713 nil 'move)
714 ;; if we landed inside a string, go to the beginning of that
715 ;; string. this handles triple quoted, multi-line spanning
716 ;; strings.
717 (let ((state (parse-partial-sexp
718 (save-excursion (beginning-of-python-def-or-class)
719 (point))
720 (point))))
721 (if (nth 3 state)
722 (goto-char (nth 2 state))))
723 (py-goto-initial-line)
724 (if (py-statement-opens-block-p)
725 (+ (current-indentation) py-indent-offset)
726 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000727
728(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000729 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000730By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000731`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000732Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000733`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000734their own buffer-local copy), both those currently existing and those
735created later in the Emacs session.
736
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000737Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000738There's no excuse for such foolishness, but sometimes you have to deal
739with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000740`py-indent-offset' to what it thinks it was when they created the
741mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000742
743Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000744looking for a line that opens a block of code. `py-indent-offset' is
745set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746statement following it. If the search doesn't succeed going forward,
747it's tried again going backward."
748 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000749 (let (new-value
750 (start (point))
751 restart
752 (found nil)
753 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000754 (py-goto-initial-line)
755 (while (not (or found (eobp)))
756 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
757 (progn
758 (setq restart (point))
759 (py-goto-initial-line)
760 (if (py-statement-opens-block-p)
761 (setq found t)
762 (goto-char restart)))))
763 (if found
764 ()
765 (goto-char start)
766 (py-goto-initial-line)
767 (while (not (or found (bobp)))
768 (setq found
769 (and
770 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
771 (or (py-goto-initial-line) t) ; always true -- side effect
772 (py-statement-opens-block-p)))))
773 (setq colon-indent (current-indentation)
774 found (and found (zerop (py-next-statement 1)))
775 new-value (- (current-indentation) colon-indent))
776 (goto-char start)
777 (if found
778 (progn
779 (funcall (if global 'kill-local-variable 'make-local-variable)
780 'py-indent-offset)
781 (setq py-indent-offset new-value)
782 (message "%s value of py-indent-offset set to %d"
783 (if global "Global" "Local")
784 py-indent-offset))
785 (error "Sorry, couldn't guess a value for py-indent-offset"))))
786
787(defun py-shift-region (start end count)
788 (save-excursion
789 (goto-char end) (beginning-of-line) (setq end (point))
790 (goto-char start) (beginning-of-line) (setq start (point))
791 (indent-rigidly start end count)))
792
793(defun py-shift-region-left (start end &optional count)
794 "Shift region of Python code to the left.
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
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000797shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000798
799If a prefix argument is given, the region is instead shifted by that
800many columns."
801 (interactive "*r\nP") ; region; raw prefix arg
802 (py-shift-region start end
803 (- (prefix-numeric-value
804 (or count py-indent-offset)))))
805
806(defun py-shift-region-right (start end &optional count)
807 "Shift region of Python code to the right.
808The lines from the line containing the start of the current region up
809to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000810shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000811
812If a prefix argument is given, the region is instead shifted by that
813many columns."
814 (interactive "*r\nP") ; region; raw prefix arg
815 (py-shift-region start end (prefix-numeric-value
816 (or count py-indent-offset))))
817
818(defun py-indent-region (start end &optional indent-offset)
819 "Reindent a region of Python code.
820The lines from the line containing the start of the current region up
821to (but not including) the line containing the end of the region are
822reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000823character in the first column, the first line is left alone and the
824rest of the region is reindented with respect to it. Else the entire
825region is reindented with respect to the (closest code or
826indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000827
828This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000829control structures are introduced or removed, or to reformat code
830using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000831
832If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000833the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000834used.
835
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000836Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000837is called! This function does not compute proper indentation from
838scratch (that's impossible in Python), it merely adjusts the existing
839indentation to be correct in context.
840
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000841Warning: This function really has no idea what to do with
842non-indenting comment lines, and shifts them as if they were indenting
843comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000844
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000845Special cases: whitespace is deleted from blank lines; continuation
846lines are shifted by the same amount their initial line was shifted,
847in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000848initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000849 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000850 (save-excursion
851 (goto-char end) (beginning-of-line) (setq end (point-marker))
852 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000853 (let ((py-indent-offset (prefix-numeric-value
854 (or indent-offset py-indent-offset)))
855 (indents '(-1)) ; stack of active indent levels
856 (target-column 0) ; column to which to indent
857 (base-shifted-by 0) ; amount last base line was shifted
858 (indent-base (if (looking-at "[ \t\n]")
859 (py-compute-indentation)
860 0))
861 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000862 (while (< (point) end)
863 (setq ci (current-indentation))
864 ;; figure out appropriate target column
865 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000866 ((or (eq (following-char) ?#) ; comment in column 1
867 (looking-at "[ \t]*$")) ; entirely blank
868 (setq target-column 0))
869 ((py-continuation-line-p) ; shift relative to base line
870 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000871 (t ; new base line
872 (if (> ci (car indents)) ; going deeper; push it
873 (setq indents (cons ci indents))
874 ;; else we should have seen this indent before
875 (setq indents (memq ci indents)) ; pop deeper indents
876 (if (null indents)
877 (error "Bad indentation in region, at line %d"
878 (save-restriction
879 (widen)
880 (1+ (count-lines 1 (point)))))))
881 (setq target-column (+ indent-base
882 (* py-indent-offset
883 (- (length indents) 2))))
884 (setq base-shifted-by (- target-column ci))))
885 ;; shift as needed
886 (if (/= ci target-column)
887 (progn
888 (delete-horizontal-space)
889 (indent-to target-column)))
890 (forward-line 1))))
891 (set-marker end nil))
892
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000893
894;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000895(defun py-previous-statement (count)
896 "Go to the start of previous Python statement.
897If the statement at point is the i'th Python statement, goes to the
898start of statement i-COUNT. If there is no such statement, goes to the
899first statement. Returns count of statements left to move.
900`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000901 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000902 (if (< count 0) (py-next-statement (- count))
903 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000905 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000906 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907 (> count 0)
908 (zerop (forward-line -1))
909 (py-goto-statement-at-or-above))
910 (setq count (1- count)))
911 (if (> count 0) (goto-char start)))
912 count))
913
914(defun py-next-statement (count)
915 "Go to the start of next Python statement.
916If the statement at point is the i'th Python statement, goes to the
917start of statement i+COUNT. If there is no such statement, goes to the
918last statement. Returns count of statements left to move. `Statements'
919do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000921 (if (< count 0) (py-previous-statement (- count))
922 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000923 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000924 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000925 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000926 (> count 0)
927 (py-goto-statement-below))
928 (setq count (1- count)))
929 (if (> count 0) (goto-char start)))
930 count))
931
932(defun py-goto-block-up (&optional nomark)
933 "Move up to start of current block.
934Go to the statement that starts the smallest enclosing block; roughly
935speaking, this will be the closest preceding statement that ends with a
936colon and is indented less than the statement you started on. If
937successful, also sets the mark to the starting point.
938
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000939`\\[py-mark-block]' can be used afterward to mark the whole code
940block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000941
942If called from a program, the mark will not be set if optional argument
943NOMARK is not nil."
944 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945 (let ((start (point))
946 (found nil)
947 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000948 (py-goto-initial-line)
949 ;; if on blank or non-indenting comment line, use the preceding stmt
950 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
951 (progn
952 (py-goto-statement-at-or-above)
953 (setq found (py-statement-opens-block-p))))
954 ;; search back for colon line indented less
955 (setq initial-indent (current-indentation))
956 (if (zerop initial-indent)
957 ;; force fast exit
958 (goto-char (point-min)))
959 (while (not (or found (bobp)))
960 (setq found
961 (and
962 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
963 (or (py-goto-initial-line) t) ; always true -- side effect
964 (< (current-indentation) initial-indent)
965 (py-statement-opens-block-p))))
966 (if found
967 (progn
968 (or nomark (push-mark start))
969 (back-to-indentation))
970 (goto-char start)
971 (error "Enclosing block not found"))))
972
973(defun beginning-of-python-def-or-class (&optional class)
974 "Move point to start of def (or class, with prefix arg).
975
976Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000977arg, looks for a `class' instead. The docs assume the `def' case;
978just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000979
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000980If point is in a def statement already, and after the `d', simply
981moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000982
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000983Else (point is not in a def statement, or at or before the `d' of a
984def statement), searches for the closest preceding def statement, and
985leaves point at its start. If no such statement can be found, leaves
986point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987
988Returns t iff a def statement is found by these rules.
989
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000990Note that doing this command repeatedly will take you closer to the
991start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000993If you want to mark the current def/class, see
994`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000996 (let ((at-or-before-p (<= (current-column) (current-indentation)))
997 (start-of-line (progn (beginning-of-line) (point)))
998 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999 (if (or (/= start-of-stmt start-of-line)
1000 (not at-or-before-p))
1001 (end-of-line)) ; OK to match on this line
1002 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001003 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001004
1005(defun end-of-python-def-or-class (&optional class)
1006 "Move point beyond end of def (or class, with prefix arg) body.
1007
1008By default, looks for an appropriate `def'. If you supply a prefix arg,
1009looks for a `class' instead. The docs assume the `def' case; just
1010substitute `class' for `def' for the other case.
1011
1012If point is in a def statement already, this is the def we use.
1013
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001014Else if the def found by `\\[beginning-of-python-def-or-class]'
1015contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016
1017Else we search forward for the closest following def, and use that.
1018
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001019If a def can be found by these rules, point is moved to the start of
1020the line immediately following the def block, and the position of the
1021start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022
1023Else point is moved to the end of the buffer, and nil is returned.
1024
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001025Note that doing this command repeatedly will take you closer to the
1026end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028If you want to mark the current def/class, see
1029`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001031 (let ((start (progn (py-goto-initial-line) (point)))
1032 (which (if class "class" "def"))
1033 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001034 ;; move point to start of appropriate def/class
1035 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1036 (setq state 'at-beginning)
1037 ;; else see if beginning-of-python-def-or-class hits container
1038 (if (and (beginning-of-python-def-or-class class)
1039 (progn (py-goto-beyond-block)
1040 (> (point) start)))
1041 (setq state 'at-end)
1042 ;; else search forward
1043 (goto-char start)
1044 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1045 (progn (setq state 'at-beginning)
1046 (beginning-of-line)))))
1047 (cond
1048 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1049 ((eq state 'at-end) t)
1050 ((eq state 'not-found) nil)
1051 (t (error "internal error in end-of-python-def-or-class")))))
1052
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001053
1054;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001055(defun py-mark-block (&optional extend just-move)
1056 "Mark following block of lines. With prefix arg, mark structure.
1057Easier to use than explain. It sets the region to an `interesting'
1058block of succeeding lines. If point is on a blank line, it goes down to
1059the next non-blank line. That will be the start of the region. The end
1060of the region depends on the kind of line at the start:
1061
1062 - If a comment, the region will include all succeeding comment lines up
1063 to (but not including) the next non-comment line (if any).
1064
1065 - Else if a prefix arg is given, and the line begins one of these
1066 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001067
1068 if elif else try except finally for while def class
1069
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 the region will be set to the body of the structure, including
1071 following blocks that `belong' to it, but excluding trailing blank
1072 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001073 and all (if any) of the following `except' and `finally' blocks
1074 that belong to the `try' structure will be in the region. Ditto
1075 for if/elif/else, for/else and while/else structures, and (a bit
1076 degenerate, since they're always one-block structures) def and
1077 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001078
1079 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 block (see list above), and the block is not a `one-liner' (i.e.,
1081 the statement ends with a colon, not with code), the region will
1082 include all succeeding lines up to (but not including) the next
1083 code statement (if any) that's indented no more than the starting
1084 line, except that trailing blank and comment lines are excluded.
1085 E.g., if the starting line begins a multi-statement `def'
1086 structure, the region will be set to the full function definition,
1087 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001088
1089 - Else the region will include all succeeding lines up to (but not
1090 including) the next blank line, or code or indenting-comment line
1091 indented strictly less than the starting line. Trailing indenting
1092 comment lines are included in this case, but not trailing blank
1093 lines.
1094
1095A msg identifying the location of the mark is displayed in the echo
1096area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1097
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001098If called from a program, optional argument EXTEND plays the role of
1099the prefix arg, and if optional argument JUST-MOVE is not nil, just
1100moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001101 (interactive "P") ; raw prefix arg
1102 (py-goto-initial-line)
1103 ;; skip over blank lines
1104 (while (and
1105 (looking-at "[ \t]*$") ; while blank line
1106 (not (eobp))) ; & somewhere to go
1107 (forward-line 1))
1108 (if (eobp)
1109 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001110 (let ((initial-pos (point))
1111 (initial-indent (current-indentation))
1112 last-pos ; position of last stmt in region
1113 (followers
1114 '((if elif else) (elif elif else) (else)
1115 (try except finally) (except except) (finally)
1116 (for else) (while else)
1117 (def) (class) ) )
1118 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001119
1120 (cond
1121 ;; if comment line, suck up the following comment lines
1122 ((looking-at "[ \t]*#")
1123 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1124 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1125 (setq last-pos (point)))
1126
1127 ;; else if line is a block line and EXTEND given, suck up
1128 ;; the whole structure
1129 ((and extend
1130 (setq first-symbol (py-suck-up-first-keyword) )
1131 (assq first-symbol followers))
1132 (while (and
1133 (or (py-goto-beyond-block) t) ; side effect
1134 (forward-line -1) ; side effect
1135 (setq last-pos (point)) ; side effect
1136 (py-goto-statement-below)
1137 (= (current-indentation) initial-indent)
1138 (setq next-symbol (py-suck-up-first-keyword))
1139 (memq next-symbol (cdr (assq first-symbol followers))))
1140 (setq first-symbol next-symbol)))
1141
1142 ;; else if line *opens* a block, search for next stmt indented <=
1143 ((py-statement-opens-block-p)
1144 (while (and
1145 (setq last-pos (point)) ; always true -- side effect
1146 (py-goto-statement-below)
1147 (> (current-indentation) initial-indent))
1148 nil))
1149
1150 ;; else plain code line; stop at next blank line, or stmt or
1151 ;; indenting comment line indented <
1152 (t
1153 (while (and
1154 (setq last-pos (point)) ; always true -- side effect
1155 (or (py-goto-beyond-final-line) t)
1156 (not (looking-at "[ \t]*$")) ; stop at blank line
1157 (or
1158 (>= (current-indentation) initial-indent)
1159 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1160 nil)))
1161
1162 ;; skip to end of last stmt
1163 (goto-char last-pos)
1164 (py-goto-beyond-final-line)
1165
1166 ;; set mark & display
1167 (if just-move
1168 () ; just return
1169 (push-mark (point) 'no-msg)
1170 (forward-line -1)
1171 (message "Mark set after: %s" (py-suck-up-leading-text))
1172 (goto-char initial-pos))))
1173
1174(defun mark-python-def-or-class (&optional class)
1175 "Set region to body of def (or class, with prefix arg) enclosing point.
1176Pushes the current mark, then point, on the mark ring (all language
1177modes do this, but although it's handy it's never documented ...).
1178
1179In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001180hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1181`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001182
1183And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001184Turned out that was more confusing than useful: the `goto start' and
1185`goto end' commands are usually used to search through a file, and
1186people expect them to act a lot like `search backward' and `search
1187forward' string-search commands. But because Python `def' and `class'
1188can nest to arbitrary levels, finding the smallest def containing
1189point cannot be done via a simple backward search: the def containing
1190point may not be the closest preceding def, or even the closest
1191preceding def that's indented less. The fancy algorithm required is
1192appropriate for the usual uses of this `mark' command, but not for the
1193`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001194
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001195So the def marked by this command may not be the one either of the
1196`goto' commands find: If point is on a blank or non-indenting comment
1197line, moves back to start of the closest preceding code statement or
1198indenting comment line. If this is a `def' statement, that's the def
1199we use. Else searches for the smallest enclosing `def' block and uses
1200that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001202When an enclosing def is found: The mark is left immediately beyond
1203the last line of the def block. Point is left at the start of the
1204def, except that: if the def is preceded by a number of comment lines
1205followed by (at most) one optional blank line, point is left at the
1206start of the comments; else if the def is preceded by a blank line,
1207point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001208
1209The intent is to mark the containing def/class and its associated
1210documentation, to make moving and duplicating functions and classes
1211pleasant."
1212 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001213 (let ((start (point))
1214 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001215 (push-mark start)
1216 (if (not (py-go-up-tree-to-keyword which))
1217 (progn (goto-char start)
1218 (error "Enclosing %s not found" which))
1219 ;; else enclosing def/class found
1220 (setq start (point))
1221 (py-goto-beyond-block)
1222 (push-mark (point))
1223 (goto-char start)
1224 (if (zerop (forward-line -1)) ; if there is a preceding line
1225 (progn
1226 (if (looking-at "[ \t]*$") ; it's blank
1227 (setq start (point)) ; so reset start point
1228 (goto-char start)) ; else try again
1229 (if (zerop (forward-line -1))
1230 (if (looking-at "[ \t]*#") ; a comment
1231 ;; look back for non-comment line
1232 ;; tricky: note that the regexp matches a blank
1233 ;; line, cuz \n is in the 2nd character class
1234 (and
1235 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1236 (forward-line 1))
1237 ;; no comment, so go back
1238 (goto-char start))))))))
1239
1240(defun py-comment-region (start end &optional uncomment-p)
1241 "Comment out region of code; with prefix arg, uncomment region.
1242The lines from the line containing the start of the current region up
1243to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001244commented out, by inserting the string `py-block-comment-prefix' at
1245the start of each line. With a prefix arg, removes
1246`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001247 (interactive "*r\nP") ; region; raw prefix arg
1248 (goto-char end) (beginning-of-line) (setq end (point))
1249 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001250 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001251 (save-excursion
1252 (save-restriction
1253 (narrow-to-region start end)
1254 (while (not (eobp))
1255 (if uncomment-p
1256 (and (string= py-block-comment-prefix
1257 (buffer-substring
1258 (point) (+ (point) prefix-len)))
1259 (delete-char prefix-len))
1260 (insert py-block-comment-prefix))
1261 (forward-line 1))))))
1262
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001263
1264;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001265
1266;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001267;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1268;; out of the right places, along with the keys they're on & current
1269;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001270(defun py-dump-help-string (str)
1271 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001272 (let ((locals (buffer-local-variables))
1273 funckind funcname func funcdoc
1274 (start 0) mstart end
1275 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001276 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1277 (setq mstart (match-beginning 0) end (match-end 0)
1278 funckind (substring str (match-beginning 1) (match-end 1))
1279 funcname (substring str (match-beginning 2) (match-end 2))
1280 func (intern funcname))
1281 (princ (substitute-command-keys (substring str start mstart)))
1282 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001283 ((equal funckind "c") ; command
1284 (setq funcdoc (documentation func)
1285 keys (concat
1286 "Key(s): "
1287 (mapconcat 'key-description
1288 (where-is-internal func py-mode-map)
1289 ", "))))
1290 ((equal funckind "v") ; variable
1291 (setq funcdoc (substitute-command-keys
1292 (get func 'variable-documentation))
1293 keys (if (assq func locals)
1294 (concat
1295 "Local/Global values: "
1296 (prin1-to-string (symbol-value func))
1297 " / "
1298 (prin1-to-string (default-value func)))
1299 (concat
1300 "Value: "
1301 (prin1-to-string (symbol-value func))))))
1302 (t ; unexpected
1303 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001304 (princ (format "\n-> %s:\t%s\t%s\n\n"
1305 (if (equal funckind "c") "Command" "Variable")
1306 funcname keys))
1307 (princ funcdoc)
1308 (terpri)
1309 (setq start end))
1310 (princ (substitute-command-keys (substring str start))))
1311 (print-help-return-message)))
1312
1313(defun py-describe-mode ()
1314 "Dump long form of Python-mode docs."
1315 (interactive)
1316 (py-dump-help-string "Major mode for editing Python files.
1317Knows about Python indentation, tokens, comments and continuation lines.
1318Paragraphs are separated by blank lines only.
1319
1320Major sections below begin with the string `@'; specific function and
1321variable docs begin with `->'.
1322
1323@EXECUTING PYTHON CODE
1324
1325\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1326\\[py-execute-region]\tsends the current region
1327\\[py-shell]\tstarts a Python interpreter window; this will be used by
1328\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1329%c:py-execute-buffer
1330%c:py-execute-region
1331%c:py-shell
1332
1333@VARIABLES
1334
1335py-indent-offset\tindentation increment
1336py-block-comment-prefix\tcomment string used by py-comment-region
1337
1338py-python-command\tshell command to invoke Python interpreter
1339py-scroll-process-buffer\talways scroll Python process buffer
1340py-temp-directory\tdirectory used for temp files (if needed)
1341
1342py-beep-if-tab-change\tring the bell if tab-width is changed
1343%v:py-indent-offset
1344%v:py-block-comment-prefix
1345%v:py-python-command
1346%v:py-scroll-process-buffer
1347%v:py-temp-directory
1348%v:py-beep-if-tab-change
1349
1350@KINDS OF LINES
1351
1352Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001353preceding line ends with a backslash that's not part of a comment, or
1354the paren/bracket/brace nesting level at the start of the line is
1355non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356
1357An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001358possibly blanks or tabs), a `comment line' (leftmost non-blank
1359character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001360
1361Comment Lines
1362
1363Although all comment lines are treated alike by Python, Python mode
1364recognizes two kinds that act differently with respect to indentation.
1365
1366An `indenting comment line' is a comment line with a blank, tab or
1367nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001368treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369indenting comment line will be indented like the comment line. All
1370other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001371following the initial `#') are `non-indenting comment lines', and
1372their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
1374Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001375whenever possible. Non-indenting comment lines are useful in cases
1376like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001377
1378\ta = b # a very wordy single-line comment that ends up being
1379\t #... continued onto another line
1380
1381\tif a == b:
1382##\t\tprint 'panic!' # old code we've `commented out'
1383\t\treturn a
1384
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001385Since the `#...' and `##' comment lines have a non-whitespace
1386character following the initial `#', Python mode ignores them when
1387computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001388
1389Continuation Lines and Statements
1390
1391The Python-mode commands generally work on statements instead of on
1392individual lines, where a `statement' is a comment or blank line, or a
1393code line and all of its following continuation lines (if any)
1394considered as a single logical unit. The commands in this mode
1395generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001396statement containing point, even if point happens to be in the middle
1397of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001398
1399
1400@INDENTATION
1401
1402Primarily for entering new code:
1403\t\\[indent-for-tab-command]\t indent line appropriately
1404\t\\[py-newline-and-indent]\t insert newline, then indent
1405\t\\[py-delete-char]\t reduce indentation, or delete single character
1406
1407Primarily for reindenting existing code:
1408\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1409\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1410
1411\t\\[py-indent-region]\t reindent region to match its context
1412\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1413\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1414
1415Unlike most programming languages, Python uses indentation, and only
1416indentation, to specify block structure. Hence the indentation supplied
1417automatically by Python-mode is just an educated guess: only you know
1418the block structure you intend, so only you can supply correct
1419indentation.
1420
1421The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1422the indentation of preceding statements. E.g., assuming
1423py-indent-offset is 4, after you enter
1424\tif a > 0: \\[py-newline-and-indent]
1425the cursor will be moved to the position of the `_' (_ is not a
1426character in the file, it's just used here to indicate the location of
1427the cursor):
1428\tif a > 0:
1429\t _
1430If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1431to
1432\tif a > 0:
1433\t c = d
1434\t _
1435Python-mode cannot know whether that's what you intended, or whether
1436\tif a > 0:
1437\t c = d
1438\t_
1439was your intent. In general, Python-mode either reproduces the
1440indentation of the (closest code or indenting-comment) preceding
1441statement, or adds an extra py-indent-offset blanks if the preceding
1442statement has `:' as its last significant (non-whitespace and non-
1443comment) character. If the suggested indentation is too much, use
1444\\[py-delete-char] to reduce it.
1445
1446Continuation lines are given extra indentation. If you don't like the
1447suggested indentation, change it to something you do like, and Python-
1448mode will strive to indent later lines of the statement in the same way.
1449
1450If a line is a continuation line by virtue of being in an unclosed
1451paren/bracket/brace structure (`list', for short), the suggested
1452indentation depends on whether the current line contains the first item
1453in the list. If it does, it's indented py-indent-offset columns beyond
1454the indentation of the line containing the open bracket. If you don't
1455like that, change it by hand. The remaining items in the list will mimic
1456whatever indentation you give to the first item.
1457
1458If a line is a continuation line because the line preceding it ends with
1459a backslash, the third and following lines of the statement inherit their
1460indentation from the line preceding them. The indentation of the second
1461line in the statement depends on the form of the first (base) line: if
1462the base line is an assignment statement with anything more interesting
1463than the backslash following the leftmost assigning `=', the second line
1464is indented two columns beyond that `='. Else it's indented to two
1465columns beyond the leftmost solid chunk of non-whitespace characters on
1466the base line.
1467
1468Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1469repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1470structure you intend.
1471%c:indent-for-tab-command
1472%c:py-newline-and-indent
1473%c:py-delete-char
1474
1475
1476The next function may be handy when editing code you didn't write:
1477%c:py-guess-indent-offset
1478
1479
1480The remaining `indent' functions apply to a region of Python code. They
1481assume the block structure (equals indentation, in Python) of the region
1482is correct, and alter the indentation in various ways while preserving
1483the block structure:
1484%c:py-indent-region
1485%c:py-shift-region-left
1486%c:py-shift-region-right
1487
1488@MARKING & MANIPULATING REGIONS OF CODE
1489
1490\\[py-mark-block]\t mark block of lines
1491\\[mark-python-def-or-class]\t mark smallest enclosing def
1492\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1493\\[py-comment-region]\t comment out region of code
1494\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1495%c:py-mark-block
1496%c:mark-python-def-or-class
1497%c:py-comment-region
1498
1499@MOVING POINT
1500
1501\\[py-previous-statement]\t move to statement preceding point
1502\\[py-next-statement]\t move to statement following point
1503\\[py-goto-block-up]\t move up to start of current block
1504\\[beginning-of-python-def-or-class]\t move to start of def
1505\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1506\\[end-of-python-def-or-class]\t move to end of def
1507\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1508
1509The first two move to one statement beyond the statement that contains
1510point. A numeric prefix argument tells them to move that many
1511statements instead. Blank lines, comment lines, and continuation lines
1512do not count as `statements' for these commands. So, e.g., you can go
1513to the first code statement in a file by entering
1514\t\\[beginning-of-buffer]\t to move to the top of the file
1515\t\\[py-next-statement]\t to skip over initial comments and blank lines
1516Or do `\\[py-previous-statement]' with a huge prefix argument.
1517%c:py-previous-statement
1518%c:py-next-statement
1519%c:py-goto-block-up
1520%c:beginning-of-python-def-or-class
1521%c:end-of-python-def-or-class
1522
1523@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1524
1525`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1526
1527`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1528overall class and def structure of a module.
1529
1530`\\[back-to-indentation]' moves point to a line's first non-blank character.
1531
1532`\\[indent-relative]' is handy for creating odd indentation.
1533
1534@OTHER EMACS HINTS
1535
1536If you don't like the default value of a variable, change its value to
1537whatever you do like by putting a `setq' line in your .emacs file.
1538E.g., to set the indentation increment to 4, put this line in your
1539.emacs:
1540\t(setq py-indent-offset 4)
1541To see the value of a variable, do `\\[describe-variable]' and enter the variable
1542name at the prompt.
1543
1544When entering a key sequence like `C-c C-n', it is not necessary to
1545release the CONTROL key after doing the `C-c' part -- it suffices to
1546press the CONTROL key, press and release `c' (while still holding down
1547CONTROL), press and release `n' (while still holding down CONTROL), &
1548then release CONTROL.
1549
1550Entering Python mode calls with no arguments the value of the variable
1551`python-mode-hook', if that value exists and is not nil; for backward
1552compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1553the Elisp manual for details.
1554
1555Obscure: When python-mode is first loaded, it looks for all bindings
1556to newline-and-indent in the global keymap, and shadows them with
1557local bindings to py-newline-and-indent."))
1558
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001559
1560;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001561(defvar py-parse-state-re
1562 (concat
1563 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1564 "\\|"
1565 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001566
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567;; returns the parse state at point (see parse-partial-sexp docs)
1568(defun py-parse-state ()
1569 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001571 ;; back up to the first preceding line (if any; else start of
1572 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573 ;; whitespace and non-comment character. These are good places
1574 ;; to start parsing to see whether where we started is at a
1575 ;; non-zero nesting level. It may be slow for people who write
1576 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577 (re-search-backward py-parse-state-re nil 'move)
1578 (beginning-of-line)
1579 (parse-partial-sexp (point) here))))
1580
1581;; if point is at a non-zero nesting level, returns the number of the
1582;; character that opens the smallest enclosing unclosed list; else
1583;; returns nil.
1584(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001585 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586 (if (zerop (car status))
1587 nil ; not in a nest
1588 (car (cdr status))))) ; char# of open bracket
1589
1590;; t iff preceding line ends with backslash that's not in a comment
1591(defun py-backslash-continuation-line-p ()
1592 (save-excursion
1593 (beginning-of-line)
1594 (and
1595 ;; use a cheap test first to avoid the regexp if possible
1596 ;; use 'eq' because char-after may return nil
1597 (eq (char-after (- (point) 2)) ?\\ )
1598 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001599 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600 (looking-at py-continued-re))))
1601
1602;; t iff current line is a continuation line
1603(defun py-continuation-line-p ()
1604 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001605 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001606 (or (py-backslash-continuation-line-p)
1607 (py-nesting-level))))
1608
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001609;; go to initial line of current statement; usually this is the line
1610;; we're on, but if we're on the 2nd or following lines of a
1611;; continuation block, we need to go up to the first line of the
1612;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001614;; Tricky: We want to avoid quadratic-time behavior for long continued
1615;; blocks, whether of the backslash or open-bracket varieties, or a
1616;; mix of the two. The following manages to do that in the usual
1617;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001618(defun py-goto-initial-line ()
1619 (let ( open-bracket-pos )
1620 (while (py-continuation-line-p)
1621 (beginning-of-line)
1622 (if (py-backslash-continuation-line-p)
1623 (while (py-backslash-continuation-line-p)
1624 (forward-line -1))
1625 ;; else zip out of nested brackets/braces/parens
1626 (while (setq open-bracket-pos (py-nesting-level))
1627 (goto-char open-bracket-pos)))))
1628 (beginning-of-line))
1629
1630;; go to point right beyond final line of current statement; usually
1631;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001632;; statement we need to skip over the continuation lines. Tricky:
1633;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001634(defun py-goto-beyond-final-line ()
1635 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001636 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637 (while (and (py-continuation-line-p)
1638 (not (eobp)))
1639 ;; skip over the backslash flavor
1640 (while (and (py-backslash-continuation-line-p)
1641 (not (eobp)))
1642 (forward-line 1))
1643 ;; if in nest, zip to the end of the nest
1644 (setq state (py-parse-state))
1645 (if (and (not (zerop (car state)))
1646 (not (eobp)))
1647 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001648 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001649 ;; the 3rd argument should be plain 0
1650 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1651 nil state)
1652 (forward-line 1))))))
1653
1654;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001655;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656(defun py-statement-opens-block-p ()
1657 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001658 (let ((start (point))
1659 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1660 (searching t)
1661 (answer nil)
1662 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663 (goto-char start)
1664 (while searching
1665 ;; look for a colon with nothing after it except whitespace, and
1666 ;; maybe a comment
1667 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1668 finish t)
1669 (if (eq (point) finish) ; note: no `else' clause; just
1670 ; keep searching if we're not at
1671 ; the end yet
1672 ;; sure looks like it opens a block -- but it might
1673 ;; be in a comment
1674 (progn
1675 (setq searching nil) ; search is done either way
1676 (setq state (parse-partial-sexp start
1677 (match-beginning 0)))
1678 (setq answer (not (nth 4 state)))))
1679 ;; search failed: couldn't find another interesting colon
1680 (setq searching nil)))
1681 answer)))
1682
1683;; go to point right beyond final line of block begun by the current
1684;; line. This is the same as where py-goto-beyond-final-line goes
1685;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001686;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001687(defun py-goto-beyond-block ()
1688 (if (py-statement-opens-block-p)
1689 (py-mark-block nil 'just-move)
1690 (py-goto-beyond-final-line)))
1691
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001692;; go to start of first statement (not blank or comment or
1693;; continuation line) at or preceding point. returns t if there is
1694;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001695(defun py-goto-statement-at-or-above ()
1696 (py-goto-initial-line)
1697 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001698 ;; skip back over blank & comment lines
1699 ;; note: will skip a blank or comment line that happens to be
1700 ;; a continuation line too
1701 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1702 (progn (py-goto-initial-line) t)
1703 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001704 t))
1705
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001706;; go to start of first statement (not blank or comment or
1707;; continuation line) following the statement containing point returns
1708;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001709(defun py-goto-statement-below ()
1710 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001711 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001712 (py-goto-beyond-final-line)
1713 (while (and
1714 (looking-at py-blank-or-comment-re)
1715 (not (eobp)))
1716 (forward-line 1))
1717 (if (eobp)
1718 (progn (goto-char start) nil)
1719 t)))
1720
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001721;; go to start of statement, at or preceding point, starting with
1722;; keyword KEY. Skips blank lines and non-indenting comments upward
1723;; first. If that statement starts with KEY, done, else go back to
1724;; first enclosing block starting with KEY. If successful, leaves
1725;; point at the start of the KEY line & returns t. Else leaves point
1726;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727(defun py-go-up-tree-to-keyword (key)
1728 ;; skip blanks and non-indenting #
1729 (py-goto-initial-line)
1730 (while (and
1731 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1732 (zerop (forward-line -1))) ; go back
1733 nil)
1734 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001735 (let* ((re (concat "[ \t]*" key "\\b"))
1736 (case-fold-search nil) ; let* so looking-at sees this
1737 (found (looking-at re))
1738 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739 (while (not (or found dead))
1740 (condition-case nil ; in case no enclosing block
1741 (py-goto-block-up 'no-mark)
1742 (error (setq dead t)))
1743 (or dead (setq found (looking-at re))))
1744 (beginning-of-line)
1745 found))
1746
1747;; return string in buffer from start of indentation to end of line;
1748;; prefix "..." if leading whitespace was skipped
1749(defun py-suck-up-leading-text ()
1750 (save-excursion
1751 (back-to-indentation)
1752 (concat
1753 (if (bolp) "" "...")
1754 (buffer-substring (point) (progn (end-of-line) (point))))))
1755
1756;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1757;; as a Lisp symbol; return nil if none
1758(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001759 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1761 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1762 nil)))
1763
1764(defun py-make-temp-name ()
1765 (make-temp-name
1766 (concat (file-name-as-directory py-temp-directory) "python")))
1767
1768(defun py-delete-file-silently (fname)
1769 (condition-case nil
1770 (delete-file fname)
1771 (error nil)))
1772
1773(defun py-kill-emacs-hook ()
1774 ;; delete our temp files
1775 (while py-file-queue
1776 (py-delete-file-silently (car py-file-queue))
1777 (setq py-file-queue (cdr py-file-queue)))
1778 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1779 ;; run the hook we inherited, if any
1780 (and py-inherited-kill-emacs-hook
1781 (funcall py-inherited-kill-emacs-hook))))
1782
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001783;; make PROCESS's buffer visible, append STRING to it, and force
1784;; display; also make shell-mode believe the user typed this string,
1785;; so that kill-output-from-shell and show-output-from-shell work
1786;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001787(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788 (let ((cbuf (current-buffer))
1789 (pbuf (process-buffer process))
1790 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791 (set-buffer pbuf)
1792 (goto-char (point-max))
1793 (move-marker (process-mark process) (point))
1794 (if (not py-this-is-emacs-19-p)
1795 (move-marker last-input-start (point))) ; muck w/ shell-mode
1796 (funcall (process-filter process) process string)
1797 (if (not py-this-is-emacs-19-p)
1798 (move-marker last-input-end (point))) ; muck w/ shell-mode
1799 (set-buffer cbuf))
1800 (sit-for 0))
1801
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001802(defun py-keep-region-active ()
1803 ;; do whatever is necessary to keep the region active in XEmacs.
1804 ;; Ignore byte-compiler warnings you might see. Also note that
1805 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1806 ;; require us to take explicit action.
1807 (and (boundp 'zmacs-region-stays)
1808 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001809
1810
Barry Warsaw850437a1995-03-08 21:50:28 +00001811(defconst py-version "$Revision$"
1812 "`python-mode' version number.")
1813(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1814 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815
Barry Warsaw850437a1995-03-08 21:50:28 +00001816(defun py-version ()
1817 "Echo the current version of `python-mode' in the minibuffer."
1818 (interactive)
1819 (message "Using `python-mode' version %s" py-version)
1820 (py-keep-region-active))
1821
1822;; only works under Emacs 19
1823;(eval-when-compile
1824; (require 'reporter))
1825
1826(defun py-submit-bug-report (enhancement-p)
1827 "Submit via mail a bug report on `python-mode'.
1828With \\[universal-argument] just submit an enhancement request."
1829 (interactive
1830 (list (not (y-or-n-p
1831 "Is this a bug report? (hit `n' to send other comments) "))))
1832 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1833 (require 'reporter)
1834 (reporter-submit-bug-report
1835 py-help-address ;address
1836 "python-mode" ;pkgname
1837 ;; varlist
1838 (if enhancement-p nil
1839 '(py-python-command
1840 py-indent-offset
1841 py-block-comment-prefix
1842 py-scroll-process-buffer
1843 py-temp-directory
1844 py-beep-if-tab-change))
1845 nil ;pre-hooks
1846 nil ;post-hooks
1847 "Dear Barry,") ;salutation
1848 (if enhancement-p nil
1849 (set-mark (point))
1850 (insert
1851"Please replace this text with a sufficiently large code sample\n\
1852and an exact recipe so that I can reproduce your problem. Failure\n\
1853to do so may mean a greater delay in fixing your bug.\n\n")
1854 (exchange-point-and-mark)
1855 (py-keep-region-active))))
1856
1857
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858;; arrange to kill temp files when Emacs exists
1859(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1860 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1861 ;; have to trust that other people are as respectful of our hook
1862 ;; fiddling as we are of theirs
1863 (if (boundp 'py-inherited-kill-emacs-hook)
1864 ;; we were loaded before -- trust others not to have screwed us
1865 ;; in the meantime (no choice, really)
1866 nil
1867 ;; else arrange for our hook to run theirs
1868 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1869 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1870
1871
1872
1873(provide 'python-mode)
1874;;; python-mode.el ends here