blob: 07b00f814f5d73b430c9565d2343c065de231271 [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 Warsaw0012c1e1995-03-14 16:32:55 +0000293(defconst py-outdent-re
294 (concat "\\(" (mapconcat 'identity
295 '("else:"
296 "except\\s +.*:"
297 "finally:"
298 "elif\\s +.*:")
299 "\\|")
300 "\\)")
301 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000302
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000303
304;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000305(defun python-mode ()
306 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000307To submit a problem report, enter `\\[py-submit-bug-report]' from a
308`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
309documentation. To see what version of `python-mode' you are running,
310enter `\\[py-version]'.
311
312This mode knows about Python indentation, tokens, comments and
313continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000314
315COMMANDS
316\\{py-mode-map}
317VARIABLES
318
319py-indent-offset\tindentation increment
320py-block-comment-prefix\tcomment string used by py-comment-region
321py-python-command\tshell command to invoke Python interpreter
322py-scroll-process-buffer\talways scroll Python process buffer
323py-temp-directory\tdirectory used for temp files (if needed)
324py-beep-if-tab-change\tring the bell if tab-width is changed"
325 (interactive)
326 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000327 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000328 (setq major-mode 'python-mode
329 mode-name "Python"
330 local-abbrev-table python-mode-abbrev-table)
331 (use-local-map py-mode-map)
332 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000333 (mapcar (function (lambda (x)
334 (make-local-variable (car x))
335 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000336 '((paragraph-separate . "^[ \t]*$")
337 (paragraph-start . "^[ \t]*$")
338 (require-final-newline . t)
339 (comment-start . "# ")
340 (comment-start-skip . "# *")
341 (comment-column . 40)
342 (indent-region-function . py-indent-region)
343 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000344 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000345 ;;
346 ;; not sure where the magic comment has to be; to save time
347 ;; searching for a rarity, we give up if it's not found prior to the
348 ;; first executable statement.
349 ;;
350 ;; BAW - on first glance, this seems like complete hackery. Why was
351 ;; this necessary, and is it still necessary?
352 (let ((case-fold-search nil)
353 (start (point))
354 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355 (if (re-search-forward
356 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
357 (prog2 (py-next-statement 1) (point) (goto-char 1))
358 t)
359 (progn
360 (setq new-tab-width
361 (string-to-int
362 (buffer-substring (match-beginning 1) (match-end 1))))
363 (if (= tab-width new-tab-width)
364 nil
365 (setq tab-width new-tab-width)
366 (message "Caution: tab-width changed to %d" new-tab-width)
367 (if py-beep-if-tab-change (beep)))))
368 (goto-char start))
369
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000370 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000371 (if python-mode-hook
372 (run-hooks 'python-mode-hook)
373 (run-hooks 'py-mode-hook)))
374
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000375
Barry Warsawb91b7431995-03-14 15:55:20 +0000376;; electric characters
377(defun py-electric-colon (arg)
378 "Insert a colon.
379In certain cases the line is outdented appropriately. If a numeric
380argument is provided, that many colons are inserted non-electrically."
381 (interactive "P")
382 (self-insert-command (prefix-numeric-value arg))
383 (let (this-indent)
384 (if (and (not arg)
385 (save-excursion
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000386 (back-to-indentation)
387 (looking-at py-outdent-re))
Barry Warsawb91b7431995-03-14 15:55:20 +0000388 (= (setq this-indent (py-compute-indentation))
389 (save-excursion
390 (forward-line -1)
391 (py-compute-indentation)))
392 )
393 (save-excursion
394 (beginning-of-line)
395 (delete-horizontal-space)
396 (indent-to (- this-indent py-indent-offset)))
397 )))
398
399
Barry Warsaw7ae77681994-12-12 20:38:05 +0000400;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000401(defun py-shell ()
402 "Start an interactive Python interpreter in another window.
403This is like Shell mode, except that Python is running in the window
404instead of a shell. See the `Interactive Shell' and `Shell Mode'
405sections of the Emacs manual for details, especially for the key
406bindings active in the `*Python*' buffer.
407
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000408See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000409behavior in the process window.
410
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000411Warning: Don't use an interactive Python if you change sys.ps1 or
412sys.ps2 from their default values, or if you're running code that
413prints `>>> ' or `... ' at the start of a line. `python-mode' can't
414distinguish your output from Python's output, and assumes that `>>> '
415at the start of a line is a prompt from Python. Similarly, the Emacs
416Shell mode code assumes that both `>>> ' and `... ' at the start of a
417line are Python prompts. Bad things can happen if you fool either
418mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000419
420Warning: If you do any editing *in* the process buffer *while* the
421buffer is accepting output from Python, do NOT attempt to `undo' the
422changes. Some of the output (nowhere near the parts you changed!) may
423be lost if you do. This appears to be an Emacs bug, an unfortunate
424interaction between undo and process filters; the same problem exists in
425non-Python process buffers using the default (Emacs-supplied) process
426filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000427 ;; BAW - should undo be disabled in the python process buffer, if
428 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000429 (interactive)
430 (if py-this-is-emacs-19-p
431 (progn
432 (require 'comint)
433 (switch-to-buffer-other-window
434 (make-comint "Python" py-python-command)))
435 (progn
436 (require 'shell)
437 (switch-to-buffer-other-window
438 (make-shell "Python" py-python-command))))
439 (make-local-variable 'shell-prompt-pattern)
440 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
441 (set-process-filter (get-buffer-process (current-buffer))
442 'py-process-filter)
443 (set-syntax-table py-mode-syntax-table))
444
445(defun py-execute-region (start end)
446 "Send the region between START and END to a Python interpreter.
447If there is a *Python* process it is used.
448
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000449Hint: If you want to execute part of a Python file several times
450\(e.g., perhaps you're developing a function and want to flesh it out
451a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
452the region of interest, and send the code to a *Python* process via
453`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000454
455Following are subtleties to note when using a *Python* process:
456
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000457If a *Python* process is used, the region is copied into a temporary
458file (in directory `py-temp-directory'), and an `execfile' command is
459sent to Python naming that file. If you send regions faster than
460Python can execute them, `python-mode' will save them into distinct
461temp files, and execute the next one in the queue the next time it
462sees a `>>> ' prompt from Python. Each time this happens, the process
463buffer is popped into a window (if it's not already in some window) so
464you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000465
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000466 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000467
468is inserted at the end.
469
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000470Caution: No more than 26 regions can be pending at any given time.
471This limit is (indirectly) inherited from libc's mktemp(3).
472`python-mode' does not try to protect you from exceeding the limit.
473It's extremely unlikely that you'll get anywhere close to the limit in
474practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000475
476See the `\\[py-shell]' docs for additional warnings."
477 (interactive "r")
478 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000479 (let ((pyproc (get-process "Python"))
480 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000481 (if (null pyproc)
482 (shell-command-on-region start end py-python-command)
483 ;; else feed it thru a temp file
484 (setq fname (py-make-temp-name))
485 (write-region start end fname nil 'no-msg)
486 (setq py-file-queue (append py-file-queue (list fname)))
487 (if (cdr py-file-queue)
488 (message "File %s queued for execution" fname)
489 ;; else
490 (py-execute-file pyproc fname)))))
491
492(defun py-execute-file (pyproc fname)
493 (py-append-to-process-buffer
494 pyproc
495 (format "## working on region in file %s ...\n" fname))
496 (process-send-string pyproc (format "execfile('%s')\n" fname)))
497
498(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000499 (let ((curbuf (current-buffer))
500 (pbuf (process-buffer pyproc))
501 (pmark (process-mark pyproc))
502 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000503
504 ;; make sure we switch to a different buffer at least once. if we
505 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000506 ;; window, and point is before the end, and lots of output is
507 ;; coming at a fast pace, then (a) simple cursor-movement commands
508 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
509 ;; to have a visible effect (the window just doesn't get updated,
510 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
511 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000512 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000513 ;; #b makes no sense to me at all. #a almost makes sense: unless
514 ;; we actually change buffers, set_buffer_internal in buffer.c
515 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
516 ;; seems to make the Emacs command loop reluctant to update the
517 ;; display. Perhaps the default process filter in process.c's
518 ;; read_process_output has update_mode_lines++ for a similar
519 ;; reason? beats me ...
520
521 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000522 (if (eq curbuf pbuf) ; mysterious ugly hack
523 (set-buffer (get-buffer-create "*scratch*")))
524
525 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000526 (let* ((start (point))
527 (goback (< start pmark))
528 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000529 (goto-char pmark)
530 (insert string)
531 (move-marker pmark (point))
532 (setq file-finished
533 (and py-file-queue
534 (equal ">>> "
535 (buffer-substring
536 (prog2 (beginning-of-line) (point)
537 (goto-char pmark))
538 (point)))))
539 (if goback (goto-char start)
540 ;; else
541 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000542 (let* ((pop-up-windows t)
543 (pwin (display-buffer pbuf)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544 (set-window-point pwin (point))))))
545 (set-buffer curbuf)
546 (if file-finished
547 (progn
548 (py-delete-file-silently (car py-file-queue))
549 (setq py-file-queue (cdr py-file-queue))
550 (if py-file-queue
551 (py-execute-file pyproc (car py-file-queue)))))))
552
553(defun py-execute-buffer ()
554 "Send the contents of the buffer to a Python interpreter.
555If there is a *Python* process buffer it is used. If a clipping
556restriction is in effect, only the accessible portion of the buffer is
557sent. A trailing newline will be supplied if needed.
558
559See the `\\[py-execute-region]' docs for an account of some subtleties."
560 (interactive)
561 (py-execute-region (point-min) (point-max)))
562
563
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000564
565;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000566(defun py-delete-char ()
567 "Reduce indentation or delete character.
568If point is at the leftmost column, deletes the preceding newline.
569
570Else if point is at the leftmost non-blank character of a line that is
571neither a continuation line nor a non-indenting comment line, or if
572point is at the end of a blank line, reduces the indentation to match
573that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000574opened the block is displayed in the echo area to help you keep track
575of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576
577Else the preceding character is deleted, converting a tab to spaces if
578needed so that only a single column position is deleted."
579 (interactive "*")
580 (if (or (/= (current-indentation) (current-column))
581 (bolp)
582 (py-continuation-line-p)
583 (looking-at "#[^ \t\n]")) ; non-indenting #
584 (backward-delete-char-untabify 1)
585 ;; else indent the same as the colon line that opened the block
586
587 ;; force non-blank so py-goto-block-up doesn't ignore it
588 (insert-char ?* 1)
589 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000590 (let ((base-indent 0) ; indentation of base line
591 (base-text "") ; and text of base line
592 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000593 (condition-case nil ; in case no enclosing block
594 (save-excursion
595 (py-goto-block-up 'no-mark)
596 (setq base-indent (current-indentation)
597 base-text (py-suck-up-leading-text)
598 base-found-p t))
599 (error nil))
600 (delete-char 1) ; toss the dummy character
601 (delete-horizontal-space)
602 (indent-to base-indent)
603 (if base-found-p
604 (message "Closes block: %s" base-text)))))
605
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000606;; required for pending-del and delsel modes
607(put 'py-delete-char 'delete-selection 'supersede)
608(put 'py-delete-char 'pending-delete 'supersede)
609
Barry Warsaw7ae77681994-12-12 20:38:05 +0000610(defun py-indent-line ()
611 "Fix the indentation of the current line according to Python rules."
612 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000613 (let* ((ci (current-indentation))
614 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000615 (need (py-compute-indentation)))
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000616 ;; watch for outdents
617 (if (save-excursion
618 (back-to-indentation)
619 (looking-at py-outdent-re))
620 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000621 (if (/= ci need)
622 (save-excursion
623 (beginning-of-line)
624 (delete-horizontal-space)
625 (indent-to need)))
626 (if move-to-indentation-p (back-to-indentation))))
627
628(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000629 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630This is just `strives to' because correct indentation can't be computed
631from scratch for Python code. In general, deletes the whitespace before
632point, inserts a newline, and takes an educated guess as to how you want
633the new line indented."
634 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000635 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000636 (if (< ci (current-column)) ; if point beyond indentation
637 (newline-and-indent)
638 ;; else try to act like newline-and-indent "normally" acts
639 (beginning-of-line)
640 (insert-char ?\n 1)
641 (move-to-column ci))))
642
643(defun py-compute-indentation ()
644 (save-excursion
645 (beginning-of-line)
646 (cond
647 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000648 ((py-continuation-line-p)
649 (let ((startpos (point))
650 (open-bracket-pos (py-nesting-level))
651 endpos searching found)
652 (if open-bracket-pos
653 (progn
654 ;; align with first item in list; else a normal
655 ;; indent beyond the line with the open bracket
656 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
657 ;; is the first list item on the same line?
658 (skip-chars-forward " \t")
659 (if (null (memq (following-char) '(?\n ?# ?\\)))
660 ; yes, so line up with it
661 (current-column)
662 ;; first list item on another line, or doesn't exist yet
663 (forward-line 1)
664 (while (and (< (point) startpos)
665 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
666 (forward-line 1))
667 (if (< (point) startpos)
668 ;; again mimic the first list item
669 (current-indentation)
670 ;; else they're about to enter the first item
671 (goto-char open-bracket-pos)
672 (+ (current-indentation) py-indent-offset))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000673
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000674 ;; else on backslash continuation line
675 (forward-line -1)
676 (if (py-continuation-line-p) ; on at least 3rd line in block
677 (current-indentation) ; so just continue the pattern
678 ;; else started on 2nd line in block, so indent more.
679 ;; if base line is an assignment with a start on a RHS,
680 ;; indent to 2 beyond the leftmost "="; else skip first
681 ;; chunk of non-whitespace characters on base line, + 1 more
682 ;; column
683 (end-of-line)
684 (setq endpos (point) searching t)
685 (back-to-indentation)
686 (setq startpos (point))
687 ;; look at all "=" from left to right, stopping at first
688 ;; one not nested in a list or string
689 (while searching
690 (skip-chars-forward "^=" endpos)
691 (if (= (point) endpos)
692 (setq searching nil)
693 (forward-char 1)
694 (setq state (parse-partial-sexp startpos (point)))
695 (if (and (zerop (car state)) ; not in a bracket
696 (null (nth 3 state))) ; & not in a string
697 (progn
698 (setq searching nil) ; done searching in any case
699 (setq found
700 (not (or
701 (eq (following-char) ?=)
702 (memq (char-after (- (point) 2))
703 '(?< ?> ?!)))))))))
704 (if (or (not found) ; not an assignment
705 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
706 (progn
707 (goto-char startpos)
708 (skip-chars-forward "^ \t\n")))
709 (1+ (current-column))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000710
711 ;; not on a continuation line
712
713 ;; if at start of restriction, or on a non-indenting comment line,
714 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000715 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
716 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000717
718 ;; else indentation based on that of the statement that precedes
719 ;; us; use the first line of that statement to establish the base,
720 ;; in case the user forced a non-std indentation for the
721 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000722 (t
723 ;; skip back over blank & non-indenting comment lines
724 ;; note: will skip a blank or non-indenting comment line that
725 ;; happens to be a continuation line too
726 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
727 nil 'move)
728 ;; if we landed inside a string, go to the beginning of that
729 ;; string. this handles triple quoted, multi-line spanning
730 ;; strings.
731 (let ((state (parse-partial-sexp
732 (save-excursion (beginning-of-python-def-or-class)
733 (point))
734 (point))))
735 (if (nth 3 state)
736 (goto-char (nth 2 state))))
737 (py-goto-initial-line)
738 (if (py-statement-opens-block-p)
739 (+ (current-indentation) py-indent-offset)
740 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000741
742(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000743 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000745`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000747`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748their own buffer-local copy), both those currently existing and those
749created later in the Emacs session.
750
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000751Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000752There's no excuse for such foolishness, but sometimes you have to deal
753with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000754`py-indent-offset' to what it thinks it was when they created the
755mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000756
757Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000758looking for a line that opens a block of code. `py-indent-offset' is
759set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000760statement following it. If the search doesn't succeed going forward,
761it's tried again going backward."
762 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000763 (let (new-value
764 (start (point))
765 restart
766 (found nil)
767 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000768 (py-goto-initial-line)
769 (while (not (or found (eobp)))
770 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
771 (progn
772 (setq restart (point))
773 (py-goto-initial-line)
774 (if (py-statement-opens-block-p)
775 (setq found t)
776 (goto-char restart)))))
777 (if found
778 ()
779 (goto-char start)
780 (py-goto-initial-line)
781 (while (not (or found (bobp)))
782 (setq found
783 (and
784 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
785 (or (py-goto-initial-line) t) ; always true -- side effect
786 (py-statement-opens-block-p)))))
787 (setq colon-indent (current-indentation)
788 found (and found (zerop (py-next-statement 1)))
789 new-value (- (current-indentation) colon-indent))
790 (goto-char start)
791 (if found
792 (progn
793 (funcall (if global 'kill-local-variable 'make-local-variable)
794 'py-indent-offset)
795 (setq py-indent-offset new-value)
796 (message "%s value of py-indent-offset set to %d"
797 (if global "Global" "Local")
798 py-indent-offset))
799 (error "Sorry, couldn't guess a value for py-indent-offset"))))
800
801(defun py-shift-region (start end count)
802 (save-excursion
803 (goto-char end) (beginning-of-line) (setq end (point))
804 (goto-char start) (beginning-of-line) (setq start (point))
805 (indent-rigidly start end count)))
806
807(defun py-shift-region-left (start end &optional count)
808 "Shift region of Python code to the left.
809The lines from the line containing the start of the current region up
810to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000811shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000812
813If a prefix argument is given, the region is instead shifted by that
814many columns."
815 (interactive "*r\nP") ; region; raw prefix arg
816 (py-shift-region start end
817 (- (prefix-numeric-value
818 (or count py-indent-offset)))))
819
820(defun py-shift-region-right (start end &optional count)
821 "Shift region of Python code to the right.
822The lines from the line containing the start of the current region up
823to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000824shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000825
826If a prefix argument is given, the region is instead shifted by that
827many columns."
828 (interactive "*r\nP") ; region; raw prefix arg
829 (py-shift-region start end (prefix-numeric-value
830 (or count py-indent-offset))))
831
832(defun py-indent-region (start end &optional indent-offset)
833 "Reindent a region of Python code.
834The lines from the line containing the start of the current region up
835to (but not including) the line containing the end of the region are
836reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000837character in the first column, the first line is left alone and the
838rest of the region is reindented with respect to it. Else the entire
839region is reindented with respect to the (closest code or
840indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000841
842This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000843control structures are introduced or removed, or to reformat code
844using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000845
846If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000847the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000848used.
849
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000850Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000851is called! This function does not compute proper indentation from
852scratch (that's impossible in Python), it merely adjusts the existing
853indentation to be correct in context.
854
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000855Warning: This function really has no idea what to do with
856non-indenting comment lines, and shifts them as if they were indenting
857comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000858
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000859Special cases: whitespace is deleted from blank lines; continuation
860lines are shifted by the same amount their initial line was shifted,
861in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000862initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000863 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000864 (save-excursion
865 (goto-char end) (beginning-of-line) (setq end (point-marker))
866 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000867 (let ((py-indent-offset (prefix-numeric-value
868 (or indent-offset py-indent-offset)))
869 (indents '(-1)) ; stack of active indent levels
870 (target-column 0) ; column to which to indent
871 (base-shifted-by 0) ; amount last base line was shifted
872 (indent-base (if (looking-at "[ \t\n]")
873 (py-compute-indentation)
874 0))
875 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876 (while (< (point) end)
877 (setq ci (current-indentation))
878 ;; figure out appropriate target column
879 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000880 ((or (eq (following-char) ?#) ; comment in column 1
881 (looking-at "[ \t]*$")) ; entirely blank
882 (setq target-column 0))
883 ((py-continuation-line-p) ; shift relative to base line
884 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000885 (t ; new base line
886 (if (> ci (car indents)) ; going deeper; push it
887 (setq indents (cons ci indents))
888 ;; else we should have seen this indent before
889 (setq indents (memq ci indents)) ; pop deeper indents
890 (if (null indents)
891 (error "Bad indentation in region, at line %d"
892 (save-restriction
893 (widen)
894 (1+ (count-lines 1 (point)))))))
895 (setq target-column (+ indent-base
896 (* py-indent-offset
897 (- (length indents) 2))))
898 (setq base-shifted-by (- target-column ci))))
899 ;; shift as needed
900 (if (/= ci target-column)
901 (progn
902 (delete-horizontal-space)
903 (indent-to target-column)))
904 (forward-line 1))))
905 (set-marker end nil))
906
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000907
908;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909(defun py-previous-statement (count)
910 "Go to the start of previous Python statement.
911If the statement at point is the i'th Python statement, goes to the
912start of statement i-COUNT. If there is no such statement, goes to the
913first statement. Returns count of statements left to move.
914`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000915 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916 (if (< count 0) (py-next-statement (- count))
917 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000918 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000919 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000921 (> count 0)
922 (zerop (forward-line -1))
923 (py-goto-statement-at-or-above))
924 (setq count (1- count)))
925 (if (> count 0) (goto-char start)))
926 count))
927
928(defun py-next-statement (count)
929 "Go to the start of next Python statement.
930If the statement at point is the i'th Python statement, goes to the
931start of statement i+COUNT. If there is no such statement, goes to the
932last statement. Returns count of statements left to move. `Statements'
933do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000934 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935 (if (< count 0) (py-previous-statement (- count))
936 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000937 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000938 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000939 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940 (> count 0)
941 (py-goto-statement-below))
942 (setq count (1- count)))
943 (if (> count 0) (goto-char start)))
944 count))
945
946(defun py-goto-block-up (&optional nomark)
947 "Move up to start of current block.
948Go to the statement that starts the smallest enclosing block; roughly
949speaking, this will be the closest preceding statement that ends with a
950colon and is indented less than the statement you started on. If
951successful, also sets the mark to the starting point.
952
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000953`\\[py-mark-block]' can be used afterward to mark the whole code
954block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000955
956If called from a program, the mark will not be set if optional argument
957NOMARK is not nil."
958 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000959 (let ((start (point))
960 (found nil)
961 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000962 (py-goto-initial-line)
963 ;; if on blank or non-indenting comment line, use the preceding stmt
964 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
965 (progn
966 (py-goto-statement-at-or-above)
967 (setq found (py-statement-opens-block-p))))
968 ;; search back for colon line indented less
969 (setq initial-indent (current-indentation))
970 (if (zerop initial-indent)
971 ;; force fast exit
972 (goto-char (point-min)))
973 (while (not (or found (bobp)))
974 (setq found
975 (and
976 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
977 (or (py-goto-initial-line) t) ; always true -- side effect
978 (< (current-indentation) initial-indent)
979 (py-statement-opens-block-p))))
980 (if found
981 (progn
982 (or nomark (push-mark start))
983 (back-to-indentation))
984 (goto-char start)
985 (error "Enclosing block not found"))))
986
987(defun beginning-of-python-def-or-class (&optional class)
988 "Move point to start of def (or class, with prefix arg).
989
990Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000991arg, looks for a `class' instead. The docs assume the `def' case;
992just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000993
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994If point is in a def statement already, and after the `d', simply
995moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000997Else (point is not in a def statement, or at or before the `d' of a
998def statement), searches for the closest preceding def statement, and
999leaves point at its start. If no such statement can be found, leaves
1000point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001001
1002Returns t iff a def statement is found by these rules.
1003
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001004Note that doing this command repeatedly will take you closer to the
1005start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007If you want to mark the current def/class, see
1008`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001009 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001010 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1011 (start-of-line (progn (beginning-of-line) (point)))
1012 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013 (if (or (/= start-of-stmt start-of-line)
1014 (not at-or-before-p))
1015 (end-of-line)) ; OK to match on this line
1016 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001017 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018
1019(defun end-of-python-def-or-class (&optional class)
1020 "Move point beyond end of def (or class, with prefix arg) body.
1021
1022By default, looks for an appropriate `def'. If you supply a prefix arg,
1023looks for a `class' instead. The docs assume the `def' case; just
1024substitute `class' for `def' for the other case.
1025
1026If point is in a def statement already, this is the def we use.
1027
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028Else if the def found by `\\[beginning-of-python-def-or-class]'
1029contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030
1031Else we search forward for the closest following def, and use that.
1032
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001033If a def can be found by these rules, point is moved to the start of
1034the line immediately following the def block, and the position of the
1035start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001036
1037Else point is moved to the end of the buffer, and nil is returned.
1038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001039Note that doing this command repeatedly will take you closer to the
1040end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001042If you want to mark the current def/class, see
1043`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001044 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001045 (let ((start (progn (py-goto-initial-line) (point)))
1046 (which (if class "class" "def"))
1047 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001048 ;; move point to start of appropriate def/class
1049 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1050 (setq state 'at-beginning)
1051 ;; else see if beginning-of-python-def-or-class hits container
1052 (if (and (beginning-of-python-def-or-class class)
1053 (progn (py-goto-beyond-block)
1054 (> (point) start)))
1055 (setq state 'at-end)
1056 ;; else search forward
1057 (goto-char start)
1058 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1059 (progn (setq state 'at-beginning)
1060 (beginning-of-line)))))
1061 (cond
1062 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1063 ((eq state 'at-end) t)
1064 ((eq state 'not-found) nil)
1065 (t (error "internal error in end-of-python-def-or-class")))))
1066
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001067
1068;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001069(defun py-mark-block (&optional extend just-move)
1070 "Mark following block of lines. With prefix arg, mark structure.
1071Easier to use than explain. It sets the region to an `interesting'
1072block of succeeding lines. If point is on a blank line, it goes down to
1073the next non-blank line. That will be the start of the region. The end
1074of the region depends on the kind of line at the start:
1075
1076 - If a comment, the region will include all succeeding comment lines up
1077 to (but not including) the next non-comment line (if any).
1078
1079 - Else if a prefix arg is given, and the line begins one of these
1080 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001081
1082 if elif else try except finally for while def class
1083
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 the region will be set to the body of the structure, including
1085 following blocks that `belong' to it, but excluding trailing blank
1086 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001087 and all (if any) of the following `except' and `finally' blocks
1088 that belong to the `try' structure will be in the region. Ditto
1089 for if/elif/else, for/else and while/else structures, and (a bit
1090 degenerate, since they're always one-block structures) def and
1091 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092
1093 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094 block (see list above), and the block is not a `one-liner' (i.e.,
1095 the statement ends with a colon, not with code), the region will
1096 include all succeeding lines up to (but not including) the next
1097 code statement (if any) that's indented no more than the starting
1098 line, except that trailing blank and comment lines are excluded.
1099 E.g., if the starting line begins a multi-statement `def'
1100 structure, the region will be set to the full function definition,
1101 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001102
1103 - Else the region will include all succeeding lines up to (but not
1104 including) the next blank line, or code or indenting-comment line
1105 indented strictly less than the starting line. Trailing indenting
1106 comment lines are included in this case, but not trailing blank
1107 lines.
1108
1109A msg identifying the location of the mark is displayed in the echo
1110area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1111
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001112If called from a program, optional argument EXTEND plays the role of
1113the prefix arg, and if optional argument JUST-MOVE is not nil, just
1114moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115 (interactive "P") ; raw prefix arg
1116 (py-goto-initial-line)
1117 ;; skip over blank lines
1118 (while (and
1119 (looking-at "[ \t]*$") ; while blank line
1120 (not (eobp))) ; & somewhere to go
1121 (forward-line 1))
1122 (if (eobp)
1123 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001124 (let ((initial-pos (point))
1125 (initial-indent (current-indentation))
1126 last-pos ; position of last stmt in region
1127 (followers
1128 '((if elif else) (elif elif else) (else)
1129 (try except finally) (except except) (finally)
1130 (for else) (while else)
1131 (def) (class) ) )
1132 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001133
1134 (cond
1135 ;; if comment line, suck up the following comment lines
1136 ((looking-at "[ \t]*#")
1137 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1138 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1139 (setq last-pos (point)))
1140
1141 ;; else if line is a block line and EXTEND given, suck up
1142 ;; the whole structure
1143 ((and extend
1144 (setq first-symbol (py-suck-up-first-keyword) )
1145 (assq first-symbol followers))
1146 (while (and
1147 (or (py-goto-beyond-block) t) ; side effect
1148 (forward-line -1) ; side effect
1149 (setq last-pos (point)) ; side effect
1150 (py-goto-statement-below)
1151 (= (current-indentation) initial-indent)
1152 (setq next-symbol (py-suck-up-first-keyword))
1153 (memq next-symbol (cdr (assq first-symbol followers))))
1154 (setq first-symbol next-symbol)))
1155
1156 ;; else if line *opens* a block, search for next stmt indented <=
1157 ((py-statement-opens-block-p)
1158 (while (and
1159 (setq last-pos (point)) ; always true -- side effect
1160 (py-goto-statement-below)
1161 (> (current-indentation) initial-indent))
1162 nil))
1163
1164 ;; else plain code line; stop at next blank line, or stmt or
1165 ;; indenting comment line indented <
1166 (t
1167 (while (and
1168 (setq last-pos (point)) ; always true -- side effect
1169 (or (py-goto-beyond-final-line) t)
1170 (not (looking-at "[ \t]*$")) ; stop at blank line
1171 (or
1172 (>= (current-indentation) initial-indent)
1173 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1174 nil)))
1175
1176 ;; skip to end of last stmt
1177 (goto-char last-pos)
1178 (py-goto-beyond-final-line)
1179
1180 ;; set mark & display
1181 (if just-move
1182 () ; just return
1183 (push-mark (point) 'no-msg)
1184 (forward-line -1)
1185 (message "Mark set after: %s" (py-suck-up-leading-text))
1186 (goto-char initial-pos))))
1187
1188(defun mark-python-def-or-class (&optional class)
1189 "Set region to body of def (or class, with prefix arg) enclosing point.
1190Pushes the current mark, then point, on the mark ring (all language
1191modes do this, but although it's handy it's never documented ...).
1192
1193In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001194hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1195`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001196
1197And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198Turned out that was more confusing than useful: the `goto start' and
1199`goto end' commands are usually used to search through a file, and
1200people expect them to act a lot like `search backward' and `search
1201forward' string-search commands. But because Python `def' and `class'
1202can nest to arbitrary levels, finding the smallest def containing
1203point cannot be done via a simple backward search: the def containing
1204point may not be the closest preceding def, or even the closest
1205preceding def that's indented less. The fancy algorithm required is
1206appropriate for the usual uses of this `mark' command, but not for the
1207`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001208
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001209So the def marked by this command may not be the one either of the
1210`goto' commands find: If point is on a blank or non-indenting comment
1211line, moves back to start of the closest preceding code statement or
1212indenting comment line. If this is a `def' statement, that's the def
1213we use. Else searches for the smallest enclosing `def' block and uses
1214that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001215
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001216When an enclosing def is found: The mark is left immediately beyond
1217the last line of the def block. Point is left at the start of the
1218def, except that: if the def is preceded by a number of comment lines
1219followed by (at most) one optional blank line, point is left at the
1220start of the comments; else if the def is preceded by a blank line,
1221point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001222
1223The intent is to mark the containing def/class and its associated
1224documentation, to make moving and duplicating functions and classes
1225pleasant."
1226 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001227 (let ((start (point))
1228 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001229 (push-mark start)
1230 (if (not (py-go-up-tree-to-keyword which))
1231 (progn (goto-char start)
1232 (error "Enclosing %s not found" which))
1233 ;; else enclosing def/class found
1234 (setq start (point))
1235 (py-goto-beyond-block)
1236 (push-mark (point))
1237 (goto-char start)
1238 (if (zerop (forward-line -1)) ; if there is a preceding line
1239 (progn
1240 (if (looking-at "[ \t]*$") ; it's blank
1241 (setq start (point)) ; so reset start point
1242 (goto-char start)) ; else try again
1243 (if (zerop (forward-line -1))
1244 (if (looking-at "[ \t]*#") ; a comment
1245 ;; look back for non-comment line
1246 ;; tricky: note that the regexp matches a blank
1247 ;; line, cuz \n is in the 2nd character class
1248 (and
1249 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1250 (forward-line 1))
1251 ;; no comment, so go back
1252 (goto-char start))))))))
1253
1254(defun py-comment-region (start end &optional uncomment-p)
1255 "Comment out region of code; with prefix arg, uncomment region.
1256The lines from the line containing the start of the current region up
1257to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001258commented out, by inserting the string `py-block-comment-prefix' at
1259the start of each line. With a prefix arg, removes
1260`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001261 (interactive "*r\nP") ; region; raw prefix arg
1262 (goto-char end) (beginning-of-line) (setq end (point))
1263 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001264 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001265 (save-excursion
1266 (save-restriction
1267 (narrow-to-region start end)
1268 (while (not (eobp))
1269 (if uncomment-p
1270 (and (string= py-block-comment-prefix
1271 (buffer-substring
1272 (point) (+ (point) prefix-len)))
1273 (delete-char prefix-len))
1274 (insert py-block-comment-prefix))
1275 (forward-line 1))))))
1276
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001277
1278;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001279
1280;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1282;; out of the right places, along with the keys they're on & current
1283;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001284(defun py-dump-help-string (str)
1285 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001286 (let ((locals (buffer-local-variables))
1287 funckind funcname func funcdoc
1288 (start 0) mstart end
1289 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1291 (setq mstart (match-beginning 0) end (match-end 0)
1292 funckind (substring str (match-beginning 1) (match-end 1))
1293 funcname (substring str (match-beginning 2) (match-end 2))
1294 func (intern funcname))
1295 (princ (substitute-command-keys (substring str start mstart)))
1296 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001297 ((equal funckind "c") ; command
1298 (setq funcdoc (documentation func)
1299 keys (concat
1300 "Key(s): "
1301 (mapconcat 'key-description
1302 (where-is-internal func py-mode-map)
1303 ", "))))
1304 ((equal funckind "v") ; variable
1305 (setq funcdoc (substitute-command-keys
1306 (get func 'variable-documentation))
1307 keys (if (assq func locals)
1308 (concat
1309 "Local/Global values: "
1310 (prin1-to-string (symbol-value func))
1311 " / "
1312 (prin1-to-string (default-value func)))
1313 (concat
1314 "Value: "
1315 (prin1-to-string (symbol-value func))))))
1316 (t ; unexpected
1317 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001318 (princ (format "\n-> %s:\t%s\t%s\n\n"
1319 (if (equal funckind "c") "Command" "Variable")
1320 funcname keys))
1321 (princ funcdoc)
1322 (terpri)
1323 (setq start end))
1324 (princ (substitute-command-keys (substring str start))))
1325 (print-help-return-message)))
1326
1327(defun py-describe-mode ()
1328 "Dump long form of Python-mode docs."
1329 (interactive)
1330 (py-dump-help-string "Major mode for editing Python files.
1331Knows about Python indentation, tokens, comments and continuation lines.
1332Paragraphs are separated by blank lines only.
1333
1334Major sections below begin with the string `@'; specific function and
1335variable docs begin with `->'.
1336
1337@EXECUTING PYTHON CODE
1338
1339\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1340\\[py-execute-region]\tsends the current region
1341\\[py-shell]\tstarts a Python interpreter window; this will be used by
1342\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1343%c:py-execute-buffer
1344%c:py-execute-region
1345%c:py-shell
1346
1347@VARIABLES
1348
1349py-indent-offset\tindentation increment
1350py-block-comment-prefix\tcomment string used by py-comment-region
1351
1352py-python-command\tshell command to invoke Python interpreter
1353py-scroll-process-buffer\talways scroll Python process buffer
1354py-temp-directory\tdirectory used for temp files (if needed)
1355
1356py-beep-if-tab-change\tring the bell if tab-width is changed
1357%v:py-indent-offset
1358%v:py-block-comment-prefix
1359%v:py-python-command
1360%v:py-scroll-process-buffer
1361%v:py-temp-directory
1362%v:py-beep-if-tab-change
1363
1364@KINDS OF LINES
1365
1366Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001367preceding line ends with a backslash that's not part of a comment, or
1368the paren/bracket/brace nesting level at the start of the line is
1369non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001370
1371An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001372possibly blanks or tabs), a `comment line' (leftmost non-blank
1373character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001374
1375Comment Lines
1376
1377Although all comment lines are treated alike by Python, Python mode
1378recognizes two kinds that act differently with respect to indentation.
1379
1380An `indenting comment line' is a comment line with a blank, tab or
1381nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001382treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001383indenting comment line will be indented like the comment line. All
1384other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001385following the initial `#') are `non-indenting comment lines', and
1386their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001387
1388Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001389whenever possible. Non-indenting comment lines are useful in cases
1390like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001391
1392\ta = b # a very wordy single-line comment that ends up being
1393\t #... continued onto another line
1394
1395\tif a == b:
1396##\t\tprint 'panic!' # old code we've `commented out'
1397\t\treturn a
1398
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001399Since the `#...' and `##' comment lines have a non-whitespace
1400character following the initial `#', Python mode ignores them when
1401computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001402
1403Continuation Lines and Statements
1404
1405The Python-mode commands generally work on statements instead of on
1406individual lines, where a `statement' is a comment or blank line, or a
1407code line and all of its following continuation lines (if any)
1408considered as a single logical unit. The commands in this mode
1409generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001410statement containing point, even if point happens to be in the middle
1411of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001412
1413
1414@INDENTATION
1415
1416Primarily for entering new code:
1417\t\\[indent-for-tab-command]\t indent line appropriately
1418\t\\[py-newline-and-indent]\t insert newline, then indent
1419\t\\[py-delete-char]\t reduce indentation, or delete single character
1420
1421Primarily for reindenting existing code:
1422\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1423\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1424
1425\t\\[py-indent-region]\t reindent region to match its context
1426\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1427\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1428
1429Unlike most programming languages, Python uses indentation, and only
1430indentation, to specify block structure. Hence the indentation supplied
1431automatically by Python-mode is just an educated guess: only you know
1432the block structure you intend, so only you can supply correct
1433indentation.
1434
1435The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1436the indentation of preceding statements. E.g., assuming
1437py-indent-offset is 4, after you enter
1438\tif a > 0: \\[py-newline-and-indent]
1439the cursor will be moved to the position of the `_' (_ is not a
1440character in the file, it's just used here to indicate the location of
1441the cursor):
1442\tif a > 0:
1443\t _
1444If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1445to
1446\tif a > 0:
1447\t c = d
1448\t _
1449Python-mode cannot know whether that's what you intended, or whether
1450\tif a > 0:
1451\t c = d
1452\t_
1453was your intent. In general, Python-mode either reproduces the
1454indentation of the (closest code or indenting-comment) preceding
1455statement, or adds an extra py-indent-offset blanks if the preceding
1456statement has `:' as its last significant (non-whitespace and non-
1457comment) character. If the suggested indentation is too much, use
1458\\[py-delete-char] to reduce it.
1459
1460Continuation lines are given extra indentation. If you don't like the
1461suggested indentation, change it to something you do like, and Python-
1462mode will strive to indent later lines of the statement in the same way.
1463
1464If a line is a continuation line by virtue of being in an unclosed
1465paren/bracket/brace structure (`list', for short), the suggested
1466indentation depends on whether the current line contains the first item
1467in the list. If it does, it's indented py-indent-offset columns beyond
1468the indentation of the line containing the open bracket. If you don't
1469like that, change it by hand. The remaining items in the list will mimic
1470whatever indentation you give to the first item.
1471
1472If a line is a continuation line because the line preceding it ends with
1473a backslash, the third and following lines of the statement inherit their
1474indentation from the line preceding them. The indentation of the second
1475line in the statement depends on the form of the first (base) line: if
1476the base line is an assignment statement with anything more interesting
1477than the backslash following the leftmost assigning `=', the second line
1478is indented two columns beyond that `='. Else it's indented to two
1479columns beyond the leftmost solid chunk of non-whitespace characters on
1480the base line.
1481
1482Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1483repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1484structure you intend.
1485%c:indent-for-tab-command
1486%c:py-newline-and-indent
1487%c:py-delete-char
1488
1489
1490The next function may be handy when editing code you didn't write:
1491%c:py-guess-indent-offset
1492
1493
1494The remaining `indent' functions apply to a region of Python code. They
1495assume the block structure (equals indentation, in Python) of the region
1496is correct, and alter the indentation in various ways while preserving
1497the block structure:
1498%c:py-indent-region
1499%c:py-shift-region-left
1500%c:py-shift-region-right
1501
1502@MARKING & MANIPULATING REGIONS OF CODE
1503
1504\\[py-mark-block]\t mark block of lines
1505\\[mark-python-def-or-class]\t mark smallest enclosing def
1506\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1507\\[py-comment-region]\t comment out region of code
1508\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1509%c:py-mark-block
1510%c:mark-python-def-or-class
1511%c:py-comment-region
1512
1513@MOVING POINT
1514
1515\\[py-previous-statement]\t move to statement preceding point
1516\\[py-next-statement]\t move to statement following point
1517\\[py-goto-block-up]\t move up to start of current block
1518\\[beginning-of-python-def-or-class]\t move to start of def
1519\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1520\\[end-of-python-def-or-class]\t move to end of def
1521\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1522
1523The first two move to one statement beyond the statement that contains
1524point. A numeric prefix argument tells them to move that many
1525statements instead. Blank lines, comment lines, and continuation lines
1526do not count as `statements' for these commands. So, e.g., you can go
1527to the first code statement in a file by entering
1528\t\\[beginning-of-buffer]\t to move to the top of the file
1529\t\\[py-next-statement]\t to skip over initial comments and blank lines
1530Or do `\\[py-previous-statement]' with a huge prefix argument.
1531%c:py-previous-statement
1532%c:py-next-statement
1533%c:py-goto-block-up
1534%c:beginning-of-python-def-or-class
1535%c:end-of-python-def-or-class
1536
1537@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1538
1539`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1540
1541`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1542overall class and def structure of a module.
1543
1544`\\[back-to-indentation]' moves point to a line's first non-blank character.
1545
1546`\\[indent-relative]' is handy for creating odd indentation.
1547
1548@OTHER EMACS HINTS
1549
1550If you don't like the default value of a variable, change its value to
1551whatever you do like by putting a `setq' line in your .emacs file.
1552E.g., to set the indentation increment to 4, put this line in your
1553.emacs:
1554\t(setq py-indent-offset 4)
1555To see the value of a variable, do `\\[describe-variable]' and enter the variable
1556name at the prompt.
1557
1558When entering a key sequence like `C-c C-n', it is not necessary to
1559release the CONTROL key after doing the `C-c' part -- it suffices to
1560press the CONTROL key, press and release `c' (while still holding down
1561CONTROL), press and release `n' (while still holding down CONTROL), &
1562then release CONTROL.
1563
1564Entering Python mode calls with no arguments the value of the variable
1565`python-mode-hook', if that value exists and is not nil; for backward
1566compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1567the Elisp manual for details.
1568
1569Obscure: When python-mode is first loaded, it looks for all bindings
1570to newline-and-indent in the global keymap, and shadows them with
1571local bindings to py-newline-and-indent."))
1572
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573
1574;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001575(defvar py-parse-state-re
1576 (concat
1577 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1578 "\\|"
1579 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581;; returns the parse state at point (see parse-partial-sexp docs)
1582(defun py-parse-state ()
1583 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001584 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001585 ;; back up to the first preceding line (if any; else start of
1586 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001587 ;; whitespace and non-comment character. These are good places
1588 ;; to start parsing to see whether where we started is at a
1589 ;; non-zero nesting level. It may be slow for people who write
1590 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001591 (re-search-backward py-parse-state-re nil 'move)
1592 (beginning-of-line)
1593 (parse-partial-sexp (point) here))))
1594
1595;; if point is at a non-zero nesting level, returns the number of the
1596;; character that opens the smallest enclosing unclosed list; else
1597;; returns nil.
1598(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001599 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600 (if (zerop (car status))
1601 nil ; not in a nest
1602 (car (cdr status))))) ; char# of open bracket
1603
1604;; t iff preceding line ends with backslash that's not in a comment
1605(defun py-backslash-continuation-line-p ()
1606 (save-excursion
1607 (beginning-of-line)
1608 (and
1609 ;; use a cheap test first to avoid the regexp if possible
1610 ;; use 'eq' because char-after may return nil
1611 (eq (char-after (- (point) 2)) ?\\ )
1612 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001613 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001614 (looking-at py-continued-re))))
1615
1616;; t iff current line is a continuation line
1617(defun py-continuation-line-p ()
1618 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001619 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001620 (or (py-backslash-continuation-line-p)
1621 (py-nesting-level))))
1622
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001623;; go to initial line of current statement; usually this is the line
1624;; we're on, but if we're on the 2nd or following lines of a
1625;; continuation block, we need to go up to the first line of the
1626;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001627;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628;; Tricky: We want to avoid quadratic-time behavior for long continued
1629;; blocks, whether of the backslash or open-bracket varieties, or a
1630;; mix of the two. The following manages to do that in the usual
1631;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632(defun py-goto-initial-line ()
1633 (let ( open-bracket-pos )
1634 (while (py-continuation-line-p)
1635 (beginning-of-line)
1636 (if (py-backslash-continuation-line-p)
1637 (while (py-backslash-continuation-line-p)
1638 (forward-line -1))
1639 ;; else zip out of nested brackets/braces/parens
1640 (while (setq open-bracket-pos (py-nesting-level))
1641 (goto-char open-bracket-pos)))))
1642 (beginning-of-line))
1643
1644;; go to point right beyond final line of current statement; usually
1645;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001646;; statement we need to skip over the continuation lines. Tricky:
1647;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001648(defun py-goto-beyond-final-line ()
1649 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001650 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001651 (while (and (py-continuation-line-p)
1652 (not (eobp)))
1653 ;; skip over the backslash flavor
1654 (while (and (py-backslash-continuation-line-p)
1655 (not (eobp)))
1656 (forward-line 1))
1657 ;; if in nest, zip to the end of the nest
1658 (setq state (py-parse-state))
1659 (if (and (not (zerop (car state)))
1660 (not (eobp)))
1661 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663 ;; the 3rd argument should be plain 0
1664 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1665 nil state)
1666 (forward-line 1))))))
1667
1668;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001670(defun py-statement-opens-block-p ()
1671 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001672 (let ((start (point))
1673 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1674 (searching t)
1675 (answer nil)
1676 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001677 (goto-char start)
1678 (while searching
1679 ;; look for a colon with nothing after it except whitespace, and
1680 ;; maybe a comment
1681 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1682 finish t)
1683 (if (eq (point) finish) ; note: no `else' clause; just
1684 ; keep searching if we're not at
1685 ; the end yet
1686 ;; sure looks like it opens a block -- but it might
1687 ;; be in a comment
1688 (progn
1689 (setq searching nil) ; search is done either way
1690 (setq state (parse-partial-sexp start
1691 (match-beginning 0)))
1692 (setq answer (not (nth 4 state)))))
1693 ;; search failed: couldn't find another interesting colon
1694 (setq searching nil)))
1695 answer)))
1696
1697;; go to point right beyond final line of block begun by the current
1698;; line. This is the same as where py-goto-beyond-final-line goes
1699;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001700;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001701(defun py-goto-beyond-block ()
1702 (if (py-statement-opens-block-p)
1703 (py-mark-block nil 'just-move)
1704 (py-goto-beyond-final-line)))
1705
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001706;; go to start of first statement (not blank or comment or
1707;; continuation line) at or preceding point. returns t if there is
1708;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001709(defun py-goto-statement-at-or-above ()
1710 (py-goto-initial-line)
1711 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712 ;; skip back over blank & comment lines
1713 ;; note: will skip a blank or comment line that happens to be
1714 ;; a continuation line too
1715 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1716 (progn (py-goto-initial-line) t)
1717 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718 t))
1719
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001720;; go to start of first statement (not blank or comment or
1721;; continuation line) following the statement containing point returns
1722;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723(defun py-goto-statement-below ()
1724 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001725 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001726 (py-goto-beyond-final-line)
1727 (while (and
1728 (looking-at py-blank-or-comment-re)
1729 (not (eobp)))
1730 (forward-line 1))
1731 (if (eobp)
1732 (progn (goto-char start) nil)
1733 t)))
1734
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001735;; go to start of statement, at or preceding point, starting with
1736;; keyword KEY. Skips blank lines and non-indenting comments upward
1737;; first. If that statement starts with KEY, done, else go back to
1738;; first enclosing block starting with KEY. If successful, leaves
1739;; point at the start of the KEY line & returns t. Else leaves point
1740;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001741(defun py-go-up-tree-to-keyword (key)
1742 ;; skip blanks and non-indenting #
1743 (py-goto-initial-line)
1744 (while (and
1745 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1746 (zerop (forward-line -1))) ; go back
1747 nil)
1748 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749 (let* ((re (concat "[ \t]*" key "\\b"))
1750 (case-fold-search nil) ; let* so looking-at sees this
1751 (found (looking-at re))
1752 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001753 (while (not (or found dead))
1754 (condition-case nil ; in case no enclosing block
1755 (py-goto-block-up 'no-mark)
1756 (error (setq dead t)))
1757 (or dead (setq found (looking-at re))))
1758 (beginning-of-line)
1759 found))
1760
1761;; return string in buffer from start of indentation to end of line;
1762;; prefix "..." if leading whitespace was skipped
1763(defun py-suck-up-leading-text ()
1764 (save-excursion
1765 (back-to-indentation)
1766 (concat
1767 (if (bolp) "" "...")
1768 (buffer-substring (point) (progn (end-of-line) (point))))))
1769
1770;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1771;; as a Lisp symbol; return nil if none
1772(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1775 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1776 nil)))
1777
1778(defun py-make-temp-name ()
1779 (make-temp-name
1780 (concat (file-name-as-directory py-temp-directory) "python")))
1781
1782(defun py-delete-file-silently (fname)
1783 (condition-case nil
1784 (delete-file fname)
1785 (error nil)))
1786
1787(defun py-kill-emacs-hook ()
1788 ;; delete our temp files
1789 (while py-file-queue
1790 (py-delete-file-silently (car py-file-queue))
1791 (setq py-file-queue (cdr py-file-queue)))
1792 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1793 ;; run the hook we inherited, if any
1794 (and py-inherited-kill-emacs-hook
1795 (funcall py-inherited-kill-emacs-hook))))
1796
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001797;; make PROCESS's buffer visible, append STRING to it, and force
1798;; display; also make shell-mode believe the user typed this string,
1799;; so that kill-output-from-shell and show-output-from-shell work
1800;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001801(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001802 (let ((cbuf (current-buffer))
1803 (pbuf (process-buffer process))
1804 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805 (set-buffer pbuf)
1806 (goto-char (point-max))
1807 (move-marker (process-mark process) (point))
1808 (if (not py-this-is-emacs-19-p)
1809 (move-marker last-input-start (point))) ; muck w/ shell-mode
1810 (funcall (process-filter process) process string)
1811 (if (not py-this-is-emacs-19-p)
1812 (move-marker last-input-end (point))) ; muck w/ shell-mode
1813 (set-buffer cbuf))
1814 (sit-for 0))
1815
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001816(defun py-keep-region-active ()
1817 ;; do whatever is necessary to keep the region active in XEmacs.
1818 ;; Ignore byte-compiler warnings you might see. Also note that
1819 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1820 ;; require us to take explicit action.
1821 (and (boundp 'zmacs-region-stays)
1822 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001823
1824
Barry Warsaw850437a1995-03-08 21:50:28 +00001825(defconst py-version "$Revision$"
1826 "`python-mode' version number.")
1827(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1828 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001829
Barry Warsaw850437a1995-03-08 21:50:28 +00001830(defun py-version ()
1831 "Echo the current version of `python-mode' in the minibuffer."
1832 (interactive)
1833 (message "Using `python-mode' version %s" py-version)
1834 (py-keep-region-active))
1835
1836;; only works under Emacs 19
1837;(eval-when-compile
1838; (require 'reporter))
1839
1840(defun py-submit-bug-report (enhancement-p)
1841 "Submit via mail a bug report on `python-mode'.
1842With \\[universal-argument] just submit an enhancement request."
1843 (interactive
1844 (list (not (y-or-n-p
1845 "Is this a bug report? (hit `n' to send other comments) "))))
1846 (let ((reporter-prompt-for-summary-p (not enhancement-p)))
1847 (require 'reporter)
1848 (reporter-submit-bug-report
1849 py-help-address ;address
1850 "python-mode" ;pkgname
1851 ;; varlist
1852 (if enhancement-p nil
1853 '(py-python-command
1854 py-indent-offset
1855 py-block-comment-prefix
1856 py-scroll-process-buffer
1857 py-temp-directory
1858 py-beep-if-tab-change))
1859 nil ;pre-hooks
1860 nil ;post-hooks
1861 "Dear Barry,") ;salutation
1862 (if enhancement-p nil
1863 (set-mark (point))
1864 (insert
1865"Please replace this text with a sufficiently large code sample\n\
1866and an exact recipe so that I can reproduce your problem. Failure\n\
1867to do so may mean a greater delay in fixing your bug.\n\n")
1868 (exchange-point-and-mark)
1869 (py-keep-region-active))))
1870
1871
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872;; arrange to kill temp files when Emacs exists
1873(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
1874 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
1875 ;; have to trust that other people are as respectful of our hook
1876 ;; fiddling as we are of theirs
1877 (if (boundp 'py-inherited-kill-emacs-hook)
1878 ;; we were loaded before -- trust others not to have screwed us
1879 ;; in the meantime (no choice, really)
1880 nil
1881 ;; else arrange for our hook to run theirs
1882 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
1883 (setq kill-emacs-hook 'py-kill-emacs-hook)))
1884
1885
1886
1887(provide 'python-mode)
1888;;; python-mode.el ends here