blob: 76b391c5980bd1eb1c0a24b499ebfbae704dc2e1 [file] [log] [blame]
Barry Warsaw7ae77681994-12-12 20:38:05 +00001;;; Major mode for editing Python programs, version 1.10
2;; by: Tim Peters <tim@ksr.com>
3;; after an original idea by: Michael A. Guravage
4;;
5;; Copyright (c) 1992,1993,1994 Tim Peters
6;;
7;; This software is provided as-is, without express or implied warranty.
8;; Permission to use, copy, modify, distribute or sell this software,
9;; without fee, for any purpose and by any individual or organization, is
10;; hereby granted, provided that the above copyright notice and this
11;; paragraph appear in all copies.
12;;
13;;
14;; The following statements, placed in your .emacs file or site-init.el,
15;; will cause this file to be autoloaded, and python-mode invoked, when
16;; visiting .py files (assuming the file is in your load-path):
17;;
18;; (autoload 'python-mode "python-mode" "" t)
19;; (setq auto-mode-alist
20;; (cons '("\\.py$" . python-mode) auto-mode-alist))
21
22(provide 'python-mode)
23
24;;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19.
25;;; This seems to be the standard way of checking this.
26
27(setq py-this-is-lucid-emacs-p (string-match "Lucid" emacs-version))
28(setq py-this-is-emacs-19-p
29 (and
30 (not py-this-is-lucid-emacs-p)
31 (string-match "^19\\." emacs-version)))
32
33;;; Constants and variables
34
35(defvar py-python-command "python"
36 "*Shell command used to start Python interpreter.")
37
38(defvar py-indent-offset 8 ; argue with Guido <grin>
39 "*Indentation increment.
40Note that `\\[py-guess-indent-offset]' can usually guess a good value when you're
41editing someone else's Python code.")
42
43(defvar py-block-comment-prefix "##"
44 "*String used by py-comment-region to comment out a block of code.
45This should follow the convention for non-indenting comment lines so
46that the indentation commands won't get confused (i.e., the string
47should be of the form `#x...' where `x' is not a blank or a tab, and
48`...' is arbitrary).")
49
50(defvar py-scroll-process-buffer t
51 "*Scroll Python process buffer as output arrives.
52If nil, the Python process buffer acts, with respect to scrolling, like
53Shell-mode buffers normally act. This is surprisingly complicated and
54so won't be explained here; in fact, you can't get the whole story
55without studying the Emacs C code.
56
57If non-nil, the behavior is different in two respects (which are
58slightly inaccurate in the interest of brevity):
59
60 - If the buffer is in a window, and you left point at its end, the
61 window will scroll as new output arrives, and point will move to the
62 buffer's end, even if the window is not the selected window (that
63 being the one the cursor is in). The usual behavior for shell-mode
64 windows is not to scroll, and to leave point where it was, if the
65 buffer is in a window other than the selected window.
66
67 - If the buffer is not visible in any window, and you left point at
68 its end, the buffer will be popped into a window as soon as more
69 output arrives. This is handy if you have a long-running
70 computation and don't want to tie up screen area waiting for the
71 output. The usual behavior for a shell-mode buffer is to stay
72 invisible until you explicitly visit it.
73
74Note the `and if you left point at its end' clauses in both of the
75above: you can `turn off' the special behaviors while output is in
76progress, by visiting the Python buffer and moving point to anywhere
77besides the end. Then the buffer won't scroll, point will remain where
78you leave it, and if you hide the buffer it will stay hidden until you
79visit it again. You can enable and disable the special behaviors as
80often as you like, while output is in progress, by (respectively) moving
81point to, or away from, the end of the buffer.
82
83Warning: If you expect a large amount of output, you'll probably be
84happier setting this option to nil.
85
86Obscure: `End of buffer' above should really say `at or beyond the
87process mark', but if you know what that means you didn't need to be
88told <grin>.")
89
90(defvar py-temp-directory
91 (let ( (ok '(lambda (x)
92 (and x
93 (setq x (expand-file-name x)) ; always true
94 (file-directory-p x)
95 (file-writable-p x)
96 x))))
97 (or (funcall ok (getenv "TMPDIR"))
98 (funcall ok "/usr/tmp")
99 (funcall ok "/tmp")
100 (funcall ok ".")
101 (error
102 "Couldn't find a usable temp directory -- set py-temp-directory")))
103 "*Directory used for temp files created by a *Python* process.
104By default, the first directory from this list that exists and that you
105can write into: the value (if any) of the environment variable TMPDIR,
106/usr/tmp, /tmp, or the current directory.")
107
108;; have to bind py-file-queue before installing the kill-emacs hook
109(defvar py-file-queue nil
110 "Queue of Python temp files awaiting execution.
111Currently-active file is at the head of the list.")
112
113;; define a mode-specific abbrev table for those who use such things
114(defvar python-mode-abbrev-table nil
115 "Abbrev table in use in python-mode buffers.")
116(define-abbrev-table 'python-mode-abbrev-table nil)
117
118;; arrange to kill temp files no matter what
119(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
120 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
121 ;; have to trust that other people are as respectful of our hook
122 ;; fiddling as we are of theirs
123 (if (boundp 'py-inherited-kill-emacs-hook)
124 ;; we were loaded before -- trust others not to have screwed us
125 ;; in the meantime (no choice, really)
126 nil
127 ;; else arrange for our hook to run theirs
128 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
129 (setq kill-emacs-hook 'py-kill-emacs-hook)))
130
131(defvar python-mode-hook nil
132 "*Hook called by `python-mode'.")
133
134(and (fboundp 'make-obsolete-variable)
135 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
136
137(defvar py-beep-if-tab-change t
138 "*Ring the bell if tab-width is changed.
139If a comment of the form
140\t# vi:set tabsize=<number>:
141is found before the first code line when the file is entered, and
142the current 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 the
145Emacs bell is also rung as a warning.")
146
147(defvar py-mode-map nil "Keymap used in Python mode buffers.")
148(if py-mode-map
149 ()
150 (setq py-mode-map (make-sparse-keymap))
151
152 ;; shadow global bindings for newline-and-indent w/ the py- version
153 (mapcar (function (lambda (key)
154 (define-key
155 py-mode-map key 'py-newline-and-indent)))
156 (where-is-internal 'newline-and-indent))
157
158 (mapcar (function
159 (lambda (x)
160 (define-key py-mode-map (car x) (cdr x))))
161 '( ("\C-c\C-c" . py-execute-buffer)
162 ("\C-c|" . py-execute-region)
163 ("\C-c!" . py-shell)
164 ("\177" . py-delete-char)
165 ("\n" . py-newline-and-indent)
166 ("\C-c:" . py-guess-indent-offset)
167 ("\C-c\t" . py-indent-region)
168 ("\C-c<" . py-shift-region-left)
169 ("\C-c>" . py-shift-region-right)
170 ("\C-c\C-n" . py-next-statement)
171 ("\C-c\C-p" . py-previous-statement)
172 ("\C-c\C-u" . py-goto-block-up)
173 ("\C-c\C-b" . py-mark-block)
174 ("\C-c#" . py-comment-region)
175 ("\C-c?" . py-describe-mode)
176 ("\C-c\C-hm" . py-describe-mode)
177 ("\e\C-a" . beginning-of-python-def-or-class)
178 ("\e\C-e" . end-of-python-def-or-class)
179 ( "\e\C-h" . mark-python-def-or-class))))
180
181(defvar py-mode-syntax-table nil "Python mode syntax table")
182(if py-mode-syntax-table
183 ()
184 (setq py-mode-syntax-table (make-syntax-table))
185 (mapcar (function
186 (lambda (x) (modify-syntax-entry
187 (car x) (cdr x) py-mode-syntax-table)))
188 '(( ?\( . "()" ) ( ?\) . ")(" )
189 ( ?\[ . "(]" ) ( ?\] . ")[" )
190 ( ?\{ . "(}" ) ( ?\} . "){" )
191 ;; fix operator symbols misassigned in the std table
192 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
193 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
194 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
195 ( ?\> . "." ) ( ?\| . "." )
196 ( ?\_ . "w" ) ; underscore is legit in names
197 ( ?\' . "\"") ; single quote is string quote
198 ( ?\" . "\"" ) ; double quote is string quote too
199 ( ?\` . "$") ; backquote is open and close paren
200 ( ?\# . "<") ; hash starts comment
201 ( ?\n . ">")))) ; newline ends comment
202
203(defconst py-stringlit-re
204 (concat
205 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
206 "\\|" ; or
207 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
208 "regexp matching a Python string literal")
209
210;; this is tricky because a trailing backslash does not mean
211;; continuation if it's in a comment
212(defconst py-continued-re
213 (concat
214 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
215 "\\\\$")
216 "regexp matching Python lines that are continued via backslash")
217
218(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
219 "regexp matching blank or comment lines")
220
221;;; General Functions
222
223(defun python-mode ()
224 "Major mode for editing Python files.
225Do `\\[py-describe-mode]' for detailed documentation.
226Knows about Python indentation, tokens, comments and continuation lines.
227Paragraphs are separated by blank lines only.
228
229COMMANDS
230\\{py-mode-map}
231VARIABLES
232
233py-indent-offset\tindentation increment
234py-block-comment-prefix\tcomment string used by py-comment-region
235py-python-command\tshell command to invoke Python interpreter
236py-scroll-process-buffer\talways scroll Python process buffer
237py-temp-directory\tdirectory used for temp files (if needed)
238py-beep-if-tab-change\tring the bell if tab-width is changed"
239 (interactive)
240 (kill-all-local-variables)
241 (setq major-mode 'python-mode
242 mode-name "Python"
243 local-abbrev-table python-mode-abbrev-table)
244 (use-local-map py-mode-map)
245 (set-syntax-table py-mode-syntax-table)
246
247 (mapcar (function (lambda (x)
248 (make-local-variable (car x))
249 (set (car x) (cdr x))))
250 '( (paragraph-separate . "^[ \t]*$")
251 (paragraph-start . "^[ \t]*$")
252 (require-final-newline . t)
253 (comment-start . "# ")
254 (comment-start-skip . "# *")
255 (comment-column . 40)
256 (indent-region-function . py-indent-region)
257 (indent-line-function . py-indent-line)))
258
259 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
260
261 ;; not sure where the magic comment has to be; to save time searching
262 ;; for a rarity, we give up if it's not found prior to the first
263 ;; executable statement
264 (let ( (case-fold-search nil)
265 (start (point))
266 new-tab-width)
267 (if (re-search-forward
268 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
269 (prog2 (py-next-statement 1) (point) (goto-char 1))
270 t)
271 (progn
272 (setq new-tab-width
273 (string-to-int
274 (buffer-substring (match-beginning 1) (match-end 1))))
275 (if (= tab-width new-tab-width)
276 nil
277 (setq tab-width new-tab-width)
278 (message "Caution: tab-width changed to %d" new-tab-width)
279 (if py-beep-if-tab-change (beep)))))
280 (goto-char start))
281
282 (if python-mode-hook
283 (run-hooks 'python-mode-hook)
284 (run-hooks 'py-mode-hook)))
285
286;;; Functions that execute Python commands in a subprocess
287
288(defun py-shell ()
289 "Start an interactive Python interpreter in another window.
290This is like Shell mode, except that Python is running in the window
291instead of a shell. See the `Interactive Shell' and `Shell Mode'
292sections of the Emacs manual for details, especially for the key
293bindings active in the `*Python*' buffer.
294
295See the docs for variable py-scroll-buffer for info on scrolling
296behavior in the process window.
297
298Warning: Don't use an interactive Python if you change sys.ps1 or
299sys.ps2 from their default values, or if you're running code that prints
300`>>> ' or `... ' at the start of a line. Python mode can't distinguish
301your output from Python's output, and assumes that `>>> ' at the start
302of a line is a prompt from Python. Similarly, the Emacs Shell mode code
303assumes that both `>>> ' and `... ' at the start of a line are Python
304prompts. Bad things can happen if you fool either mode.
305
306Warning: If you do any editing *in* the process buffer *while* the
307buffer is accepting output from Python, do NOT attempt to `undo' the
308changes. Some of the output (nowhere near the parts you changed!) may
309be lost if you do. This appears to be an Emacs bug, an unfortunate
310interaction between undo and process filters; the same problem exists in
311non-Python process buffers using the default (Emacs-supplied) process
312filter."
313 (interactive)
314 (if py-this-is-emacs-19-p
315 (progn
316 (require 'comint)
317 (switch-to-buffer-other-window
318 (make-comint "Python" py-python-command)))
319 (progn
320 (require 'shell)
321 (switch-to-buffer-other-window
322 (make-shell "Python" py-python-command))))
323 (make-local-variable 'shell-prompt-pattern)
324 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
325 (set-process-filter (get-buffer-process (current-buffer))
326 'py-process-filter)
327 (set-syntax-table py-mode-syntax-table))
328
329(defun py-execute-region (start end)
330 "Send the region between START and END to a Python interpreter.
331If there is a *Python* process it is used.
332
333Hint: If you want to execute part of a Python file several times (e.g.,
334perhaps you're developing a function and want to flesh it out a bit at a
335time), use `\\[narrow-to-region]' to restrict the buffer to the region of interest,
336and send the code to a *Python* process via `\\[py-execute-buffer]' instead.
337
338Following are subtleties to note when using a *Python* process:
339
340If a *Python* process is used, the region is copied into a temp file (in
341directory py-temp-directory), and an `execfile' command is sent to
342Python naming that file. If you send regions faster than Python can
343execute them, Python mode will save them into distinct temp files, and
344execute the next one in the queue the next time it sees a `>>> ' prompt
345from Python. Each time this happens, the process buffer is popped into
346a window (if it's not already in some window) so you can see it, and a
347comment of the form
348
349\t## working on region in file <name> ...
350
351is inserted at the end.
352
353Caution: No more than 26 regions can be pending at any given time. This
354limit is (indirectly) inherited from libc's mktemp(3). Python mode does
355not try to protect you from exceeding the limit. It's extremely
356unlikely that you'll get anywhere close to the limit in practice, unless
357you're trying to be a jerk <grin>.
358
359See the `\\[py-shell]' docs for additional warnings."
360 (interactive "r")
361 (or (< start end) (error "Region is empty"))
362 (let ( (pyproc (get-process "Python"))
363 fname)
364 (if (null pyproc)
365 (shell-command-on-region start end py-python-command)
366 ;; else feed it thru a temp file
367 (setq fname (py-make-temp-name))
368 (write-region start end fname nil 'no-msg)
369 (setq py-file-queue (append py-file-queue (list fname)))
370 (if (cdr py-file-queue)
371 (message "File %s queued for execution" fname)
372 ;; else
373 (py-execute-file pyproc fname)))))
374
375(defun py-execute-file (pyproc fname)
376 (py-append-to-process-buffer
377 pyproc
378 (format "## working on region in file %s ...\n" fname))
379 (process-send-string pyproc (format "execfile('%s')\n" fname)))
380
381(defun py-process-filter (pyproc string)
382 (let ( (curbuf (current-buffer))
383 (pbuf (process-buffer pyproc))
384 (pmark (process-mark pyproc))
385 file-finished)
386
387 ;; make sure we switch to a different buffer at least once. if we
388 ;; *don't* do this, then if the process buffer is in the selected
389 ;; window, and point is before the end, and lots of output is coming
390 ;; at a fast pace, then (a) simple cursor-movement commands like
391 ;; C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time to have
392 ;; a visible effect (the window just doesn't get updated, sometimes
393 ;; for minutes(!)), and (b) it takes about 5x longer to get all the
394 ;; process output (until the next python prompt).
395 ;;
396 ;; #b makes no sense to me at all. #a almost makes sense: unless we
397 ;; actually change buffers, set_buffer_internal in buffer.c doesn't
398 ;; set windows_or_buffers_changed to 1, & that in turn seems to make
399 ;; the Emacs command loop reluctant to update the display. Perhaps
400 ;; the default process filter in process.c's read_process_output has
401 ;; update_mode_lines++ for a similar reason? beats me ...
402 (if (eq curbuf pbuf) ; mysterious ugly hack
403 (set-buffer (get-buffer-create "*scratch*")))
404
405 (set-buffer pbuf)
406 (let* ( (start (point))
407 (goback (< start pmark))
408 (buffer-read-only nil))
409 (goto-char pmark)
410 (insert string)
411 (move-marker pmark (point))
412 (setq file-finished
413 (and py-file-queue
414 (equal ">>> "
415 (buffer-substring
416 (prog2 (beginning-of-line) (point)
417 (goto-char pmark))
418 (point)))))
419 (if goback (goto-char start)
420 ;; else
421 (if py-scroll-process-buffer
422 (let* ( (pop-up-windows t)
423 (pwin (display-buffer pbuf)))
424 (set-window-point pwin (point))))))
425 (set-buffer curbuf)
426 (if file-finished
427 (progn
428 (py-delete-file-silently (car py-file-queue))
429 (setq py-file-queue (cdr py-file-queue))
430 (if py-file-queue
431 (py-execute-file pyproc (car py-file-queue)))))))
432
433(defun py-execute-buffer ()
434 "Send the contents of the buffer to a Python interpreter.
435If there is a *Python* process buffer it is used. If a clipping
436restriction is in effect, only the accessible portion of the buffer is
437sent. A trailing newline will be supplied if needed.
438
439See the `\\[py-execute-region]' docs for an account of some subtleties."
440 (interactive)
441 (py-execute-region (point-min) (point-max)))
442
443
444;;; Functions for Python style indentation
445
446(defun py-delete-char ()
447 "Reduce indentation or delete character.
448If point is at the leftmost column, deletes the preceding newline.
449
450Else if point is at the leftmost non-blank character of a line that is
451neither a continuation line nor a non-indenting comment line, or if
452point is at the end of a blank line, reduces the indentation to match
453that of the line that opened the current block of code. The line that
454opened the block is displayed in the echo area to help you keep track of
455where you are.
456
457Else the preceding character is deleted, converting a tab to spaces if
458needed so that only a single column position is deleted."
459 (interactive "*")
460 (if (or (/= (current-indentation) (current-column))
461 (bolp)
462 (py-continuation-line-p)
463 (looking-at "#[^ \t\n]")) ; non-indenting #
464 (backward-delete-char-untabify 1)
465 ;; else indent the same as the colon line that opened the block
466
467 ;; force non-blank so py-goto-block-up doesn't ignore it
468 (insert-char ?* 1)
469 (backward-char)
470 (let ( (base-indent 0) ; indentation of base line
471 (base-text "") ; and text of base line
472 (base-found-p nil))
473 (condition-case nil ; in case no enclosing block
474 (save-excursion
475 (py-goto-block-up 'no-mark)
476 (setq base-indent (current-indentation)
477 base-text (py-suck-up-leading-text)
478 base-found-p t))
479 (error nil))
480 (delete-char 1) ; toss the dummy character
481 (delete-horizontal-space)
482 (indent-to base-indent)
483 (if base-found-p
484 (message "Closes block: %s" base-text)))))
485
486(defun py-indent-line ()
487 "Fix the indentation of the current line according to Python rules."
488 (interactive)
489 (let* ( (ci (current-indentation))
490 (move-to-indentation-p (<= (current-column) ci))
491 (need (py-compute-indentation)) )
492 (if (/= ci need)
493 (save-excursion
494 (beginning-of-line)
495 (delete-horizontal-space)
496 (indent-to need)))
497 (if move-to-indentation-p (back-to-indentation))))
498
499(defun py-newline-and-indent ()
500 "Strives to act like the Emacs newline-and-indent.
501This is just `strives to' because correct indentation can't be computed
502from scratch for Python code. In general, deletes the whitespace before
503point, inserts a newline, and takes an educated guess as to how you want
504the new line indented."
505 (interactive)
506 (let ( (ci (current-indentation)) )
507 (if (< ci (current-column)) ; if point beyond indentation
508 (newline-and-indent)
509 ;; else try to act like newline-and-indent "normally" acts
510 (beginning-of-line)
511 (insert-char ?\n 1)
512 (move-to-column ci))))
513
514(defun py-compute-indentation ()
515 (save-excursion
516 (beginning-of-line)
517 (cond
518 ;; are we on a continuation line?
519 ( (py-continuation-line-p)
520 (let ( (startpos (point))
521 (open-bracket-pos (py-nesting-level))
522 endpos searching found)
523 (if open-bracket-pos
524 (progn
525 ;; align with first item in list; else a normal
526 ;; indent beyond the line with the open bracket
527 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
528 ;; is the first list item on the same line?
529 (skip-chars-forward " \t")
530 (if (null (memq (following-char) '(?\n ?# ?\\)))
531 ; yes, so line up with it
532 (current-column)
533 ;; first list item on another line, or doesn't exist yet
534 (forward-line 1)
535 (while (and (< (point) startpos)
536 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
537 (forward-line 1))
538 (if (< (point) startpos)
539 ;; again mimic the first list item
540 (current-indentation)
541 ;; else they're about to enter the first item
542 (goto-char open-bracket-pos)
543 (+ (current-indentation) py-indent-offset))))
544
545 ;; else on backslash continuation line
546 (forward-line -1)
547 (if (py-continuation-line-p) ; on at least 3rd line in block
548 (current-indentation) ; so just continue the pattern
549 ;; else started on 2nd line in block, so indent more.
550 ;; if base line is an assignment with a start on a RHS,
551 ;; indent to 2 beyond the leftmost "="; else skip first
552 ;; chunk of non-whitespace characters on base line, + 1 more
553 ;; column
554 (end-of-line)
555 (setq endpos (point) searching t)
556 (back-to-indentation)
557 (setq startpos (point))
558 ;; look at all "=" from left to right, stopping at first
559 ;; one not nested in a list or string
560 (while searching
561 (skip-chars-forward "^=" endpos)
562 (if (= (point) endpos)
563 (setq searching nil)
564 (forward-char 1)
565 (setq state (parse-partial-sexp startpos (point)))
566 (if (and (zerop (car state)) ; not in a bracket
567 (null (nth 3 state))) ; & not in a string
568 (progn
569 (setq searching nil) ; done searching in any case
570 (setq found
571 (not (or
572 (eq (following-char) ?=)
573 (memq (char-after (- (point) 2))
574 '(?< ?> ?!)))))))))
575 (if (or (not found) ; not an assignment
576 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
577 (progn
578 (goto-char startpos)
579 (skip-chars-forward "^ \t\n")))
580 (1+ (current-column))))))
581
582 ;; not on a continuation line
583
584 ;; if at start of restriction, or on a non-indenting comment line,
585 ;; assume they intended whatever's there
586 ( (or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
587 (current-indentation) )
588
589 ;; else indentation based on that of the statement that precedes
590 ;; us; use the first line of that statement to establish the base,
591 ;; in case the user forced a non-std indentation for the
592 ;; continuation lines (if any)
593 ( t
594 ;; skip back over blank & non-indenting comment lines
595 ;; note: will skip a blank or non-indenting comment line that
596 ;; happens to be a continuation line too
597 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
598 nil 'move)
Barry Warsaw3ff44491994-12-16 00:13:34 +0000599 ;; if we landed inside a string, go to the beginning of that string
600 (let ((state (parse-partial-sexp
601 (save-excursion (beginning-of-python-def-or-class)
602 (point))
603 (point))))
604 (if (nth 3 state)
605 (goto-char (nth 2 state))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000606 (py-goto-initial-line)
607 (if (py-statement-opens-block-p)
608 (+ (current-indentation) py-indent-offset)
609 (current-indentation))))))
610
611(defun py-guess-indent-offset (&optional global)
612 "Guess a good value for, and change, py-indent-offset.
613By default (without a prefix arg), makes a buffer-local copy of
614py-indent-offset with the new value. This will not affect any other
615Python buffers. With a prefix arg, changes the global value of
616py-indent-offset. This affects all Python buffers (that don't have
617their own buffer-local copy), both those currently existing and those
618created later in the Emacs session.
619
620Some people use a different value for py-indent-offset than you use.
621There's no excuse for such foolishness, but sometimes you have to deal
622with their ugly code anyway. This function examines the file and sets
623py-indent-offset to what it thinks it was when they created the mess.
624
625Specifically, it searches forward from the statement containing point,
626looking for a line that opens a block of code. py-indent-offset is set
627to the difference in indentation between that line and the Python
628statement following it. If the search doesn't succeed going forward,
629it's tried again going backward."
630 (interactive "P") ; raw prefix arg
631 (let ( new-value
632 (start (point))
633 restart
634 (found nil)
635 colon-indent)
636 (py-goto-initial-line)
637 (while (not (or found (eobp)))
638 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
639 (progn
640 (setq restart (point))
641 (py-goto-initial-line)
642 (if (py-statement-opens-block-p)
643 (setq found t)
644 (goto-char restart)))))
645 (if found
646 ()
647 (goto-char start)
648 (py-goto-initial-line)
649 (while (not (or found (bobp)))
650 (setq found
651 (and
652 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
653 (or (py-goto-initial-line) t) ; always true -- side effect
654 (py-statement-opens-block-p)))))
655 (setq colon-indent (current-indentation)
656 found (and found (zerop (py-next-statement 1)))
657 new-value (- (current-indentation) colon-indent))
658 (goto-char start)
659 (if found
660 (progn
661 (funcall (if global 'kill-local-variable 'make-local-variable)
662 'py-indent-offset)
663 (setq py-indent-offset new-value)
664 (message "%s value of py-indent-offset set to %d"
665 (if global "Global" "Local")
666 py-indent-offset))
667 (error "Sorry, couldn't guess a value for py-indent-offset"))))
668
669(defun py-shift-region (start end count)
670 (save-excursion
671 (goto-char end) (beginning-of-line) (setq end (point))
672 (goto-char start) (beginning-of-line) (setq start (point))
673 (indent-rigidly start end count)))
674
675(defun py-shift-region-left (start end &optional count)
676 "Shift region of Python code to the left.
677The lines from the line containing the start of the current region up
678to (but not including) the line containing the end of the region are
679shifted to the left, by py-indent-offset columns.
680
681If a prefix argument is given, the region is instead shifted by that
682many columns."
683 (interactive "*r\nP") ; region; raw prefix arg
684 (py-shift-region start end
685 (- (prefix-numeric-value
686 (or count py-indent-offset)))))
687
688(defun py-shift-region-right (start end &optional count)
689 "Shift region of Python code to the right.
690The lines from the line containing the start of the current region up
691to (but not including) the line containing the end of the region are
692shifted to the right, by py-indent-offset columns.
693
694If a prefix argument is given, the region is instead shifted by that
695many columns."
696 (interactive "*r\nP") ; region; raw prefix arg
697 (py-shift-region start end (prefix-numeric-value
698 (or count py-indent-offset))))
699
700(defun py-indent-region (start end &optional indent-offset)
701 "Reindent a region of Python code.
702The lines from the line containing the start of the current region up
703to (but not including) the line containing the end of the region are
704reindented. If the first line of the region has a non-whitespace
705character in the first column, the first line is left alone and the rest
706of the region is reindented with respect to it. Else the entire region
707is reindented with respect to the (closest code or indenting-comment)
708statement immediately preceding the region.
709
710This is useful when code blocks are moved or yanked, when enclosing
711control structures are introduced or removed, or to reformat code using
712a new value for the indentation offset.
713
714If a numeric prefix argument is given, it will be used as the value of
715the indentation offset. Else the value of py-indent-offset will be
716used.
717
718Warning: The region must be consistently indented before this function
719is called! This function does not compute proper indentation from
720scratch (that's impossible in Python), it merely adjusts the existing
721indentation to be correct in context.
722
723Warning: This function really has no idea what to do with non-indenting
724comment lines, and shifts them as if they were indenting comment lines.
725Fixing this appears to require telepathy.
726
727Special cases: whitespace is deleted from blank lines; continuation
728lines are shifted by the same amount their initial line was shifted, in
729order to preserve their relative indentation with respect to their
730initial line; and comment lines beginning in column 1 are ignored."
731
732 (interactive "*r\nP") ; region; raw prefix arg
733 (save-excursion
734 (goto-char end) (beginning-of-line) (setq end (point-marker))
735 (goto-char start) (beginning-of-line)
736 (let ( (py-indent-offset (prefix-numeric-value
737 (or indent-offset py-indent-offset)))
738 (indents '(-1)) ; stack of active indent levels
739 (target-column 0) ; column to which to indent
740 (base-shifted-by 0) ; amount last base line was shifted
741 (indent-base (if (looking-at "[ \t\n]")
742 (py-compute-indentation)
743 0))
744 ci)
745 (while (< (point) end)
746 (setq ci (current-indentation))
747 ;; figure out appropriate target column
748 (cond
749 ( (or (eq (following-char) ?#) ; comment in column 1
750 (looking-at "[ \t]*$")) ; entirely blank
751 (setq target-column 0))
752 ( (py-continuation-line-p) ; shift relative to base line
753 (setq target-column (+ ci base-shifted-by)))
754 (t ; new base line
755 (if (> ci (car indents)) ; going deeper; push it
756 (setq indents (cons ci indents))
757 ;; else we should have seen this indent before
758 (setq indents (memq ci indents)) ; pop deeper indents
759 (if (null indents)
760 (error "Bad indentation in region, at line %d"
761 (save-restriction
762 (widen)
763 (1+ (count-lines 1 (point)))))))
764 (setq target-column (+ indent-base
765 (* py-indent-offset
766 (- (length indents) 2))))
767 (setq base-shifted-by (- target-column ci))))
768 ;; shift as needed
769 (if (/= ci target-column)
770 (progn
771 (delete-horizontal-space)
772 (indent-to target-column)))
773 (forward-line 1))))
774 (set-marker end nil))
775
776;;; Functions for moving point
777
778(defun py-previous-statement (count)
779 "Go to the start of previous Python statement.
780If the statement at point is the i'th Python statement, goes to the
781start of statement i-COUNT. If there is no such statement, goes to the
782first statement. Returns count of statements left to move.
783`Statements' do not include blank, comment, or continuation lines."
784 (interactive "p") ; numeric prefix arg
785 (if (< count 0) (py-next-statement (- count))
786 (py-goto-initial-line)
787 (let ( start )
788 (while (and
789 (setq start (point)) ; always true -- side effect
790 (> count 0)
791 (zerop (forward-line -1))
792 (py-goto-statement-at-or-above))
793 (setq count (1- count)))
794 (if (> count 0) (goto-char start)))
795 count))
796
797(defun py-next-statement (count)
798 "Go to the start of next Python statement.
799If the statement at point is the i'th Python statement, goes to the
800start of statement i+COUNT. If there is no such statement, goes to the
801last statement. Returns count of statements left to move. `Statements'
802do not include blank, comment, or continuation lines."
803 (interactive "p") ; numeric prefix arg
804 (if (< count 0) (py-previous-statement (- count))
805 (beginning-of-line)
806 (let ( start )
807 (while (and
808 (setq start (point)) ; always true -- side effect
809 (> count 0)
810 (py-goto-statement-below))
811 (setq count (1- count)))
812 (if (> count 0) (goto-char start)))
813 count))
814
815(defun py-goto-block-up (&optional nomark)
816 "Move up to start of current block.
817Go to the statement that starts the smallest enclosing block; roughly
818speaking, this will be the closest preceding statement that ends with a
819colon and is indented less than the statement you started on. If
820successful, also sets the mark to the starting point.
821
822`\\[py-mark-block]' can be used afterward to mark the whole code block, if desired.
823
824If called from a program, the mark will not be set if optional argument
825NOMARK is not nil."
826 (interactive)
827 (let ( (start (point))
828 (found nil)
829 initial-indent)
830 (py-goto-initial-line)
831 ;; if on blank or non-indenting comment line, use the preceding stmt
832 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
833 (progn
834 (py-goto-statement-at-or-above)
835 (setq found (py-statement-opens-block-p))))
836 ;; search back for colon line indented less
837 (setq initial-indent (current-indentation))
838 (if (zerop initial-indent)
839 ;; force fast exit
840 (goto-char (point-min)))
841 (while (not (or found (bobp)))
842 (setq found
843 (and
844 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
845 (or (py-goto-initial-line) t) ; always true -- side effect
846 (< (current-indentation) initial-indent)
847 (py-statement-opens-block-p))))
848 (if found
849 (progn
850 (or nomark (push-mark start))
851 (back-to-indentation))
852 (goto-char start)
853 (error "Enclosing block not found"))))
854
855(defun beginning-of-python-def-or-class (&optional class)
856 "Move point to start of def (or class, with prefix arg).
857
858Searches back for the closest preceding `def'. If you supply a prefix
859arg, looks for a `class' instead. The docs assume the `def' case; just
860substitute `class' for `def' for the other case.
861
862If point is in a def statement already, and after the `d', simply moves
863point to the start of the statement.
864
865Else (point is not in a def statement, or at or before the `d' of a def
866statement), searches for the closest preceding def statement, and leaves
867point at its start. If no such statement can be found, leaves point at
868the start of the buffer.
869
870Returns t iff a def statement is found by these rules.
871
872Note that doing this command repeatedly will take you closer to the start
873of the buffer each time.
874
875If you want to mark the current def/class, see `\\[mark-python-def-or-class]'."
876 (interactive "P") ; raw prefix arg
877 (let ( (at-or-before-p (<= (current-column) (current-indentation)))
878 (start-of-line (progn (beginning-of-line) (point)))
879 (start-of-stmt (progn (py-goto-initial-line) (point))))
880 (if (or (/= start-of-stmt start-of-line)
881 (not at-or-before-p))
882 (end-of-line)) ; OK to match on this line
883 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
884 nil 'move)))
885
886(defun end-of-python-def-or-class (&optional class)
887 "Move point beyond end of def (or class, with prefix arg) body.
888
889By default, looks for an appropriate `def'. If you supply a prefix arg,
890looks for a `class' instead. The docs assume the `def' case; just
891substitute `class' for `def' for the other case.
892
893If point is in a def statement already, this is the def we use.
894
895Else if the def found by `\\[beginning-of-python-def-or-class]' contains the statement you
896started on, that's the def we use.
897
898Else we search forward for the closest following def, and use that.
899
900If a def can be found by these rules, point is moved to the start of the
901line immediately following the def block, and the position of the start
902of the def is returned.
903
904Else point is moved to the end of the buffer, and nil is returned.
905
906Note that doing this command repeatedly will take you closer to the end
907of the buffer each time.
908
909If you want to mark the current def/class, see `\\[mark-python-def-or-class]'."
910 (interactive "P") ; raw prefix arg
911 (let ( (start (progn (py-goto-initial-line) (point)))
912 (which (if class "class" "def"))
913 (state 'not-found))
914 ;; move point to start of appropriate def/class
915 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
916 (setq state 'at-beginning)
917 ;; else see if beginning-of-python-def-or-class hits container
918 (if (and (beginning-of-python-def-or-class class)
919 (progn (py-goto-beyond-block)
920 (> (point) start)))
921 (setq state 'at-end)
922 ;; else search forward
923 (goto-char start)
924 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
925 (progn (setq state 'at-beginning)
926 (beginning-of-line)))))
927 (cond
928 ((eq state 'at-beginning) (py-goto-beyond-block) t)
929 ((eq state 'at-end) t)
930 ((eq state 'not-found) nil)
931 (t (error "internal error in end-of-python-def-or-class")))))
932
933;;; Functions for marking regions
934
935(defun py-mark-block (&optional extend just-move)
936 "Mark following block of lines. With prefix arg, mark structure.
937Easier to use than explain. It sets the region to an `interesting'
938block of succeeding lines. If point is on a blank line, it goes down to
939the next non-blank line. That will be the start of the region. The end
940of the region depends on the kind of line at the start:
941
942 - If a comment, the region will include all succeeding comment lines up
943 to (but not including) the next non-comment line (if any).
944
945 - Else if a prefix arg is given, and the line begins one of these
946 structures:
947\tif elif else try except finally for while def class
948 the region will be set to the body of the structure, including
949 following blocks that `belong' to it, but excluding trailing blank
950 and comment lines. E.g., if on a `try' statement, the `try' block
951 and all (if any) of the following `except' and `finally' blocks that
952 belong to the `try' structure will be in the region. Ditto for
953 if/elif/else, for/else and while/else structures, and (a bit
954 degenerate, since they're always one-block structures) def and class
955 blocks.
956
957 - Else if no prefix argument is given, and the line begins a Python
958 block (see list above), and the block is not a `one-liner' (i.e., the
959 statement ends with a colon, not with code), the region will include
960 all succeeding lines up to (but not including) the next code
961 statement (if any) that's indented no more than the starting line,
962 except that trailing blank and comment lines are excluded. E.g., if
963 the starting line begins a multi-statement `def' structure, the
964 region will be set to the full function definition, but without any
965 trailing `noise' lines.
966
967 - Else the region will include all succeeding lines up to (but not
968 including) the next blank line, or code or indenting-comment line
969 indented strictly less than the starting line. Trailing indenting
970 comment lines are included in this case, but not trailing blank
971 lines.
972
973A msg identifying the location of the mark is displayed in the echo
974area; or do `\\[exchange-point-and-mark]' to flip down to the end.
975
976If called from a program, optional argument EXTEND plays the role of the
977prefix arg, and if optional argument JUST-MOVE is not nil, just moves to
978the end of the block (& does not set mark or display a msg)."
979
980 (interactive "P") ; raw prefix arg
981 (py-goto-initial-line)
982 ;; skip over blank lines
983 (while (and
984 (looking-at "[ \t]*$") ; while blank line
985 (not (eobp))) ; & somewhere to go
986 (forward-line 1))
987 (if (eobp)
988 (error "Hit end of buffer without finding a non-blank stmt"))
989 (let ( (initial-pos (point))
990 (initial-indent (current-indentation))
991 last-pos ; position of last stmt in region
992 (followers
993 '( (if elif else) (elif elif else) (else)
994 (try except finally) (except except) (finally)
995 (for else) (while else)
996 (def) (class) ) )
997 first-symbol next-symbol)
998
999 (cond
1000 ;; if comment line, suck up the following comment lines
1001 ((looking-at "[ \t]*#")
1002 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1003 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1004 (setq last-pos (point)))
1005
1006 ;; else if line is a block line and EXTEND given, suck up
1007 ;; the whole structure
1008 ((and extend
1009 (setq first-symbol (py-suck-up-first-keyword) )
1010 (assq first-symbol followers))
1011 (while (and
1012 (or (py-goto-beyond-block) t) ; side effect
1013 (forward-line -1) ; side effect
1014 (setq last-pos (point)) ; side effect
1015 (py-goto-statement-below)
1016 (= (current-indentation) initial-indent)
1017 (setq next-symbol (py-suck-up-first-keyword))
1018 (memq next-symbol (cdr (assq first-symbol followers))))
1019 (setq first-symbol next-symbol)))
1020
1021 ;; else if line *opens* a block, search for next stmt indented <=
1022 ((py-statement-opens-block-p)
1023 (while (and
1024 (setq last-pos (point)) ; always true -- side effect
1025 (py-goto-statement-below)
1026 (> (current-indentation) initial-indent))
1027 nil))
1028
1029 ;; else plain code line; stop at next blank line, or stmt or
1030 ;; indenting comment line indented <
1031 (t
1032 (while (and
1033 (setq last-pos (point)) ; always true -- side effect
1034 (or (py-goto-beyond-final-line) t)
1035 (not (looking-at "[ \t]*$")) ; stop at blank line
1036 (or
1037 (>= (current-indentation) initial-indent)
1038 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1039 nil)))
1040
1041 ;; skip to end of last stmt
1042 (goto-char last-pos)
1043 (py-goto-beyond-final-line)
1044
1045 ;; set mark & display
1046 (if just-move
1047 () ; just return
1048 (push-mark (point) 'no-msg)
1049 (forward-line -1)
1050 (message "Mark set after: %s" (py-suck-up-leading-text))
1051 (goto-char initial-pos))))
1052
1053(defun mark-python-def-or-class (&optional class)
1054 "Set region to body of def (or class, with prefix arg) enclosing point.
1055Pushes the current mark, then point, on the mark ring (all language
1056modes do this, but although it's handy it's never documented ...).
1057
1058In most Emacs language modes, this function bears at least a
1059hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and `\\[beginning-of-python-def-or-class]'.
1060
1061And in earlier versions of Python mode, all 3 were tightly connected.
1062Turned out that was more confusing than useful: the `goto start' and
1063`goto end' commands are usually used to search through a file, and people
1064expect them to act a lot like `search backward' and `search forward'
1065string-search commands. But because Python `def' and `class' can nest to
1066arbitrary levels, finding the smallest def containing point cannot be
1067done via a simple backward search: the def containing point may not be
1068the closest preceding def, or even the closest preceding def that's
1069indented less. The fancy algorithm required is appropriate for the usual
1070uses of this `mark' command, but not for the `goto' variations.
1071
1072So the def marked by this command may not be the one either of the `goto'
1073commands find: If point is on a blank or non-indenting comment line,
1074moves back to start of the closest preceding code statement or indenting
1075comment line. If this is a `def' statement, that's the def we use. Else
1076searches for the smallest enclosing `def' block and uses that. Else
1077signals an error.
1078
1079When an enclosing def is found: The mark is left immediately beyond the
1080last line of the def block. Point is left at the start of the def,
1081except that: if the def is preceded by a number of comment lines
1082followed by (at most) one optional blank line, point is left at the start
1083of the comments; else if the def is preceded by a blank line, point is
1084left at its start.
1085
1086The intent is to mark the containing def/class and its associated
1087documentation, to make moving and duplicating functions and classes
1088pleasant."
1089 (interactive "P") ; raw prefix arg
1090 (let ( (start (point))
1091 (which (if class "class" "def")))
1092 (push-mark start)
1093 (if (not (py-go-up-tree-to-keyword which))
1094 (progn (goto-char start)
1095 (error "Enclosing %s not found" which))
1096 ;; else enclosing def/class found
1097 (setq start (point))
1098 (py-goto-beyond-block)
1099 (push-mark (point))
1100 (goto-char start)
1101 (if (zerop (forward-line -1)) ; if there is a preceding line
1102 (progn
1103 (if (looking-at "[ \t]*$") ; it's blank
1104 (setq start (point)) ; so reset start point
1105 (goto-char start)) ; else try again
1106 (if (zerop (forward-line -1))
1107 (if (looking-at "[ \t]*#") ; a comment
1108 ;; look back for non-comment line
1109 ;; tricky: note that the regexp matches a blank
1110 ;; line, cuz \n is in the 2nd character class
1111 (and
1112 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1113 (forward-line 1))
1114 ;; no comment, so go back
1115 (goto-char start))))))))
1116
1117(defun py-comment-region (start end &optional uncomment-p)
1118 "Comment out region of code; with prefix arg, uncomment region.
1119The lines from the line containing the start of the current region up
1120to (but not including) the line containing the end of the region are
1121commented out, by inserting the string py-block-comment-prefix at the
1122start of each line. With a prefix arg, removes py-block-comment-prefix
1123from the start of each line instead."
1124 (interactive "*r\nP") ; region; raw prefix arg
1125 (goto-char end) (beginning-of-line) (setq end (point))
1126 (goto-char start) (beginning-of-line) (setq start (point))
1127 (let ( (prefix-len (length py-block-comment-prefix)) )
1128 (save-excursion
1129 (save-restriction
1130 (narrow-to-region start end)
1131 (while (not (eobp))
1132 (if uncomment-p
1133 (and (string= py-block-comment-prefix
1134 (buffer-substring
1135 (point) (+ (point) prefix-len)))
1136 (delete-char prefix-len))
1137 (insert py-block-comment-prefix))
1138 (forward-line 1))))))
1139
1140;;; Documentation functions
1141
1142;; dump the long form of the mode blurb; does the usual doc escapes,
1143;; plus lines of the form ^[vc]:name$ to suck variable & command
1144;; docs out of the right places, along with the keys they're on &
1145;; current values
1146(defun py-dump-help-string (str)
1147 (with-output-to-temp-buffer "*Help*"
1148 (let ( (locals (buffer-local-variables))
1149 funckind funcname func funcdoc
1150 (start 0) mstart end
1151 keys )
1152 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1153 (setq mstart (match-beginning 0) end (match-end 0)
1154 funckind (substring str (match-beginning 1) (match-end 1))
1155 funcname (substring str (match-beginning 2) (match-end 2))
1156 func (intern funcname))
1157 (princ (substitute-command-keys (substring str start mstart)))
1158 (cond
1159 ( (equal funckind "c") ; command
1160 (setq funcdoc (documentation func)
1161 keys (concat
1162 "Key(s): "
1163 (mapconcat 'key-description
1164 (where-is-internal func py-mode-map)
1165 ", "))))
1166 ( (equal funckind "v") ; variable
1167 (setq funcdoc (substitute-command-keys
1168 (get func 'variable-documentation))
1169 keys (if (assq func locals)
1170 (concat
1171 "Local/Global values: "
1172 (prin1-to-string (symbol-value func))
1173 " / "
1174 (prin1-to-string (default-value func)))
1175 (concat
1176 "Value: "
1177 (prin1-to-string (symbol-value func))))))
1178 ( t ; unexpected
1179 (error "Error in py-dump-help-string, tag `%s'" funckind)))
1180 (princ (format "\n-> %s:\t%s\t%s\n\n"
1181 (if (equal funckind "c") "Command" "Variable")
1182 funcname keys))
1183 (princ funcdoc)
1184 (terpri)
1185 (setq start end))
1186 (princ (substitute-command-keys (substring str start))))
1187 (print-help-return-message)))
1188
1189(defun py-describe-mode ()
1190 "Dump long form of Python-mode docs."
1191 (interactive)
1192 (py-dump-help-string "Major mode for editing Python files.
1193Knows about Python indentation, tokens, comments and continuation lines.
1194Paragraphs are separated by blank lines only.
1195
1196Major sections below begin with the string `@'; specific function and
1197variable docs begin with `->'.
1198
1199@EXECUTING PYTHON CODE
1200
1201\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1202\\[py-execute-region]\tsends the current region
1203\\[py-shell]\tstarts a Python interpreter window; this will be used by
1204\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1205%c:py-execute-buffer
1206%c:py-execute-region
1207%c:py-shell
1208
1209@VARIABLES
1210
1211py-indent-offset\tindentation increment
1212py-block-comment-prefix\tcomment string used by py-comment-region
1213
1214py-python-command\tshell command to invoke Python interpreter
1215py-scroll-process-buffer\talways scroll Python process buffer
1216py-temp-directory\tdirectory used for temp files (if needed)
1217
1218py-beep-if-tab-change\tring the bell if tab-width is changed
1219%v:py-indent-offset
1220%v:py-block-comment-prefix
1221%v:py-python-command
1222%v:py-scroll-process-buffer
1223%v:py-temp-directory
1224%v:py-beep-if-tab-change
1225
1226@KINDS OF LINES
1227
1228Each physical line in the file is either a `continuation line' (the
1229preceding line ends with a backslash that's not part of a comment, or the
1230paren/bracket/brace nesting level at the start of the line is non-zero,
1231or both) or an `initial line' (everything else).
1232
1233An initial line is in turn a `blank line' (contains nothing except
1234possibly blanks or tabs), a `comment line' (leftmost non-blank character
1235is `#'), or a `code line' (everything else).
1236
1237Comment Lines
1238
1239Although all comment lines are treated alike by Python, Python mode
1240recognizes two kinds that act differently with respect to indentation.
1241
1242An `indenting comment line' is a comment line with a blank, tab or
1243nothing after the initial `#'. The indentation commands (see below)
1244treat these exactly as if they were code lines: a line following an
1245indenting comment line will be indented like the comment line. All
1246other comment lines (those with a non-whitespace character immediately
1247following the initial `#') are `non-indenting comment lines', and their
1248indentation is ignored by the indentation commands.
1249
1250Indenting comment lines are by far the usual case, and should be used
1251whenever possible. Non-indenting comment lines are useful in cases like
1252these:
1253
1254\ta = b # a very wordy single-line comment that ends up being
1255\t #... continued onto another line
1256
1257\tif a == b:
1258##\t\tprint 'panic!' # old code we've `commented out'
1259\t\treturn a
1260
1261Since the `#...' and `##' comment lines have a non-whitespace character
1262following the initial `#', Python mode ignores them when computing the
1263proper indentation for the next line.
1264
1265Continuation Lines and Statements
1266
1267The Python-mode commands generally work on statements instead of on
1268individual lines, where a `statement' is a comment or blank line, or a
1269code line and all of its following continuation lines (if any)
1270considered as a single logical unit. The commands in this mode
1271generally (when it makes sense) automatically move to the start of the
1272statement containing point, even if point happens to be in the middle of
1273some continuation line.
1274
1275
1276@INDENTATION
1277
1278Primarily for entering new code:
1279\t\\[indent-for-tab-command]\t indent line appropriately
1280\t\\[py-newline-and-indent]\t insert newline, then indent
1281\t\\[py-delete-char]\t reduce indentation, or delete single character
1282
1283Primarily for reindenting existing code:
1284\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1285\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1286
1287\t\\[py-indent-region]\t reindent region to match its context
1288\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1289\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1290
1291Unlike most programming languages, Python uses indentation, and only
1292indentation, to specify block structure. Hence the indentation supplied
1293automatically by Python-mode is just an educated guess: only you know
1294the block structure you intend, so only you can supply correct
1295indentation.
1296
1297The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1298the indentation of preceding statements. E.g., assuming
1299py-indent-offset is 4, after you enter
1300\tif a > 0: \\[py-newline-and-indent]
1301the cursor will be moved to the position of the `_' (_ is not a
1302character in the file, it's just used here to indicate the location of
1303the cursor):
1304\tif a > 0:
1305\t _
1306If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1307to
1308\tif a > 0:
1309\t c = d
1310\t _
1311Python-mode cannot know whether that's what you intended, or whether
1312\tif a > 0:
1313\t c = d
1314\t_
1315was your intent. In general, Python-mode either reproduces the
1316indentation of the (closest code or indenting-comment) preceding
1317statement, or adds an extra py-indent-offset blanks if the preceding
1318statement has `:' as its last significant (non-whitespace and non-
1319comment) character. If the suggested indentation is too much, use
1320\\[py-delete-char] to reduce it.
1321
1322Continuation lines are given extra indentation. If you don't like the
1323suggested indentation, change it to something you do like, and Python-
1324mode will strive to indent later lines of the statement in the same way.
1325
1326If a line is a continuation line by virtue of being in an unclosed
1327paren/bracket/brace structure (`list', for short), the suggested
1328indentation depends on whether the current line contains the first item
1329in the list. If it does, it's indented py-indent-offset columns beyond
1330the indentation of the line containing the open bracket. If you don't
1331like that, change it by hand. The remaining items in the list will mimic
1332whatever indentation you give to the first item.
1333
1334If a line is a continuation line because the line preceding it ends with
1335a backslash, the third and following lines of the statement inherit their
1336indentation from the line preceding them. The indentation of the second
1337line in the statement depends on the form of the first (base) line: if
1338the base line is an assignment statement with anything more interesting
1339than the backslash following the leftmost assigning `=', the second line
1340is indented two columns beyond that `='. Else it's indented to two
1341columns beyond the leftmost solid chunk of non-whitespace characters on
1342the base line.
1343
1344Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1345repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1346structure you intend.
1347%c:indent-for-tab-command
1348%c:py-newline-and-indent
1349%c:py-delete-char
1350
1351
1352The next function may be handy when editing code you didn't write:
1353%c:py-guess-indent-offset
1354
1355
1356The remaining `indent' functions apply to a region of Python code. They
1357assume the block structure (equals indentation, in Python) of the region
1358is correct, and alter the indentation in various ways while preserving
1359the block structure:
1360%c:py-indent-region
1361%c:py-shift-region-left
1362%c:py-shift-region-right
1363
1364@MARKING & MANIPULATING REGIONS OF CODE
1365
1366\\[py-mark-block]\t mark block of lines
1367\\[mark-python-def-or-class]\t mark smallest enclosing def
1368\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1369\\[py-comment-region]\t comment out region of code
1370\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1371%c:py-mark-block
1372%c:mark-python-def-or-class
1373%c:py-comment-region
1374
1375@MOVING POINT
1376
1377\\[py-previous-statement]\t move to statement preceding point
1378\\[py-next-statement]\t move to statement following point
1379\\[py-goto-block-up]\t move up to start of current block
1380\\[beginning-of-python-def-or-class]\t move to start of def
1381\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1382\\[end-of-python-def-or-class]\t move to end of def
1383\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1384
1385The first two move to one statement beyond the statement that contains
1386point. A numeric prefix argument tells them to move that many
1387statements instead. Blank lines, comment lines, and continuation lines
1388do not count as `statements' for these commands. So, e.g., you can go
1389to the first code statement in a file by entering
1390\t\\[beginning-of-buffer]\t to move to the top of the file
1391\t\\[py-next-statement]\t to skip over initial comments and blank lines
1392Or do `\\[py-previous-statement]' with a huge prefix argument.
1393%c:py-previous-statement
1394%c:py-next-statement
1395%c:py-goto-block-up
1396%c:beginning-of-python-def-or-class
1397%c:end-of-python-def-or-class
1398
1399@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1400
1401`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1402
1403`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1404overall class and def structure of a module.
1405
1406`\\[back-to-indentation]' moves point to a line's first non-blank character.
1407
1408`\\[indent-relative]' is handy for creating odd indentation.
1409
1410@OTHER EMACS HINTS
1411
1412If you don't like the default value of a variable, change its value to
1413whatever you do like by putting a `setq' line in your .emacs file.
1414E.g., to set the indentation increment to 4, put this line in your
1415.emacs:
1416\t(setq py-indent-offset 4)
1417To see the value of a variable, do `\\[describe-variable]' and enter the variable
1418name at the prompt.
1419
1420When entering a key sequence like `C-c C-n', it is not necessary to
1421release the CONTROL key after doing the `C-c' part -- it suffices to
1422press the CONTROL key, press and release `c' (while still holding down
1423CONTROL), press and release `n' (while still holding down CONTROL), &
1424then release CONTROL.
1425
1426Entering Python mode calls with no arguments the value of the variable
1427`python-mode-hook', if that value exists and is not nil; for backward
1428compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1429the Elisp manual for details.
1430
1431Obscure: When python-mode is first loaded, it looks for all bindings
1432to newline-and-indent in the global keymap, and shadows them with
1433local bindings to py-newline-and-indent."))
1434
1435;;; Helper functions
1436
1437(defvar py-parse-state-re
1438 (concat
1439 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1440 "\\|"
1441 "^[^ #\t\n]"))
1442;; returns the parse state at point (see parse-partial-sexp docs)
1443(defun py-parse-state ()
1444 (save-excursion
1445 (let ( (here (point)) )
1446 ;; back up to the first preceding line (if any; else start of
1447 ;; buffer) that begins with a popular Python keyword, or a non-
1448 ;; whitespace and non-comment character. These are good places to
1449 ;; start parsing to see whether where we started is at a non-zero
1450 ;; nesting level. It may be slow for people who write huge code
1451 ;; blocks or huge lists ... tough beans.
1452 (re-search-backward py-parse-state-re nil 'move)
1453 (beginning-of-line)
1454 (parse-partial-sexp (point) here))))
1455
1456;; if point is at a non-zero nesting level, returns the number of the
1457;; character that opens the smallest enclosing unclosed list; else
1458;; returns nil.
1459(defun py-nesting-level ()
1460 (let ( (status (py-parse-state)) )
1461 (if (zerop (car status))
1462 nil ; not in a nest
1463 (car (cdr status))))) ; char# of open bracket
1464
1465;; t iff preceding line ends with backslash that's not in a comment
1466(defun py-backslash-continuation-line-p ()
1467 (save-excursion
1468 (beginning-of-line)
1469 (and
1470 ;; use a cheap test first to avoid the regexp if possible
1471 ;; use 'eq' because char-after may return nil
1472 (eq (char-after (- (point) 2)) ?\\ )
1473 ;; make sure; since eq test passed, there is a preceding line
1474 (forward-line -1) ; always true -- side effect
1475 (looking-at py-continued-re))))
1476
1477;; t iff current line is a continuation line
1478(defun py-continuation-line-p ()
1479 (save-excursion
1480 (beginning-of-line)
1481 (or (py-backslash-continuation-line-p)
1482 (py-nesting-level))))
1483
1484;; go to initial line of current statement; usually this is the
1485;; line we're on, but if we're on the 2nd or following lines of a
1486;; continuation block, we need to go up to the first line of the block.
1487;;
1488;; Tricky: We want to avoid quadratic-time behavior for long continued
1489;; blocks, whether of the backslash or open-bracket varieties, or a mix
1490;; of the two. The following manages to do that in the usual cases.
1491(defun py-goto-initial-line ()
1492 (let ( open-bracket-pos )
1493 (while (py-continuation-line-p)
1494 (beginning-of-line)
1495 (if (py-backslash-continuation-line-p)
1496 (while (py-backslash-continuation-line-p)
1497 (forward-line -1))
1498 ;; else zip out of nested brackets/braces/parens
1499 (while (setq open-bracket-pos (py-nesting-level))
1500 (goto-char open-bracket-pos)))))
1501 (beginning-of-line))
1502
1503;; go to point right beyond final line of current statement; usually
1504;; this is the start of the next line, but if this is a multi-line
1505;; statement we need to skip over the continuation lines.
1506;; Tricky: Again we need to be clever to avoid quadratic time behavior.
1507(defun py-goto-beyond-final-line ()
1508 (forward-line 1)
1509 (let ( state )
1510 (while (and (py-continuation-line-p)
1511 (not (eobp)))
1512 ;; skip over the backslash flavor
1513 (while (and (py-backslash-continuation-line-p)
1514 (not (eobp)))
1515 (forward-line 1))
1516 ;; if in nest, zip to the end of the nest
1517 (setq state (py-parse-state))
1518 (if (and (not (zerop (car state)))
1519 (not (eobp)))
1520 (progn
1521 ;; BUG ALERT: I could swear, from reading the docs, that
1522 ;; the 3rd argument should be plain 0
1523 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1524 nil state)
1525 (forward-line 1))))))
1526
1527;; t iff statement opens a block == iff it ends with a colon that's
1528;; not in a comment
1529;; point should be at the start of a statement
1530(defun py-statement-opens-block-p ()
1531 (save-excursion
1532 (let ( (start (point))
1533 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1534 (searching t)
1535 (answer nil)
1536 state)
1537 (goto-char start)
1538 (while searching
1539 ;; look for a colon with nothing after it except whitespace, and
1540 ;; maybe a comment
1541 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1542 finish t)
1543 (if (eq (point) finish) ; note: no `else' clause; just
1544 ; keep searching if we're not at
1545 ; the end yet
1546 ;; sure looks like it opens a block -- but it might
1547 ;; be in a comment
1548 (progn
1549 (setq searching nil) ; search is done either way
1550 (setq state (parse-partial-sexp start
1551 (match-beginning 0)))
1552 (setq answer (not (nth 4 state)))))
1553 ;; search failed: couldn't find another interesting colon
1554 (setq searching nil)))
1555 answer)))
1556
1557;; go to point right beyond final line of block begun by the current
1558;; line. This is the same as where py-goto-beyond-final-line goes
1559;; unless we're on colon line, in which case we go to the end of the
1560;; block.
1561;; assumes point is at bolp
1562(defun py-goto-beyond-block ()
1563 (if (py-statement-opens-block-p)
1564 (py-mark-block nil 'just-move)
1565 (py-goto-beyond-final-line)))
1566
1567;; go to start of first statement (not blank or comment or continuation
1568;; line) at or preceding point
1569;; returns t if there is one, else nil
1570(defun py-goto-statement-at-or-above ()
1571 (py-goto-initial-line)
1572 (if (looking-at py-blank-or-comment-re)
1573 ;; skip back over blank & comment lines
1574 ;; note: will skip a blank or comment line that happens to be
1575 ;; a continuation line too
1576 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1577 (progn (py-goto-initial-line) t)
1578 nil)
1579 t))
1580
1581;; go to start of first statement (not blank or comment or continuation
1582;; line) following the statement containing point
1583;; returns t if there is one, else nil
1584(defun py-goto-statement-below ()
1585 (beginning-of-line)
1586 (let ( (start (point)) )
1587 (py-goto-beyond-final-line)
1588 (while (and
1589 (looking-at py-blank-or-comment-re)
1590 (not (eobp)))
1591 (forward-line 1))
1592 (if (eobp)
1593 (progn (goto-char start) nil)
1594 t)))
1595
1596;; go to start of statement, at or preceding point, starting with keyword
1597;; KEY. Skips blank lines and non-indenting comments upward first. If
1598;; that statement starts with KEY, done, else go back to first enclosing
1599;; block starting with KEY.
1600;; If successful, leaves point at the start of the KEY line & returns t.
1601;; Else leaves point at an undefined place & returns nil.
1602(defun py-go-up-tree-to-keyword (key)
1603 ;; skip blanks and non-indenting #
1604 (py-goto-initial-line)
1605 (while (and
1606 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1607 (zerop (forward-line -1))) ; go back
1608 nil)
1609 (py-goto-initial-line)
1610 (let* ( (re (concat "[ \t]*" key "\\b"))
1611 (case-fold-search nil) ; let* so looking-at sees this
1612 (found (looking-at re))
1613 (dead nil))
1614 (while (not (or found dead))
1615 (condition-case nil ; in case no enclosing block
1616 (py-goto-block-up 'no-mark)
1617 (error (setq dead t)))
1618 (or dead (setq found (looking-at re))))
1619 (beginning-of-line)
1620 found))
1621
1622;; return string in buffer from start of indentation to end of line;
1623;; prefix "..." if leading whitespace was skipped
1624(defun py-suck-up-leading-text ()
1625 (save-excursion
1626 (back-to-indentation)
1627 (concat
1628 (if (bolp) "" "...")
1629 (buffer-substring (point) (progn (end-of-line) (point))))))
1630
1631;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1632;; as a Lisp symbol; return nil if none
1633(defun py-suck-up-first-keyword ()
1634 (let ( (case-fold-search nil) )
1635 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1636 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1637 nil)))
1638
1639(defun py-make-temp-name ()
1640 (make-temp-name
1641 (concat (file-name-as-directory py-temp-directory) "python")))
1642
1643(defun py-delete-file-silently (fname)
1644 (condition-case nil
1645 (delete-file fname)
1646 (error nil)))
1647
1648(defun py-kill-emacs-hook ()
1649 ;; delete our temp files
1650 (while py-file-queue
1651 (py-delete-file-silently (car py-file-queue))
1652 (setq py-file-queue (cdr py-file-queue)))
1653 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1654 ;; run the hook we inherited, if any
1655 (and py-inherited-kill-emacs-hook
1656 (funcall py-inherited-kill-emacs-hook))))
1657
1658;; make PROCESS's buffer visible, append STRING to it, and force display;
1659;; also make shell-mode believe the user typed this string, so that
1660;; kill-output-from-shell and show-output-from-shell work "right"
1661(defun py-append-to-process-buffer (process string)
1662 (let ( (cbuf (current-buffer))
1663 (pbuf (process-buffer process))
1664 (py-scroll-process-buffer t))
1665 (set-buffer pbuf)
1666 (goto-char (point-max))
1667 (move-marker (process-mark process) (point))
1668 (if (not py-this-is-emacs-19-p)
1669 (move-marker last-input-start (point))) ; muck w/ shell-mode
1670 (funcall (process-filter process) process string)
1671 (if (not py-this-is-emacs-19-p)
1672 (move-marker last-input-end (point))) ; muck w/ shell-mode
1673 (set-buffer cbuf))
1674 (sit-for 0))
1675
1676;; To do:
1677;; - support for ptags