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