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