blob: 045d9b0aa0d00ac389e0ade225036578668d9ef1 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5e21cb01997-11-05 18:41:11 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsawaffc0ca1997-11-03 16:59:38 +000027;; Note: this version of python-mode.el is no longer compatible with
28;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
29;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
Barry Warsawa0ee8cd1997-11-26 01:04:44 +000030;; you may need to acquire the Custom library. Please see
31;; <http://www.python.org/ftp/emacs/> for details.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
Barry Warsaw673d05f1997-12-02 21:51:57 +000033;; You will want to byte-compile this file.
34
Barry Warsawaffc0ca1997-11-03 16:59:38 +000035;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
36;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000037;; but it is compatible with 19.34 and the current 20 series Emacsen.
38;; By default, in XEmacs when you visit a .py file, it is put in
39;; Python mode. In Emacs, you need to add the following to your
40;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000041;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000042;; (autoload 'python-mode "python-mode" "Python editing mode." t)
43;; (setq auto-mode-alist
44;; (cons '("\\.py$" . python-mode) auto-mode-alist))
45;; (setq interpreter-mode-alist
46;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000047;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000048;; Assuming python-mode.el is on your load-path, it will be invoked
49;; when you visit a .py file, or a file with a first line that looks
50;; like:
51;;
52;; #! /usr/bin/env python
53
Barry Warsaw44b72201996-07-05 20:11:35 +000054;; If you want font-lock support for Python source code (a.k.a. syntax
55;; coloring, highlighting), add this to your .emacs file:
56;;
57;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000058;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000059;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000060
Barry Warsawaffc0ca1997-11-03 16:59:38 +000061;; To submit bug reports, use C-c C-b. Please include a complete, but
62;; concise code sample and a recipe for reproducing the bug. Send
63;; suggestions and other comments to python-mode@python.org.
64
65;; When in a Python mode buffer, do a C-h m for more help. It's
66;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000067
Barry Warsaw7b0f5681995-03-08 21:33:04 +000068;; Here's a brief to do list:
69;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000070;; - Better integration with gud-mode for debugging.
71;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000072;; - possibly force indent-tabs-mode == nil, and add a
73;; write-file-hooks that runs untabify on the whole buffer (to work
74;; around potential tab/space mismatch problems). In practice this
75;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000076;; - have py-execute-region on indented code act as if the region is
77;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000078;; - Add a py-goto-error or some such that would scan an exception in
79;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
Barry Warsaw7b0f5681995-03-08 21:33:04 +000081;;; Code:
82
Barry Warsawc72c11c1997-08-09 06:42:08 +000083(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +000084(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +000085 (require 'cl)
86 (require 'custom)
87 ;; Stock Emacs 19.34 has a broken/old Custom library that does more
88 ;; harm than good
89 (or (fboundp 'defcustom)
90 (error "STOP! STOP! STOP! STOP!
91
92The Custom library was not found or is out of date. A more current
93version is required. Please download and install the latest version
94of the Custom library from:
95
96 <http://www.dina.kvl.dk/~abraham/custom/>
97
98See the Python Mode home page for details:
99
100 <http://www.python.org/ftp/emacs/>
101")))
102
Barry Warsawc72c11c1997-08-09 06:42:08 +0000103
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000104
105;; user definable variables
106;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(defgroup python nil
109 "Support for the Python programming language, <http://www.python.org/>"
110 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000111
Barry Warsawc72c11c1997-08-09 06:42:08 +0000112(defcustom py-python-command "python"
113 "*Shell command used to start Python interpreter."
114 :type 'string
115 :group 'python)
116
117(defcustom py-indent-offset 4
118 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000119Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120when you're editing someone else's Python code."
121 :type 'integer
122 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000123
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124(defcustom py-align-multiline-strings-p t
125 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000126When this flag is non-nil, continuation lines are lined up under the
127preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000128lines are aligned to column zero."
129 :type '(choice (const :tag "Align under preceding line" t)
130 (const :tag "Align to column zero" nil))
131 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000132
Barry Warsawc72c11c1997-08-09 06:42:08 +0000133(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000134 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135This should follow the convention for non-indenting comment lines so
136that the indentation commands won't get confused (i.e., the string
137should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000138`...' is arbitrary)."
139 :type 'string
140 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000141
Barry Warsawc72c11c1997-08-09 06:42:08 +0000142(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000143 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000144
Barry Warsaw6d627751996-03-06 18:41:38 +0000145When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000146if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000147
148When t, lines that begin with a single `#' are a hint to subsequent
149line indentation. If the previous line is such a comment line (as
150opposed to one that starts with `py-block-comment-prefix'), then it's
151indentation is used as a hint for this line's indentation. Lines that
152begin with `py-block-comment-prefix' are ignored for indentation
153purposes.
154
155When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000156indentation hints, unless the comment character is in column zero."
157 :type '(choice
158 (const :tag "Skip all comment lines (fast)" nil)
159 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000160 (const :tag "Single # `sets' indentation except at column zero"
161 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000162 )
163 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000164
Barry Warsawc72c11c1997-08-09 06:42:08 +0000165(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166 "*Scroll Python process buffer as output arrives.
167If nil, the Python process buffer acts, with respect to scrolling, like
168Shell-mode buffers normally act. This is surprisingly complicated and
169so won't be explained here; in fact, you can't get the whole story
170without studying the Emacs C code.
171
172If non-nil, the behavior is different in two respects (which are
173slightly inaccurate in the interest of brevity):
174
175 - If the buffer is in a window, and you left point at its end, the
176 window will scroll as new output arrives, and point will move to the
177 buffer's end, even if the window is not the selected window (that
178 being the one the cursor is in). The usual behavior for shell-mode
179 windows is not to scroll, and to leave point where it was, if the
180 buffer is in a window other than the selected window.
181
182 - If the buffer is not visible in any window, and you left point at
183 its end, the buffer will be popped into a window as soon as more
184 output arrives. This is handy if you have a long-running
185 computation and don't want to tie up screen area waiting for the
186 output. The usual behavior for a shell-mode buffer is to stay
187 invisible until you explicitly visit it.
188
189Note the `and if you left point at its end' clauses in both of the
190above: you can `turn off' the special behaviors while output is in
191progress, by visiting the Python buffer and moving point to anywhere
192besides the end. Then the buffer won't scroll, point will remain where
193you leave it, and if you hide the buffer it will stay hidden until you
194visit it again. You can enable and disable the special behaviors as
195often as you like, while output is in progress, by (respectively) moving
196point to, or away from, the end of the buffer.
197
198Warning: If you expect a large amount of output, you'll probably be
199happier setting this option to nil.
200
201Obscure: `End of buffer' above should really say `at or beyond the
202process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000203told <grin>."
204 :type 'boolean
205 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000206
Barry Warsaw516b6201997-08-09 06:43:20 +0000207(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000208 (let ((ok '(lambda (x)
209 (and x
210 (setq x (expand-file-name x)) ; always true
211 (file-directory-p x)
212 (file-writable-p x)
213 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000214 (or (funcall ok (getenv "TMPDIR"))
215 (funcall ok "/usr/tmp")
216 (funcall ok "/tmp")
217 (funcall ok ".")
218 (error
219 "Couldn't find a usable temp directory -- set py-temp-directory")))
220 "*Directory used for temp files created by a *Python* process.
221By default, the first directory from this list that exists and that you
222can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000223/usr/tmp, /tmp, or the current directory."
224 :type 'string
225 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000226
Barry Warsaw516b6201997-08-09 06:43:20 +0000227(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000228 "*Ring the bell if tab-width is changed.
229If a comment of the form
230
231 \t# vi:set tabsize=<number>:
232
233is found before the first code line when the file is entered, and the
234current value of (the general Emacs variable) `tab-width' does not
235equal <number>, `tab-width' is set to <number>, a message saying so is
236displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000237the Emacs bell is also rung as a warning."
238 :type 'boolean
239 :group 'python)
240
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000241(defcustom py-backspace-function 'backward-delete-char-untabify
242 "*Function called by `py-electric-backspace' when deleting backwards."
243 :type 'function
244 :group 'python)
245
246(defcustom py-delete-function 'delete-char
247 "*Function called by `py-electric-delete' when deleting forwards."
248 :type 'function
249 :group 'python)
250
251
Barry Warsawc72c11c1997-08-09 06:42:08 +0000252
253;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
254;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
255
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000256(defconst py-emacs-features
257 (let (features)
258 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
259 ;; the same string.
260 (let ((tmp1 (make-temp-name ""))
261 (tmp2 (make-temp-name "")))
262 (if (string-equal tmp1 tmp2)
263 (push 'broken-temp-names features)))
264 ;; return the features
265 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000266 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000267There are many flavors of Emacs out there, with different levels of
268support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000269
Barry Warsawfb07f401997-02-24 03:37:22 +0000270(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000271 (let ((kw1 (mapconcat 'identity
272 '("and" "assert" "break" "class"
273 "continue" "def" "del" "elif"
274 "else" "except" "exec" "for"
275 "from" "global" "if" "import"
276 "in" "is" "lambda" "not"
277 "or" "pass" "print" "raise"
278 "return" "while"
279 )
280 "\\|"))
281 (kw2 (mapconcat 'identity
282 '("else:" "except:" "finally:" "try:")
283 "\\|"))
284 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000285 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000286 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000287 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
288 ;; block introducing keywords with immediately following colons.
289 ;; Yes "except" is in both lists.
290 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000291 ;; classes
292 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
293 1 font-lock-type-face)
294 ;; functions
295 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
296 1 font-lock-function-name-face)
297 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000298 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000299(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
300
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000301
Barry Warsaw81437461996-08-01 19:48:02 +0000302(defvar imenu-example--python-show-method-args-p nil
303 "*Controls echoing of arguments of functions & methods in the imenu buffer.
304When non-nil, arguments are printed.")
305
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000306(make-variable-buffer-local 'py-indent-offset)
307
Barry Warsawe467bfb1997-11-26 05:40:58 +0000308;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000309(defvar py-file-queue nil
310 "Queue of Python temp files awaiting execution.
311Currently-active file is at the head of the list.")
312
Barry Warsawc72c11c1997-08-09 06:42:08 +0000313
314;; Constants
315
316;; Regexp matching a Python string literal
317(defconst py-stringlit-re
318 (concat
319 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
320 "\\|" ; or
321 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
322
323;; Regexp matching Python lines that are continued via backslash.
324;; This is tricky because a trailing backslash does not mean
325;; continuation if it's in a comment
326(defconst py-continued-re
327 (concat
328 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
329 "\\\\$"))
330
331;; Regexp matching blank or comment lines.
332(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
333
334;; Regexp matching clauses to be outdented one level.
335(defconst py-outdent-re
336 (concat "\\(" (mapconcat 'identity
337 '("else:"
338 "except\\(\\s +.*\\)?:"
339 "finally:"
340 "elif\\s +.*:")
341 "\\|")
342 "\\)"))
343
344
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000345;; Regexp matching keywords which typically close a block
346(defconst py-block-closing-keywords-re
347 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
348
Barry Warsawc72c11c1997-08-09 06:42:08 +0000349;; Regexp matching lines to not outdent after.
350(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000351 (concat
352 "\\("
353 (mapconcat 'identity
354 (list "try:"
355 "except\\(\\s +.*\\)?:"
356 "while\\s +.*:"
357 "for\\s +.*:"
358 "if\\s +.*:"
359 "elif\\s +.*:"
360 (concat py-block-closing-keywords-re "[ \t\n]")
361 )
362 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000363 "\\)"))
364
365;; Regexp matching a function, method or variable assignment. If you
366;; change this, you probably have to change `py-current-defun' as
367;; well. This is only used by `py-current-defun' to find the name for
368;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000369(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000370 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
371
372;; Regexp for finding a class name. If you change this, you probably
373;; have to change `py-current-defun' as well. This is only used by
374;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000375(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
376
377;; Regexp that describes tracebacks
378(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000379 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000380
381
382
383;; Utilities
384
385(defmacro py-safe (&rest body)
386 ;; safely execute BODY, return nil if an error occurred
387 (` (condition-case nil
388 (progn (,@ body))
389 (error nil))))
390
391(defsubst py-keep-region-active ()
392 ;; Do whatever is necessary to keep the region active in XEmacs.
393 ;; Ignore byte-compiler warnings you might see. Also note that
394 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
395 ;; to take explicit action.
396 (and (boundp 'zmacs-region-stays)
397 (setq zmacs-region-stays t)))
398
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000399(defsubst py-point (position)
400 ;; Returns the value of point at certain commonly referenced POSITIONs.
401 ;; POSITION can be one of the following symbols:
402 ;;
403 ;; bol -- beginning of line
404 ;; eol -- end of line
405 ;; bod -- beginning of defun
406 ;; boi -- back to indentation
407 ;;
408 ;; This function does not modify point or mark.
409 (let ((here (point)))
410 (cond
411 ((eq position 'bol) (beginning-of-line))
412 ((eq position 'eol) (end-of-line))
413 ((eq position 'bod) (beginning-of-python-def-or-class))
414 ((eq position 'bob) (beginning-of-buffer))
415 ((eq position 'eob) (end-of-buffer))
416 ((eq position 'boi) (back-to-indentation))
417 (t (error "unknown buffer position requested: %s" position))
418 )
419 (prog1
420 (point)
421 (goto-char here))))
422
423(defsubst py-highlight-line (from to file line)
424 (cond
425 ((fboundp 'make-extent)
426 ;; XEmacs
427 (let ((e (make-extent from to)))
428 (set-extent-property e 'mouse-face 'highlight)
429 (set-extent-property e 'py-exc-info (cons file line))
430 (set-extent-property e 'keymap py-mode-output-map)))
431 (t
432 ;; Emacs -- Please port this!
433 )
434 ))
435
Barry Warsawc72c11c1997-08-09 06:42:08 +0000436
437;; Major mode boilerplate
438
Barry Warsaw7ae77681994-12-12 20:38:05 +0000439;; define a mode-specific abbrev table for those who use such things
440(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000441 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000442(define-abbrev-table 'python-mode-abbrev-table nil)
443
Barry Warsaw7ae77681994-12-12 20:38:05 +0000444(defvar python-mode-hook nil
445 "*Hook called by `python-mode'.")
446
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000447;; in previous version of python-mode.el, the hook was incorrectly
448;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000449(and (fboundp 'make-obsolete-variable)
450 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
451
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000452(defvar py-mode-map ()
453 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000454(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000455 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000456 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000457 ;; electric keys
458 (define-key py-mode-map ":" 'py-electric-colon)
459 ;; indentation level modifiers
460 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
461 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
462 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
463 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
464 ;; subprocess commands
465 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
466 (define-key py-mode-map "\C-c|" 'py-execute-region)
467 (define-key py-mode-map "\C-c!" 'py-shell)
468 ;; Caution! Enter here at your own risk. We are trying to support
469 ;; several behaviors and it gets disgusting. :-( This logic ripped
470 ;; largely from CC Mode.
471 ;;
472 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
473 ;; backwards deletion behavior to DEL, which both Delete and
474 ;; Backspace get translated to. There's no way to separate this
475 ;; behavior in a clean way, so deal with it! Besides, it's been
476 ;; this way since the dawn of time.
477 (if (not (boundp 'delete-key-deletes-forward))
478 (define-key py-mode-map "\177" 'py-electric-backspace)
479 ;; However, XEmacs 20 actually achieved enlightenment. It is
480 ;; possible to sanely define both backward and forward deletion
481 ;; behavior under X separately (TTYs are forever beyond hope, but
482 ;; who cares? XEmacs 20 does the right thing with these too).
483 (define-key py-mode-map [delete] 'py-electric-delete)
484 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000485 ;; Separate M-BS from C-M-h. The former should remain
486 ;; backward-kill-word.
487 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000488 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000489 ;; Miscellaneous
490 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
491 (define-key py-mode-map "\C-c\t" 'py-indent-region)
492 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
493 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
494 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000495 (define-key py-mode-map "\C-c#" 'py-comment-region)
496 (define-key py-mode-map "\C-c?" 'py-describe-mode)
497 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
498 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
499 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000500 (define-key py-mode-map "\C-c-" 'py-up-exception)
501 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000502 ;; information
503 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
504 (define-key py-mode-map "\C-c\C-v" 'py-version)
505 ;; py-newline-and-indent mappings
506 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000507 ;; shadow global bindings for newline-and-indent w/ the py- version.
508 ;; BAW - this is extremely bad form, but I'm not going to change it
509 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000510 (mapcar #'(lambda (key)
511 (define-key py-mode-map key 'py-newline-and-indent))
512 (where-is-internal 'newline-and-indent))
513 )
514
515(defvar py-mode-output-map nil
516 "Keymap used in *Python Output* buffers*")
517(if py-mode-output-map
518 nil
519 (setq py-mode-output-map (make-sparse-keymap))
520 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
521 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
522 ;; TBD: Disable all self-inserting keys. This is bogus, we should
523 ;; really implement this as *Python Output* buffer being read-only
524 (mapcar #' (lambda (key)
525 (define-key py-mode-output-map key
526 #'(lambda () (interactive) (beep))))
527 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000528 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000529
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000530(defvar py-mode-syntax-table nil
531 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000532(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000533 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000534 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000535 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
536 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
537 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
538 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
539 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
540 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
541 ;; Add operator symbols misassigned in the std table
542 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
543 (modify-syntax-entry ?\% "." py-mode-syntax-table)
544 (modify-syntax-entry ?\& "." py-mode-syntax-table)
545 (modify-syntax-entry ?\* "." py-mode-syntax-table)
546 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
547 (modify-syntax-entry ?\- "." py-mode-syntax-table)
548 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
549 (modify-syntax-entry ?\< "." py-mode-syntax-table)
550 (modify-syntax-entry ?\= "." py-mode-syntax-table)
551 (modify-syntax-entry ?\> "." py-mode-syntax-table)
552 (modify-syntax-entry ?\| "." py-mode-syntax-table)
553 ;; For historical reasons, underscore is word class instead of
554 ;; symbol class. GNU conventions say it should be symbol class, but
555 ;; there's a natural conflict between what major mode authors want
556 ;; and what users expect from `forward-word' and `backward-word'.
557 ;; Guido and I have hashed this out and have decided to keep
558 ;; underscore in word class. If you're tempted to change it, try
559 ;; binding M-f and M-b to py-forward-into-nomenclature and
560 ;; py-backward-into-nomenclature instead.
561 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
562 ;; Both single quote and double quote are string delimiters
563 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
564 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
565 ;; backquote is open and close paren
566 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
567 ;; comment delimiters
568 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
569 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
570 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000571
Barry Warsawb3e81d51996-09-04 15:12:42 +0000572
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000573
Barry Warsaw42f707f1996-07-29 21:05:05 +0000574;; Menu definitions, only relevent if you have the easymenu.el package
575;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000576(defvar py-menu nil
577 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000578This menu will get created automatically if you have the `easymenu'
579package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000580
Barry Warsawc72c11c1997-08-09 06:42:08 +0000581(and (py-safe (require 'easymenu) t)
582 (easy-menu-define
583 py-menu py-mode-map "Python Mode menu"
584 '("Python"
585 ["Comment Out Region" py-comment-region (mark)]
586 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
587 "-"
588 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000589 ["Mark current def" py-mark-def-or-class t]
590 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000591 "-"
592 ["Shift region left" py-shift-region-left (mark)]
593 ["Shift region right" py-shift-region-right (mark)]
594 "-"
595 ["Execute buffer" py-execute-buffer t]
596 ["Execute region" py-execute-region (mark)]
597 ["Start interpreter..." py-shell t]
598 "-"
599 ["Go to start of block" py-goto-block-up t]
600 ["Go to start of class" (beginning-of-python-def-or-class t) t]
601 ["Move to end of class" (end-of-python-def-or-class t) t]
602 ["Move to start of def" beginning-of-python-def-or-class t]
603 ["Move to end of def" end-of-python-def-or-class t]
604 "-"
605 ["Describe mode" py-describe-mode t]
606 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000607
Barry Warsaw81437461996-08-01 19:48:02 +0000608
609
610;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
611(defvar imenu-example--python-class-regexp
612 (concat ; <<classes>>
613 "\\(" ;
614 "^[ \t]*" ; newline and maybe whitespace
615 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
616 ; possibly multiple superclasses
617 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
618 "[ \t]*:" ; and the final :
619 "\\)" ; >>classes<<
620 )
621 "Regexp for Python classes for use with the imenu package."
622 )
623
624(defvar imenu-example--python-method-regexp
625 (concat ; <<methods and functions>>
626 "\\(" ;
627 "^[ \t]*" ; new line and maybe whitespace
628 "\\(def[ \t]+" ; function definitions start with def
629 "\\([a-zA-Z0-9_]+\\)" ; name is here
630 ; function arguments...
631 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
632 "\\)" ; end of def
633 "[ \t]*:" ; and then the :
634 "\\)" ; >>methods and functions<<
635 )
636 "Regexp for Python methods/functions for use with the imenu package."
637 )
638
639(defvar imenu-example--python-method-no-arg-parens '(2 8)
640 "Indicies into groups of the Python regexp for use with imenu.
641
642Using these values will result in smaller imenu lists, as arguments to
643functions are not listed.
644
645See the variable `imenu-example--python-show-method-args-p' for more
646information.")
647
648(defvar imenu-example--python-method-arg-parens '(2 7)
649 "Indicies into groups of the Python regexp for use with imenu.
650Using these values will result in large imenu lists, as arguments to
651functions are listed.
652
653See the variable `imenu-example--python-show-method-args-p' for more
654information.")
655
656;; Note that in this format, this variable can still be used with the
657;; imenu--generic-function. Otherwise, there is no real reason to have
658;; it.
659(defvar imenu-example--generic-python-expression
660 (cons
661 (concat
662 imenu-example--python-class-regexp
663 "\\|" ; or...
664 imenu-example--python-method-regexp
665 )
666 imenu-example--python-method-no-arg-parens)
667 "Generic Python expression which may be used directly with imenu.
668Used by setting the variable `imenu-generic-expression' to this value.
669Also, see the function \\[imenu-example--create-python-index] for a
670better alternative for finding the index.")
671
672;; These next two variables are used when searching for the python
673;; class/definitions. Just saving some time in accessing the
674;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000675(defvar imenu-example--python-generic-regexp nil)
676(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000677
678
Barry Warsaw81437461996-08-01 19:48:02 +0000679(defun imenu-example--create-python-index ()
680 "Python interface function for imenu package.
681Finds all python classes and functions/methods. Calls function
682\\[imenu-example--create-python-index-engine]. See that function for
683the details of how this works."
684 (setq imenu-example--python-generic-regexp
685 (car imenu-example--generic-python-expression))
686 (setq imenu-example--python-generic-parens
687 (if imenu-example--python-show-method-args-p
688 imenu-example--python-method-arg-parens
689 imenu-example--python-method-no-arg-parens))
690 (goto-char (point-min))
691 (imenu-example--create-python-index-engine nil))
692
693(defun imenu-example--create-python-index-engine (&optional start-indent)
694 "Function for finding imenu definitions in Python.
695
696Finds all definitions (classes, methods, or functions) in a Python
697file for the imenu package.
698
699Returns a possibly nested alist of the form
700
701 (INDEX-NAME . INDEX-POSITION)
702
703The second element of the alist may be an alist, producing a nested
704list as in
705
706 (INDEX-NAME . INDEX-ALIST)
707
708This function should not be called directly, as it calls itself
709recursively and requires some setup. Rather this is the engine for
710the function \\[imenu-example--create-python-index].
711
712It works recursively by looking for all definitions at the current
713indention level. When it finds one, it adds it to the alist. If it
714finds a definition at a greater indentation level, it removes the
715previous definition from the alist. In it's place it adds all
716definitions found at the next indentation level. When it finds a
717definition that is less indented then the current level, it retuns the
718alist it has created thus far.
719
720The optional argument START-INDENT indicates the starting indentation
721at which to continue looking for Python classes, methods, or
722functions. If this is not supplied, the function uses the indentation
723of the first definition found."
724 (let ((index-alist '())
725 (sub-method-alist '())
726 looking-p
727 def-name prev-name
728 cur-indent def-pos
729 (class-paren (first imenu-example--python-generic-parens))
730 (def-paren (second imenu-example--python-generic-parens)))
731 (setq looking-p
732 (re-search-forward imenu-example--python-generic-regexp
733 (point-max) t))
734 (while looking-p
735 (save-excursion
736 ;; used to set def-name to this value but generic-extract-name is
737 ;; new to imenu-1.14. this way it still works with imenu-1.11
738 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
739 (let ((cur-paren (if (match-beginning class-paren)
740 class-paren def-paren)))
741 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000742 (buffer-substring-no-properties (match-beginning cur-paren)
743 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000744 (beginning-of-line)
745 (setq cur-indent (current-indentation)))
746
747 ;; HACK: want to go to the next correct definition location. we
748 ;; explicitly list them here. would be better to have them in a
749 ;; list.
750 (setq def-pos
751 (or (match-beginning class-paren)
752 (match-beginning def-paren)))
753
754 ;; if we don't have a starting indent level, take this one
755 (or start-indent
756 (setq start-indent cur-indent))
757
758 ;; if we don't have class name yet, take this one
759 (or prev-name
760 (setq prev-name def-name))
761
762 ;; what level is the next definition on? must be same, deeper
763 ;; or shallower indentation
764 (cond
765 ;; at the same indent level, add it to the list...
766 ((= start-indent cur-indent)
767
768 ;; if we don't have push, use the following...
769 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
770 (push (cons def-name def-pos) index-alist))
771
772 ;; deeper indented expression, recur...
773 ((< start-indent cur-indent)
774
775 ;; the point is currently on the expression we're supposed to
776 ;; start on, so go back to the last expression. The recursive
777 ;; call will find this place again and add it to the correct
778 ;; list
779 (re-search-backward imenu-example--python-generic-regexp
780 (point-min) 'move)
781 (setq sub-method-alist (imenu-example--create-python-index-engine
782 cur-indent))
783
784 (if sub-method-alist
785 ;; we put the last element on the index-alist on the start
786 ;; of the submethod alist so the user can still get to it.
787 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000788 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000789 (cons save-elmt sub-method-alist))
790 index-alist))))
791
792 ;; found less indented expression, we're done.
793 (t
794 (setq looking-p nil)
795 (re-search-backward imenu-example--python-generic-regexp
796 (point-min) t)))
797 (setq prev-name def-name)
798 (and looking-p
799 (setq looking-p
800 (re-search-forward imenu-example--python-generic-regexp
801 (point-max) 'move))))
802 (nreverse index-alist)))
803
Barry Warsaw42f707f1996-07-29 21:05:05 +0000804
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000805;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000806(defun python-mode ()
807 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000808To submit a problem report, enter `\\[py-submit-bug-report]' from a
809`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
810documentation. To see what version of `python-mode' you are running,
811enter `\\[py-version]'.
812
813This mode knows about Python indentation, tokens, comments and
814continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000815
816COMMANDS
817\\{py-mode-map}
818VARIABLES
819
Barry Warsaw42f707f1996-07-29 21:05:05 +0000820py-indent-offset\t\tindentation increment
821py-block-comment-prefix\t\tcomment string used by comment-region
822py-python-command\t\tshell command to invoke Python interpreter
823py-scroll-process-buffer\t\talways scroll Python process buffer
824py-temp-directory\t\tdirectory used for temp files (if needed)
825py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000826 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000827 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000828 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000829 (make-local-variable 'font-lock-defaults)
830 (make-local-variable 'paragraph-separate)
831 (make-local-variable 'paragraph-start)
832 (make-local-variable 'require-final-newline)
833 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000834 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000835 (make-local-variable 'comment-start-skip)
836 (make-local-variable 'comment-column)
837 (make-local-variable 'indent-region-function)
838 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000839 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000840 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000841 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000842 (setq major-mode 'python-mode
843 mode-name "Python"
844 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000845 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000846 paragraph-separate "^[ \t]*$"
847 paragraph-start "^[ \t]*$"
848 require-final-newline t
849 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000850 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000851 comment-start-skip "# *"
852 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000853 indent-region-function 'py-indent-region
854 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000855 ;; tell add-log.el how to find the current function/method/variable
856 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000857 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000858 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000859 ;; add the menu
860 (if py-menu
861 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000862 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000863 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000864 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000865 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000866 ;;
867 ;; not sure where the magic comment has to be; to save time
868 ;; searching for a rarity, we give up if it's not found prior to the
869 ;; first executable statement.
870 ;;
871 ;; BAW - on first glance, this seems like complete hackery. Why was
872 ;; this necessary, and is it still necessary?
873 (let ((case-fold-search nil)
874 (start (point))
875 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876 (if (re-search-forward
877 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
878 (prog2 (py-next-statement 1) (point) (goto-char 1))
879 t)
880 (progn
881 (setq new-tab-width
882 (string-to-int
883 (buffer-substring (match-beginning 1) (match-end 1))))
884 (if (= tab-width new-tab-width)
885 nil
886 (setq tab-width new-tab-width)
887 (message "Caution: tab-width changed to %d" new-tab-width)
888 (if py-beep-if-tab-change (beep)))))
889 (goto-char start))
890
Barry Warsaw755c6711996-08-01 20:02:55 +0000891 ;; install imenu
Barry Warsaw27ee1151997-12-03 05:03:44 +0000892 (if (py-safe (require 'imenu))
893 (progn
894 (make-variable-buffer-local 'imenu-create-index-function)
895 (setq imenu-create-index-function
896 (function imenu-example--create-python-index))
897 (setq imenu-generic-expression
898 imenu-example--generic-python-expression)
899 (if (fboundp 'imenu-add-to-menubar)
900 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
901 ))
Barry Warsaw755c6711996-08-01 20:02:55 +0000902
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000903 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000904 (if python-mode-hook
905 (run-hooks 'python-mode-hook)
906 (run-hooks 'py-mode-hook)))
907
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908
Barry Warsawb91b7431995-03-14 15:55:20 +0000909;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000910(defun py-outdent-p ()
911 ;; returns non-nil if the current line should outdent one level
912 (save-excursion
913 (and (progn (back-to-indentation)
914 (looking-at py-outdent-re))
915 (progn (backward-to-indentation 1)
916 (while (or (looking-at py-blank-or-comment-re)
917 (bobp))
918 (backward-to-indentation 1))
919 (not (looking-at py-no-outdent-re)))
920 )))
921
Barry Warsawb91b7431995-03-14 15:55:20 +0000922(defun py-electric-colon (arg)
923 "Insert a colon.
924In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000925argument is provided, that many colons are inserted non-electrically.
926Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000927 (interactive "P")
928 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000929 ;; are we in a string or comment?
930 (if (save-excursion
931 (let ((pps (parse-partial-sexp (save-excursion
932 (beginning-of-python-def-or-class)
933 (point))
934 (point))))
935 (not (or (nth 3 pps) (nth 4 pps)))))
936 (save-excursion
937 (let ((here (point))
938 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000939 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000940 (if (and (not arg)
941 (py-outdent-p)
942 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000943 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000944 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000945 )
946 (setq outdent py-indent-offset))
947 ;; Don't indent, only outdent. This assumes that any lines that
948 ;; are already outdented relative to py-compute-indentation were
949 ;; put there on purpose. Its highly annoying to have `:' indent
950 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
951 ;; there a better way to determine this???
952 (if (< (current-indentation) indent) nil
953 (goto-char here)
954 (beginning-of-line)
955 (delete-horizontal-space)
956 (indent-to (- indent outdent))
957 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000958
959
Barry Warsawa97a3f31997-11-04 18:47:06 +0000960;; Python subprocess utilities and filters
961(defun py-execute-file (proc filename)
962 ;; Send a properly formatted execfile('FILENAME') to the underlying
963 ;; Python interpreter process FILENAME. Make that process's buffer
964 ;; visible and force display. Also make comint believe the user
965 ;; typed this string so that kill-output-from-shell does The Right
966 ;; Thing.
967 (let ((curbuf (current-buffer))
968 (procbuf (process-buffer proc))
969 (comint-scroll-to-bottom-on-output t)
970 (msg (format "## working on region in file %s...\n" filename))
971 (cmd (format "execfile('%s')\n" filename)))
972 (unwind-protect
973 (progn
974 (set-buffer procbuf)
975 (goto-char (point-max))
976 (move-marker (process-mark proc) (point))
977 (funcall (process-filter proc) proc msg))
978 (set-buffer curbuf))
979 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000980
981(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000982 (let ((curbuf (current-buffer))
983 (pbuf (process-buffer pyproc))
984 (pmark (process-mark pyproc))
985 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000986 ;; make sure we switch to a different buffer at least once. if we
987 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000988 ;; window, and point is before the end, and lots of output is
989 ;; coming at a fast pace, then (a) simple cursor-movement commands
990 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
991 ;; to have a visible effect (the window just doesn't get updated,
992 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
993 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000994 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000995 ;; #b makes no sense to me at all. #a almost makes sense: unless
996 ;; we actually change buffers, set_buffer_internal in buffer.c
997 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
998 ;; seems to make the Emacs command loop reluctant to update the
999 ;; display. Perhaps the default process filter in process.c's
1000 ;; read_process_output has update_mode_lines++ for a similar
1001 ;; reason? beats me ...
1002
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001003 (unwind-protect
1004 ;; make sure current buffer is restored
1005 ;; BAW - we want to check to see if this still applies
1006 (progn
1007 ;; mysterious ugly hack
1008 (if (eq curbuf pbuf)
1009 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001010
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001011 (set-buffer pbuf)
1012 (let* ((start (point))
1013 (goback (< start pmark))
1014 (goend (and (not goback) (= start (point-max))))
1015 (buffer-read-only nil))
1016 (goto-char pmark)
1017 (insert string)
1018 (move-marker pmark (point))
1019 (setq file-finished
1020 (and py-file-queue
1021 (equal ">>> "
1022 (buffer-substring
1023 (prog2 (beginning-of-line) (point)
1024 (goto-char pmark))
1025 (point)))))
1026 (if goback (goto-char start)
1027 ;; else
1028 (if py-scroll-process-buffer
1029 (let* ((pop-up-windows t)
1030 (pwin (display-buffer pbuf)))
1031 (set-window-point pwin (point)))))
1032 (set-buffer curbuf)
1033 (if file-finished
1034 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001035 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001036 (setq py-file-queue (cdr py-file-queue))
1037 (if py-file-queue
1038 (py-execute-file pyproc (car py-file-queue)))))
1039 (and goend
1040 (progn (set-buffer pbuf)
1041 (goto-char (point-max))))
1042 ))
1043 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001044
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001045(defun py-postprocess-output-buffer (buf)
1046 (save-excursion
1047 (set-buffer buf)
1048 (beginning-of-buffer)
1049 (while (re-search-forward py-traceback-line-re nil t)
1050 (let ((file (match-string 1))
1051 (line (string-to-int (match-string 2))))
1052 (py-highlight-line (py-point 'bol) (py-point 'eol) file line))
1053 )))
1054
Barry Warsawa97a3f31997-11-04 18:47:06 +00001055
1056;;; Subprocess commands
1057
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001058;; only used when (memq 'broken-temp-names py-emacs-features)
1059(defvar py-serial-number 0)
1060(defvar py-exception-buffer nil)
1061(defconst py-output-buffer "*Python Output*")
1062
Barry Warsawa97a3f31997-11-04 18:47:06 +00001063;;;###autoload
1064(defun py-shell ()
1065 "Start an interactive Python interpreter in another window.
1066This is like Shell mode, except that Python is running in the window
1067instead of a shell. See the `Interactive Shell' and `Shell Mode'
1068sections of the Emacs manual for details, especially for the key
1069bindings active in the `*Python*' buffer.
1070
1071See the docs for variable `py-scroll-buffer' for info on scrolling
1072behavior in the process window.
1073
1074Warning: Don't use an interactive Python if you change sys.ps1 or
1075sys.ps2 from their default values, or if you're running code that
1076prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1077distinguish your output from Python's output, and assumes that `>>> '
1078at the start of a line is a prompt from Python. Similarly, the Emacs
1079Shell mode code assumes that both `>>> ' and `... ' at the start of a
1080line are Python prompts. Bad things can happen if you fool either
1081mode.
1082
1083Warning: If you do any editing *in* the process buffer *while* the
1084buffer is accepting output from Python, do NOT attempt to `undo' the
1085changes. Some of the output (nowhere near the parts you changed!) may
1086be lost if you do. This appears to be an Emacs bug, an unfortunate
1087interaction between undo and process filters; the same problem exists in
1088non-Python process buffers using the default (Emacs-supplied) process
1089filter."
1090 ;; BAW - should undo be disabled in the python process buffer, if
1091 ;; this bug still exists?
1092 (interactive)
1093 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001094 (switch-to-buffer-other-window
1095 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001096 (make-local-variable 'comint-prompt-regexp)
1097 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1098 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1099 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001100 ;; set up keybindings for this subshell
1101 (local-set-key [tab] 'self-insert-command)
1102 (local-set-key "\C-c-" 'py-up-exception)
1103 (local-set-key "\C-c=" 'py-down-exception)
1104 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001105
Barry Warsawa97a3f31997-11-04 18:47:06 +00001106(defun py-clear-queue ()
1107 "Clear the queue of temporary files waiting to execute."
1108 (interactive)
1109 (let ((n (length py-file-queue)))
1110 (mapcar 'delete-file py-file-queue)
1111 (setq py-file-queue nil)
1112 (message "%d pending files de-queued." n)))
1113
1114(defun py-execute-region (start end &optional async)
1115 "Execute the the region in a Python interpreter.
1116The region is first copied into a temporary file (in the directory
1117`py-temp-directory'). If there is no Python interpreter shell
1118running, this file is executed synchronously using
1119`shell-command-on-region'. If the program is long running, use an
1120optional \\[universal-argument] to run the command asynchronously in
1121its own buffer.
1122
1123If the Python interpreter shell is running, the region is execfile()'d
1124in that shell. If you try to execute regions too quickly,
1125`python-mode' will queue them up and execute them one at a time when
1126it sees a `>>> ' prompt from Python. Each time this happens, the
1127process buffer is popped into a window (if it's not already in some
1128window) so you can see it, and a comment of the form
1129
1130 \t## working on region in file <name>...
1131
1132is inserted at the end. See also the command `py-clear-queue'."
1133 (interactive "r\nP")
1134 (or (< start end)
1135 (error "Region is empty"))
1136 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001137 (temp (if (memq 'broken-temp-names py-emacs-features)
1138 (prog1
1139 (format "python-%d" py-serial-number)
1140 (setq py-serial-number (1+ py-serial-number)))
1141 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001142 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001143 (write-region start end file nil 'nomsg)
1144 (cond
1145 ;; always run the code in it's own asynchronous subprocess
1146 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001147 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001148 (start-process "Python" buf py-python-command "-u" file)
1149 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001150 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001151 ))
1152 ;; if the Python interpreter shell is running, queue it up for
1153 ;; execution there.
1154 (proc
1155 ;; use the existing python shell
1156 (if (not py-file-queue)
1157 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001158 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001159 (push file py-file-queue)
1160 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001161 (t
1162 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001163 (shell-command-on-region start end py-python-command py-output-buffer)
1164 (setq py-exception-buffer (current-buffer))
1165 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001166 ))))
1167
1168;; Code execution command
1169(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001170 "Send the contents of the buffer to a Python interpreter.
1171If there is a *Python* process buffer it is used. If a clipping
1172restriction is in effect, only the accessible portion of the buffer is
1173sent. A trailing newline will be supplied if needed.
1174
1175See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001176 (interactive "P")
1177 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001178
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001179
1180
1181(defun py-jump-to-exception (file line)
1182 (let ((buffer (cond ((string-equal file "<stdin>")
1183 py-exception-buffer)
1184 ((and (consp py-exception-buffer)
1185 (string-equal file (car py-exception-buffer)))
1186 (cdr py-exception-buffer))
1187 ((py-safe (find-file-noselect file)))
1188 ;; could not figure out what file the exception
1189 ;; is pointing to, so prompt for it
1190 (t (find-file (read-file-name "Exception file: "
1191 nil
1192 file t))))))
1193 (pop-to-buffer buffer)
1194 (goto-line line)
1195 (message "Jumping to exception in file %s on line %d" file line)))
1196
1197(defun py-mouseto-exception (event)
1198 (interactive "e")
1199 (cond
1200 ((fboundp 'event-point)
1201 ;; XEmacs
1202 (let* ((point (event-point event))
1203 (buffer (event-buffer event))
1204 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1205 (info (and e (extent-property e 'py-exc-info))))
1206 (message "Event point: %d, info: %s" point info)
1207 (and info
1208 (py-jump-to-exception (car info) (cdr info)))
1209 ))
1210 ;; Emacs -- Please port this!
1211 ))
1212
1213(defun py-goto-exception ()
1214 "Go to the line indicated by the traceback."
1215 (interactive)
1216 (let (file line)
1217 (save-excursion
1218 (beginning-of-line)
1219 (if (looking-at py-traceback-line-re)
1220 (setq file (match-string 1)
1221 line (string-to-int (match-string 2)))))
1222 (if (not file)
1223 (error "Not on a traceback line."))
1224 (py-jump-to-exception file line)))
1225
1226(defun py-find-next-exception (start buffer searchdir errwhere)
1227 ;; Go to start position in buffer, search in the specified
1228 ;; direction, and jump to the exception found. If at the end of the
1229 ;; exception, print error message
1230 (let (file line)
1231 (save-excursion
1232 (set-buffer buffer)
1233 (goto-char (py-point start))
1234 (if (funcall searchdir py-traceback-line-re nil t)
1235 (setq file (match-string 1)
1236 line (string-to-int (match-string 2)))))
1237 (if (and file line)
1238 (py-jump-to-exception file line)
1239 (error "%s of traceback" errwhere))))
1240
1241(defun py-down-exception (&optional bottom)
1242 "Go to the next line down in the traceback.
1243With optional \\[universal-argument], jump to the bottom (innermost)
1244exception in the exception stack."
1245 (interactive "P")
1246 (let* ((proc (get-process "Python"))
1247 (buffer (if proc "*Python*" py-output-buffer)))
1248 (if bottom
1249 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1250 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1251
1252(defun py-up-exception (&optional top)
1253 "Go to the previous line up in the traceback.
1254With optional \\[universal-argument], jump to the top (outermost)
1255exception in the exception stack."
1256 (interactive "P")
1257 (let* ((proc (get-process "Python"))
1258 (buffer (if proc "*Python*" py-output-buffer)))
1259 (if top
1260 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001261 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001262
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001263
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001264;; Electric deletion
1265(defun py-electric-backspace (arg)
1266 "Deletes preceding character or levels of indentation.
1267Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001268with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001269
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001270If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001271
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001272Otherwise, if point is at the leftmost non-whitespace character of a
1273line that is neither a continuation line nor a non-indenting comment
1274line, or if point is at the end of a blank line, this command reduces
1275the indentation to match that of the line that opened the current
1276block of code. The line that opened the block is displayed in the
1277echo area to help you keep track of where you are. With numeric arg,
1278outdents that many blocks (but not past column zero).
1279
1280Otherwise the preceding character is deleted, converting a tab to
1281spaces if needed so that only a single column position is deleted.
1282Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001283 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001284 (if (or (/= (current-indentation) (current-column))
1285 (bolp)
1286 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001287 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001288 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001289 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001291 ;; force non-blank so py-goto-block-up doesn't ignore it
1292 (insert-char ?* 1)
1293 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001294 (let ((base-indent 0) ; indentation of base line
1295 (base-text "") ; and text of base line
1296 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001297 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001298 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001299 (condition-case nil ; in case no enclosing block
1300 (progn
1301 (py-goto-block-up 'no-mark)
1302 (setq base-indent (current-indentation)
1303 base-text (py-suck-up-leading-text)
1304 base-found-p t))
1305 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001306 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001307 (delete-char 1) ; toss the dummy character
1308 (delete-horizontal-space)
1309 (indent-to base-indent)
1310 (if base-found-p
1311 (message "Closes block: %s" base-text)))))
1312
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001313
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001314(defun py-electric-delete (arg)
1315 "Deletes preceding or following character or levels of whitespace.
1316
1317The behavior of this function depends on the variable
1318`delete-key-deletes-forward'. If this variable is nil (or does not
1319exist, as in older Emacsen), then this function behaves identical to
1320\\[c-electric-backspace].
1321
1322If `delete-key-deletes-forward' is non-nil and is supported in your
1323Emacs, then deletion occurs in the forward direction, by calling the
1324function in `py-delete-function'."
1325 (interactive "*p")
1326 (if (and (boundp 'delete-key-deletes-forward)
1327 delete-key-deletes-forward)
1328 (funcall py-delete-function arg)
1329 ;; else
1330 (py-electric-backspace arg)))
1331
1332;; required for pending-del and delsel modes
1333(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1334(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1335(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1336(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1337
1338
1339
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001340(defun py-indent-line (&optional arg)
1341 "Fix the indentation of the current line according to Python rules.
1342With \\[universal-argument], ignore outdenting rules for block
1343closing statements (e.g. return, raise, break, continue, pass)
1344
1345This function is normally bound to `indent-line-function' so
1346\\[indent-for-tab-command] will call it."
1347 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348 (let* ((ci (current-indentation))
1349 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001350 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001351 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001352 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001353 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354 (if (/= ci need)
1355 (save-excursion
1356 (beginning-of-line)
1357 (delete-horizontal-space)
1358 (indent-to need)))
1359 (if move-to-indentation-p (back-to-indentation))))
1360
1361(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001362 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001363This is just `strives to' because correct indentation can't be computed
1364from scratch for Python code. In general, deletes the whitespace before
1365point, inserts a newline, and takes an educated guess as to how you want
1366the new line indented."
1367 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001368 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369 (if (< ci (current-column)) ; if point beyond indentation
1370 (newline-and-indent)
1371 ;; else try to act like newline-and-indent "normally" acts
1372 (beginning-of-line)
1373 (insert-char ?\n 1)
1374 (move-to-column ci))))
1375
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001376(defun py-compute-indentation (honor-block-close-p)
1377 ;; implements all the rules for indentation computation. when
1378 ;; honor-block-close-p is non-nil, statements such as return, raise,
1379 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001381 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001382 (pps (parse-partial-sexp bod (point)))
1383 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001384 (beginning-of-line)
1385 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001386 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001387 ((or (and (nth 3 pps) (nth 3 boipps))
1388 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001389 (save-excursion
1390 (if (not py-align-multiline-strings-p) 0
1391 ;; skip back over blank & non-indenting comment lines
1392 ;; note: will skip a blank or non-indenting comment line
1393 ;; that happens to be a continuation line too
1394 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1395 (back-to-indentation)
1396 (current-column))))
1397 ;; are we on a continuation line?
1398 ((py-continuation-line-p)
1399 (let ((startpos (point))
1400 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001401 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001402 (if open-bracket-pos
1403 (progn
1404 ;; align with first item in list; else a normal
1405 ;; indent beyond the line with the open bracket
1406 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1407 ;; is the first list item on the same line?
1408 (skip-chars-forward " \t")
1409 (if (null (memq (following-char) '(?\n ?# ?\\)))
1410 ; yes, so line up with it
1411 (current-column)
1412 ;; first list item on another line, or doesn't exist yet
1413 (forward-line 1)
1414 (while (and (< (point) startpos)
1415 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1416 (forward-line 1))
1417 (if (< (point) startpos)
1418 ;; again mimic the first list item
1419 (current-indentation)
1420 ;; else they're about to enter the first item
1421 (goto-char open-bracket-pos)
1422 (+ (current-indentation) py-indent-offset))))
1423
1424 ;; else on backslash continuation line
1425 (forward-line -1)
1426 (if (py-continuation-line-p) ; on at least 3rd line in block
1427 (current-indentation) ; so just continue the pattern
1428 ;; else started on 2nd line in block, so indent more.
1429 ;; if base line is an assignment with a start on a RHS,
1430 ;; indent to 2 beyond the leftmost "="; else skip first
1431 ;; chunk of non-whitespace characters on base line, + 1 more
1432 ;; column
1433 (end-of-line)
1434 (setq endpos (point) searching t)
1435 (back-to-indentation)
1436 (setq startpos (point))
1437 ;; look at all "=" from left to right, stopping at first
1438 ;; one not nested in a list or string
1439 (while searching
1440 (skip-chars-forward "^=" endpos)
1441 (if (= (point) endpos)
1442 (setq searching nil)
1443 (forward-char 1)
1444 (setq state (parse-partial-sexp startpos (point)))
1445 (if (and (zerop (car state)) ; not in a bracket
1446 (null (nth 3 state))) ; & not in a string
1447 (progn
1448 (setq searching nil) ; done searching in any case
1449 (setq found
1450 (not (or
1451 (eq (following-char) ?=)
1452 (memq (char-after (- (point) 2))
1453 '(?< ?> ?!)))))))))
1454 (if (or (not found) ; not an assignment
1455 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1456 (progn
1457 (goto-char startpos)
1458 (skip-chars-forward "^ \t\n")))
1459 (1+ (current-column))))))
1460
1461 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001462 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001463
Barry Warsawa7891711996-08-01 15:53:09 +00001464 ;; Dfn: "Indenting comment line". A line containing only a
1465 ;; comment, but which is treated like a statement for
1466 ;; indentation calculation purposes. Such lines are only
1467 ;; treated specially by the mode; they are not treated
1468 ;; specially by the Python interpreter.
1469
1470 ;; The rules for indenting comment lines are a line where:
1471 ;; - the first non-whitespace character is `#', and
1472 ;; - the character following the `#' is whitespace, and
1473 ;; - the line is outdented with respect to (i.e. to the left
1474 ;; of) the indentation of the preceding non-blank line.
1475
1476 ;; The first non-blank line following an indenting comment
1477 ;; line is given the same amount of indentation as the
1478 ;; indenting comment line.
1479
1480 ;; All other comment-only lines are ignored for indentation
1481 ;; purposes.
1482
1483 ;; Are we looking at a comment-only line which is *not* an
1484 ;; indenting comment line? If so, we assume that its been
1485 ;; placed at the desired indentation, so leave it alone.
1486 ;; Indenting comment lines are aligned as statements down
1487 ;; below.
1488 ((and (looking-at "[ \t]*#[^ \t\n]")
1489 ;; NOTE: this test will not be performed in older Emacsen
1490 (fboundp 'forward-comment)
1491 (<= (current-indentation)
1492 (save-excursion
1493 (forward-comment (- (point-max)))
1494 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001495 (current-indentation))
1496
1497 ;; else indentation based on that of the statement that
1498 ;; precedes us; use the first line of that statement to
1499 ;; establish the base, in case the user forced a non-std
1500 ;; indentation for the continuation lines (if any)
1501 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001502 ;; skip back over blank & non-indenting comment lines note:
1503 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001504 ;; happens to be a continuation line too. use fast Emacs 19
1505 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001506 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001507 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001508 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001509 (let (done)
1510 (while (not done)
1511 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1512 nil 'move)
1513 (setq done (or (eq py-honor-comment-indentation t)
1514 (bobp)
1515 (/= (following-char) ?#)
1516 (not (zerop (current-column)))))
1517 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001518 ;; if we landed inside a string, go to the beginning of that
1519 ;; string. this handles triple quoted, multi-line spanning
1520 ;; strings.
1521 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001522 (+ (current-indentation)
1523 (if (py-statement-opens-block-p)
1524 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001525 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001526 (- py-indent-offset)
1527 0)))
1528 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001529
1530(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001532By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001533`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001534Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001535`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536their own buffer-local copy), both those currently existing and those
1537created later in the Emacs session.
1538
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001540There's no excuse for such foolishness, but sometimes you have to deal
1541with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542`py-indent-offset' to what it thinks it was when they created the
1543mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544
1545Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546looking for a line that opens a block of code. `py-indent-offset' is
1547set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548statement following it. If the search doesn't succeed going forward,
1549it's tried again going backward."
1550 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551 (let (new-value
1552 (start (point))
1553 restart
1554 (found nil)
1555 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001556 (py-goto-initial-line)
1557 (while (not (or found (eobp)))
1558 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1559 (progn
1560 (setq restart (point))
1561 (py-goto-initial-line)
1562 (if (py-statement-opens-block-p)
1563 (setq found t)
1564 (goto-char restart)))))
1565 (if found
1566 ()
1567 (goto-char start)
1568 (py-goto-initial-line)
1569 (while (not (or found (bobp)))
1570 (setq found
1571 (and
1572 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1573 (or (py-goto-initial-line) t) ; always true -- side effect
1574 (py-statement-opens-block-p)))))
1575 (setq colon-indent (current-indentation)
1576 found (and found (zerop (py-next-statement 1)))
1577 new-value (- (current-indentation) colon-indent))
1578 (goto-char start)
1579 (if found
1580 (progn
1581 (funcall (if global 'kill-local-variable 'make-local-variable)
1582 'py-indent-offset)
1583 (setq py-indent-offset new-value)
1584 (message "%s value of py-indent-offset set to %d"
1585 (if global "Global" "Local")
1586 py-indent-offset))
1587 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1588
1589(defun py-shift-region (start end count)
1590 (save-excursion
1591 (goto-char end) (beginning-of-line) (setq end (point))
1592 (goto-char start) (beginning-of-line) (setq start (point))
1593 (indent-rigidly start end count)))
1594
1595(defun py-shift-region-left (start end &optional count)
1596 "Shift region of Python code to the left.
1597The lines from the line containing the start of the current region up
1598to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001599shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600
1601If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001602many columns. With no active region, outdent only the current line.
1603You cannot outdent the region if any line is already at column zero."
1604 (interactive
1605 (let ((p (point))
1606 (m (mark))
1607 (arg current-prefix-arg))
1608 (if m
1609 (list (min p m) (max p m) arg)
1610 (list p (save-excursion (forward-line 1) (point)) arg))))
1611 ;; if any line is at column zero, don't shift the region
1612 (save-excursion
1613 (goto-char start)
1614 (while (< (point) end)
1615 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001616 (if (and (zerop (current-column))
1617 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001618 (error "Region is at left edge."))
1619 (forward-line 1)))
1620 (py-shift-region start end (- (prefix-numeric-value
1621 (or count py-indent-offset))))
1622 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001623
1624(defun py-shift-region-right (start end &optional count)
1625 "Shift region of Python code to the right.
1626The lines from the line containing the start of the current region up
1627to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001628shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001629
1630If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001631many columns. With no active region, indent only the current line."
1632 (interactive
1633 (let ((p (point))
1634 (m (mark))
1635 (arg current-prefix-arg))
1636 (if m
1637 (list (min p m) (max p m) arg)
1638 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001639 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001640 (or count py-indent-offset)))
1641 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001642
1643(defun py-indent-region (start end &optional indent-offset)
1644 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001645
Barry Warsaw7ae77681994-12-12 20:38:05 +00001646The lines from the line containing the start of the current region up
1647to (but not including) the line containing the end of the region are
1648reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001649character in the first column, the first line is left alone and the
1650rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001651region is reindented with respect to the (closest code or indenting
1652comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001653
1654This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001655control structures are introduced or removed, or to reformat code
1656using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657
1658If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660used.
1661
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663is called! This function does not compute proper indentation from
1664scratch (that's impossible in Python), it merely adjusts the existing
1665indentation to be correct in context.
1666
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667Warning: This function really has no idea what to do with
1668non-indenting comment lines, and shifts them as if they were indenting
1669comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001670
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001671Special cases: whitespace is deleted from blank lines; continuation
1672lines are shifted by the same amount their initial line was shifted,
1673in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001675 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001676 (save-excursion
1677 (goto-char end) (beginning-of-line) (setq end (point-marker))
1678 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001679 (let ((py-indent-offset (prefix-numeric-value
1680 (or indent-offset py-indent-offset)))
1681 (indents '(-1)) ; stack of active indent levels
1682 (target-column 0) ; column to which to indent
1683 (base-shifted-by 0) ; amount last base line was shifted
1684 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001685 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001686 0))
1687 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001688 (while (< (point) end)
1689 (setq ci (current-indentation))
1690 ;; figure out appropriate target column
1691 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001692 ((or (eq (following-char) ?#) ; comment in column 1
1693 (looking-at "[ \t]*$")) ; entirely blank
1694 (setq target-column 0))
1695 ((py-continuation-line-p) ; shift relative to base line
1696 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697 (t ; new base line
1698 (if (> ci (car indents)) ; going deeper; push it
1699 (setq indents (cons ci indents))
1700 ;; else we should have seen this indent before
1701 (setq indents (memq ci indents)) ; pop deeper indents
1702 (if (null indents)
1703 (error "Bad indentation in region, at line %d"
1704 (save-restriction
1705 (widen)
1706 (1+ (count-lines 1 (point)))))))
1707 (setq target-column (+ indent-base
1708 (* py-indent-offset
1709 (- (length indents) 2))))
1710 (setq base-shifted-by (- target-column ci))))
1711 ;; shift as needed
1712 (if (/= ci target-column)
1713 (progn
1714 (delete-horizontal-space)
1715 (indent-to target-column)))
1716 (forward-line 1))))
1717 (set-marker end nil))
1718
Barry Warsawa7891711996-08-01 15:53:09 +00001719(defun py-comment-region (beg end &optional arg)
1720 "Like `comment-region' but uses double hash (`#') comment starter."
1721 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001722 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001723 (comment-region beg end arg)))
1724
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001725
1726;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727(defun py-previous-statement (count)
1728 "Go to the start of previous Python statement.
1729If the statement at point is the i'th Python statement, goes to the
1730start of statement i-COUNT. If there is no such statement, goes to the
1731first statement. Returns count of statements left to move.
1732`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001733 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001734 (if (< count 0) (py-next-statement (- count))
1735 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001736 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001737 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739 (> count 0)
1740 (zerop (forward-line -1))
1741 (py-goto-statement-at-or-above))
1742 (setq count (1- count)))
1743 (if (> count 0) (goto-char start)))
1744 count))
1745
1746(defun py-next-statement (count)
1747 "Go to the start of next Python statement.
1748If the statement at point is the i'th Python statement, goes to the
1749start of statement i+COUNT. If there is no such statement, goes to the
1750last statement. Returns count of statements left to move. `Statements'
1751do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001753 (if (< count 0) (py-previous-statement (- count))
1754 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001758 (> count 0)
1759 (py-goto-statement-below))
1760 (setq count (1- count)))
1761 (if (> count 0) (goto-char start)))
1762 count))
1763
1764(defun py-goto-block-up (&optional nomark)
1765 "Move up to start of current block.
1766Go to the statement that starts the smallest enclosing block; roughly
1767speaking, this will be the closest preceding statement that ends with a
1768colon and is indented less than the statement you started on. If
1769successful, also sets the mark to the starting point.
1770
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001771`\\[py-mark-block]' can be used afterward to mark the whole code
1772block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001773
1774If called from a program, the mark will not be set if optional argument
1775NOMARK is not nil."
1776 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777 (let ((start (point))
1778 (found nil)
1779 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001780 (py-goto-initial-line)
1781 ;; if on blank or non-indenting comment line, use the preceding stmt
1782 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1783 (progn
1784 (py-goto-statement-at-or-above)
1785 (setq found (py-statement-opens-block-p))))
1786 ;; search back for colon line indented less
1787 (setq initial-indent (current-indentation))
1788 (if (zerop initial-indent)
1789 ;; force fast exit
1790 (goto-char (point-min)))
1791 (while (not (or found (bobp)))
1792 (setq found
1793 (and
1794 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1795 (or (py-goto-initial-line) t) ; always true -- side effect
1796 (< (current-indentation) initial-indent)
1797 (py-statement-opens-block-p))))
1798 (if found
1799 (progn
1800 (or nomark (push-mark start))
1801 (back-to-indentation))
1802 (goto-char start)
1803 (error "Enclosing block not found"))))
1804
1805(defun beginning-of-python-def-or-class (&optional class)
1806 "Move point to start of def (or class, with prefix arg).
1807
1808Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001809arg, looks for a `class' instead. The docs assume the `def' case;
1810just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001812If point is in a def statement already, and after the `d', simply
1813moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001814
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815Else (point is not in a def statement, or at or before the `d' of a
1816def statement), searches for the closest preceding def statement, and
1817leaves point at its start. If no such statement can be found, leaves
1818point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001819
1820Returns t iff a def statement is found by these rules.
1821
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001822Note that doing this command repeatedly will take you closer to the
1823start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001824
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001826`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001828 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1829 (start-of-line (progn (beginning-of-line) (point)))
1830 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001831 (if (or (/= start-of-stmt start-of-line)
1832 (not at-or-before-p))
1833 (end-of-line)) ; OK to match on this line
1834 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001835 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001836
1837(defun end-of-python-def-or-class (&optional class)
1838 "Move point beyond end of def (or class, with prefix arg) body.
1839
1840By default, looks for an appropriate `def'. If you supply a prefix arg,
1841looks for a `class' instead. The docs assume the `def' case; just
1842substitute `class' for `def' for the other case.
1843
1844If point is in a def statement already, this is the def we use.
1845
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846Else if the def found by `\\[beginning-of-python-def-or-class]'
1847contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848
1849Else we search forward for the closest following def, and use that.
1850
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001851If a def can be found by these rules, point is moved to the start of
1852the line immediately following the def block, and the position of the
1853start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854
1855Else point is moved to the end of the buffer, and nil is returned.
1856
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857Note that doing this command repeatedly will take you closer to the
1858end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001859
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001860If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001861`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863 (let ((start (progn (py-goto-initial-line) (point)))
1864 (which (if class "class" "def"))
1865 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866 ;; move point to start of appropriate def/class
1867 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1868 (setq state 'at-beginning)
1869 ;; else see if beginning-of-python-def-or-class hits container
1870 (if (and (beginning-of-python-def-or-class class)
1871 (progn (py-goto-beyond-block)
1872 (> (point) start)))
1873 (setq state 'at-end)
1874 ;; else search forward
1875 (goto-char start)
1876 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1877 (progn (setq state 'at-beginning)
1878 (beginning-of-line)))))
1879 (cond
1880 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1881 ((eq state 'at-end) t)
1882 ((eq state 'not-found) nil)
1883 (t (error "internal error in end-of-python-def-or-class")))))
1884
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885
1886;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001887(defun py-mark-block (&optional extend just-move)
1888 "Mark following block of lines. With prefix arg, mark structure.
1889Easier to use than explain. It sets the region to an `interesting'
1890block of succeeding lines. If point is on a blank line, it goes down to
1891the next non-blank line. That will be the start of the region. The end
1892of the region depends on the kind of line at the start:
1893
1894 - If a comment, the region will include all succeeding comment lines up
1895 to (but not including) the next non-comment line (if any).
1896
1897 - Else if a prefix arg is given, and the line begins one of these
1898 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001899
1900 if elif else try except finally for while def class
1901
Barry Warsaw7ae77681994-12-12 20:38:05 +00001902 the region will be set to the body of the structure, including
1903 following blocks that `belong' to it, but excluding trailing blank
1904 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001905 and all (if any) of the following `except' and `finally' blocks
1906 that belong to the `try' structure will be in the region. Ditto
1907 for if/elif/else, for/else and while/else structures, and (a bit
1908 degenerate, since they're always one-block structures) def and
1909 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001910
1911 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001912 block (see list above), and the block is not a `one-liner' (i.e.,
1913 the statement ends with a colon, not with code), the region will
1914 include all succeeding lines up to (but not including) the next
1915 code statement (if any) that's indented no more than the starting
1916 line, except that trailing blank and comment lines are excluded.
1917 E.g., if the starting line begins a multi-statement `def'
1918 structure, the region will be set to the full function definition,
1919 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001920
1921 - Else the region will include all succeeding lines up to (but not
1922 including) the next blank line, or code or indenting-comment line
1923 indented strictly less than the starting line. Trailing indenting
1924 comment lines are included in this case, but not trailing blank
1925 lines.
1926
1927A msg identifying the location of the mark is displayed in the echo
1928area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1929
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930If called from a program, optional argument EXTEND plays the role of
1931the prefix arg, and if optional argument JUST-MOVE is not nil, just
1932moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001933 (interactive "P") ; raw prefix arg
1934 (py-goto-initial-line)
1935 ;; skip over blank lines
1936 (while (and
1937 (looking-at "[ \t]*$") ; while blank line
1938 (not (eobp))) ; & somewhere to go
1939 (forward-line 1))
1940 (if (eobp)
1941 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001942 (let ((initial-pos (point))
1943 (initial-indent (current-indentation))
1944 last-pos ; position of last stmt in region
1945 (followers
1946 '((if elif else) (elif elif else) (else)
1947 (try except finally) (except except) (finally)
1948 (for else) (while else)
1949 (def) (class) ) )
1950 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951
1952 (cond
1953 ;; if comment line, suck up the following comment lines
1954 ((looking-at "[ \t]*#")
1955 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1956 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1957 (setq last-pos (point)))
1958
1959 ;; else if line is a block line and EXTEND given, suck up
1960 ;; the whole structure
1961 ((and extend
1962 (setq first-symbol (py-suck-up-first-keyword) )
1963 (assq first-symbol followers))
1964 (while (and
1965 (or (py-goto-beyond-block) t) ; side effect
1966 (forward-line -1) ; side effect
1967 (setq last-pos (point)) ; side effect
1968 (py-goto-statement-below)
1969 (= (current-indentation) initial-indent)
1970 (setq next-symbol (py-suck-up-first-keyword))
1971 (memq next-symbol (cdr (assq first-symbol followers))))
1972 (setq first-symbol next-symbol)))
1973
1974 ;; else if line *opens* a block, search for next stmt indented <=
1975 ((py-statement-opens-block-p)
1976 (while (and
1977 (setq last-pos (point)) ; always true -- side effect
1978 (py-goto-statement-below)
1979 (> (current-indentation) initial-indent))
1980 nil))
1981
1982 ;; else plain code line; stop at next blank line, or stmt or
1983 ;; indenting comment line indented <
1984 (t
1985 (while (and
1986 (setq last-pos (point)) ; always true -- side effect
1987 (or (py-goto-beyond-final-line) t)
1988 (not (looking-at "[ \t]*$")) ; stop at blank line
1989 (or
1990 (>= (current-indentation) initial-indent)
1991 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1992 nil)))
1993
1994 ;; skip to end of last stmt
1995 (goto-char last-pos)
1996 (py-goto-beyond-final-line)
1997
1998 ;; set mark & display
1999 (if just-move
2000 () ; just return
2001 (push-mark (point) 'no-msg)
2002 (forward-line -1)
2003 (message "Mark set after: %s" (py-suck-up-leading-text))
2004 (goto-char initial-pos))))
2005
Barry Warsaw2518c671997-11-05 00:51:08 +00002006(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002007 "Set region to body of def (or class, with prefix arg) enclosing point.
2008Pushes the current mark, then point, on the mark ring (all language
2009modes do this, but although it's handy it's never documented ...).
2010
2011In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002012hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2013`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002014
2015And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002016Turned out that was more confusing than useful: the `goto start' and
2017`goto end' commands are usually used to search through a file, and
2018people expect them to act a lot like `search backward' and `search
2019forward' string-search commands. But because Python `def' and `class'
2020can nest to arbitrary levels, finding the smallest def containing
2021point cannot be done via a simple backward search: the def containing
2022point may not be the closest preceding def, or even the closest
2023preceding def that's indented less. The fancy algorithm required is
2024appropriate for the usual uses of this `mark' command, but not for the
2025`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002026
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002027So the def marked by this command may not be the one either of the
2028`goto' commands find: If point is on a blank or non-indenting comment
2029line, moves back to start of the closest preceding code statement or
2030indenting comment line. If this is a `def' statement, that's the def
2031we use. Else searches for the smallest enclosing `def' block and uses
2032that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002033
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002034When an enclosing def is found: The mark is left immediately beyond
2035the last line of the def block. Point is left at the start of the
2036def, except that: if the def is preceded by a number of comment lines
2037followed by (at most) one optional blank line, point is left at the
2038start of the comments; else if the def is preceded by a blank line,
2039point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002040
2041The intent is to mark the containing def/class and its associated
2042documentation, to make moving and duplicating functions and classes
2043pleasant."
2044 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045 (let ((start (point))
2046 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002047 (push-mark start)
2048 (if (not (py-go-up-tree-to-keyword which))
2049 (progn (goto-char start)
2050 (error "Enclosing %s not found" which))
2051 ;; else enclosing def/class found
2052 (setq start (point))
2053 (py-goto-beyond-block)
2054 (push-mark (point))
2055 (goto-char start)
2056 (if (zerop (forward-line -1)) ; if there is a preceding line
2057 (progn
2058 (if (looking-at "[ \t]*$") ; it's blank
2059 (setq start (point)) ; so reset start point
2060 (goto-char start)) ; else try again
2061 (if (zerop (forward-line -1))
2062 (if (looking-at "[ \t]*#") ; a comment
2063 ;; look back for non-comment line
2064 ;; tricky: note that the regexp matches a blank
2065 ;; line, cuz \n is in the 2nd character class
2066 (and
2067 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2068 (forward-line 1))
2069 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002070 (goto-char start)))))))
2071 (exchange-point-and-mark)
2072 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002073
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002074;; ripped from cc-mode
2075(defun py-forward-into-nomenclature (&optional arg)
2076 "Move forward to end of a nomenclature section or word.
2077With arg, to it arg times.
2078
2079A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2080 (interactive "p")
2081 (let ((case-fold-search nil))
2082 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002083 (re-search-forward
2084 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2085 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002086 (while (and (< arg 0)
2087 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002088 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002089 (point-min) 0))
2090 (forward-char 1)
2091 (setq arg (1+ arg)))))
2092 (py-keep-region-active))
2093
2094(defun py-backward-into-nomenclature (&optional arg)
2095 "Move backward to beginning of a nomenclature section or word.
2096With optional ARG, move that many times. If ARG is negative, move
2097forward.
2098
2099A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2100 (interactive "p")
2101 (py-forward-into-nomenclature (- arg))
2102 (py-keep-region-active))
2103
2104
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002105
2106;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
2108;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002109;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2110;; out of the right places, along with the keys they're on & current
2111;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002112(defun py-dump-help-string (str)
2113 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002114 (let ((locals (buffer-local-variables))
2115 funckind funcname func funcdoc
2116 (start 0) mstart end
2117 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002118 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2119 (setq mstart (match-beginning 0) end (match-end 0)
2120 funckind (substring str (match-beginning 1) (match-end 1))
2121 funcname (substring str (match-beginning 2) (match-end 2))
2122 func (intern funcname))
2123 (princ (substitute-command-keys (substring str start mstart)))
2124 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002125 ((equal funckind "c") ; command
2126 (setq funcdoc (documentation func)
2127 keys (concat
2128 "Key(s): "
2129 (mapconcat 'key-description
2130 (where-is-internal func py-mode-map)
2131 ", "))))
2132 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002133 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002134 keys (if (assq func locals)
2135 (concat
2136 "Local/Global values: "
2137 (prin1-to-string (symbol-value func))
2138 " / "
2139 (prin1-to-string (default-value func)))
2140 (concat
2141 "Value: "
2142 (prin1-to-string (symbol-value func))))))
2143 (t ; unexpected
2144 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002145 (princ (format "\n-> %s:\t%s\t%s\n\n"
2146 (if (equal funckind "c") "Command" "Variable")
2147 funcname keys))
2148 (princ funcdoc)
2149 (terpri)
2150 (setq start end))
2151 (princ (substitute-command-keys (substring str start))))
2152 (print-help-return-message)))
2153
2154(defun py-describe-mode ()
2155 "Dump long form of Python-mode docs."
2156 (interactive)
2157 (py-dump-help-string "Major mode for editing Python files.
2158Knows about Python indentation, tokens, comments and continuation lines.
2159Paragraphs are separated by blank lines only.
2160
2161Major sections below begin with the string `@'; specific function and
2162variable docs begin with `->'.
2163
2164@EXECUTING PYTHON CODE
2165
2166\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2167\\[py-execute-region]\tsends the current region
2168\\[py-shell]\tstarts a Python interpreter window; this will be used by
2169\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2170%c:py-execute-buffer
2171%c:py-execute-region
2172%c:py-shell
2173
2174@VARIABLES
2175
2176py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002177py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002178
2179py-python-command\tshell command to invoke Python interpreter
2180py-scroll-process-buffer\talways scroll Python process buffer
2181py-temp-directory\tdirectory used for temp files (if needed)
2182
2183py-beep-if-tab-change\tring the bell if tab-width is changed
2184%v:py-indent-offset
2185%v:py-block-comment-prefix
2186%v:py-python-command
2187%v:py-scroll-process-buffer
2188%v:py-temp-directory
2189%v:py-beep-if-tab-change
2190
2191@KINDS OF LINES
2192
2193Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002194preceding line ends with a backslash that's not part of a comment, or
2195the paren/bracket/brace nesting level at the start of the line is
2196non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002197
2198An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002199possibly blanks or tabs), a `comment line' (leftmost non-blank
2200character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002201
2202Comment Lines
2203
2204Although all comment lines are treated alike by Python, Python mode
2205recognizes two kinds that act differently with respect to indentation.
2206
2207An `indenting comment line' is a comment line with a blank, tab or
2208nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002209treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002210indenting comment line will be indented like the comment line. All
2211other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212following the initial `#') are `non-indenting comment lines', and
2213their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002214
2215Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002216whenever possible. Non-indenting comment lines are useful in cases
2217like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002218
2219\ta = b # a very wordy single-line comment that ends up being
2220\t #... continued onto another line
2221
2222\tif a == b:
2223##\t\tprint 'panic!' # old code we've `commented out'
2224\t\treturn a
2225
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002226Since the `#...' and `##' comment lines have a non-whitespace
2227character following the initial `#', Python mode ignores them when
2228computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002229
2230Continuation Lines and Statements
2231
2232The Python-mode commands generally work on statements instead of on
2233individual lines, where a `statement' is a comment or blank line, or a
2234code line and all of its following continuation lines (if any)
2235considered as a single logical unit. The commands in this mode
2236generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002237statement containing point, even if point happens to be in the middle
2238of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002239
2240
2241@INDENTATION
2242
2243Primarily for entering new code:
2244\t\\[indent-for-tab-command]\t indent line appropriately
2245\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002246\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002247
2248Primarily for reindenting existing code:
2249\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2250\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2251
2252\t\\[py-indent-region]\t reindent region to match its context
2253\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2254\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2255
2256Unlike most programming languages, Python uses indentation, and only
2257indentation, to specify block structure. Hence the indentation supplied
2258automatically by Python-mode is just an educated guess: only you know
2259the block structure you intend, so only you can supply correct
2260indentation.
2261
2262The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2263the indentation of preceding statements. E.g., assuming
2264py-indent-offset is 4, after you enter
2265\tif a > 0: \\[py-newline-and-indent]
2266the cursor will be moved to the position of the `_' (_ is not a
2267character in the file, it's just used here to indicate the location of
2268the cursor):
2269\tif a > 0:
2270\t _
2271If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2272to
2273\tif a > 0:
2274\t c = d
2275\t _
2276Python-mode cannot know whether that's what you intended, or whether
2277\tif a > 0:
2278\t c = d
2279\t_
2280was your intent. In general, Python-mode either reproduces the
2281indentation of the (closest code or indenting-comment) preceding
2282statement, or adds an extra py-indent-offset blanks if the preceding
2283statement has `:' as its last significant (non-whitespace and non-
2284comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002285\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002286
2287Continuation lines are given extra indentation. If you don't like the
2288suggested indentation, change it to something you do like, and Python-
2289mode will strive to indent later lines of the statement in the same way.
2290
2291If a line is a continuation line by virtue of being in an unclosed
2292paren/bracket/brace structure (`list', for short), the suggested
2293indentation depends on whether the current line contains the first item
2294in the list. If it does, it's indented py-indent-offset columns beyond
2295the indentation of the line containing the open bracket. If you don't
2296like that, change it by hand. The remaining items in the list will mimic
2297whatever indentation you give to the first item.
2298
2299If a line is a continuation line because the line preceding it ends with
2300a backslash, the third and following lines of the statement inherit their
2301indentation from the line preceding them. The indentation of the second
2302line in the statement depends on the form of the first (base) line: if
2303the base line is an assignment statement with anything more interesting
2304than the backslash following the leftmost assigning `=', the second line
2305is indented two columns beyond that `='. Else it's indented to two
2306columns beyond the leftmost solid chunk of non-whitespace characters on
2307the base line.
2308
2309Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2310repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2311structure you intend.
2312%c:indent-for-tab-command
2313%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002314%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002315
2316
2317The next function may be handy when editing code you didn't write:
2318%c:py-guess-indent-offset
2319
2320
2321The remaining `indent' functions apply to a region of Python code. They
2322assume the block structure (equals indentation, in Python) of the region
2323is correct, and alter the indentation in various ways while preserving
2324the block structure:
2325%c:py-indent-region
2326%c:py-shift-region-left
2327%c:py-shift-region-right
2328
2329@MARKING & MANIPULATING REGIONS OF CODE
2330
2331\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002332\\[py-mark-def-or-class]\t mark smallest enclosing def
2333\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002334\\[comment-region]\t comment out region of code
2335\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002336%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002337%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002338%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002339
2340@MOVING POINT
2341
2342\\[py-previous-statement]\t move to statement preceding point
2343\\[py-next-statement]\t move to statement following point
2344\\[py-goto-block-up]\t move up to start of current block
2345\\[beginning-of-python-def-or-class]\t move to start of def
2346\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2347\\[end-of-python-def-or-class]\t move to end of def
2348\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2349
2350The first two move to one statement beyond the statement that contains
2351point. A numeric prefix argument tells them to move that many
2352statements instead. Blank lines, comment lines, and continuation lines
2353do not count as `statements' for these commands. So, e.g., you can go
2354to the first code statement in a file by entering
2355\t\\[beginning-of-buffer]\t to move to the top of the file
2356\t\\[py-next-statement]\t to skip over initial comments and blank lines
2357Or do `\\[py-previous-statement]' with a huge prefix argument.
2358%c:py-previous-statement
2359%c:py-next-statement
2360%c:py-goto-block-up
2361%c:beginning-of-python-def-or-class
2362%c:end-of-python-def-or-class
2363
2364@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2365
2366`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2367
2368`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2369overall class and def structure of a module.
2370
2371`\\[back-to-indentation]' moves point to a line's first non-blank character.
2372
2373`\\[indent-relative]' is handy for creating odd indentation.
2374
2375@OTHER EMACS HINTS
2376
2377If you don't like the default value of a variable, change its value to
2378whatever you do like by putting a `setq' line in your .emacs file.
2379E.g., to set the indentation increment to 4, put this line in your
2380.emacs:
2381\t(setq py-indent-offset 4)
2382To see the value of a variable, do `\\[describe-variable]' and enter the variable
2383name at the prompt.
2384
2385When entering a key sequence like `C-c C-n', it is not necessary to
2386release the CONTROL key after doing the `C-c' part -- it suffices to
2387press the CONTROL key, press and release `c' (while still holding down
2388CONTROL), press and release `n' (while still holding down CONTROL), &
2389then release CONTROL.
2390
2391Entering Python mode calls with no arguments the value of the variable
2392`python-mode-hook', if that value exists and is not nil; for backward
2393compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2394the Elisp manual for details.
2395
2396Obscure: When python-mode is first loaded, it looks for all bindings
2397to newline-and-indent in the global keymap, and shadows them with
2398local bindings to py-newline-and-indent."))
2399
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002400
2401;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002402(defvar py-parse-state-re
2403 (concat
2404 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2405 "\\|"
2406 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002407
Barry Warsaw7ae77681994-12-12 20:38:05 +00002408;; returns the parse state at point (see parse-partial-sexp docs)
2409(defun py-parse-state ()
2410 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002411 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002412 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002413 (while (not done)
2414 ;; back up to the first preceding line (if any; else start of
2415 ;; buffer) that begins with a popular Python keyword, or a
2416 ;; non- whitespace and non-comment character. These are good
2417 ;; places to start parsing to see whether where we started is
2418 ;; at a non-zero nesting level. It may be slow for people who
2419 ;; write huge code blocks or huge lists ... tough beans.
2420 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002421 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002422 (beginning-of-line)
2423 (save-excursion
2424 (setq pps (parse-partial-sexp (point) here)))
2425 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002426 (setq done (or (zerop ci)
2427 (not (nth 3 pps))
2428 (bobp)))
2429 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002430 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002431
2432;; if point is at a non-zero nesting level, returns the number of the
2433;; character that opens the smallest enclosing unclosed list; else
2434;; returns nil.
2435(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002436 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002437 (if (zerop (car status))
2438 nil ; not in a nest
2439 (car (cdr status))))) ; char# of open bracket
2440
2441;; t iff preceding line ends with backslash that's not in a comment
2442(defun py-backslash-continuation-line-p ()
2443 (save-excursion
2444 (beginning-of-line)
2445 (and
2446 ;; use a cheap test first to avoid the regexp if possible
2447 ;; use 'eq' because char-after may return nil
2448 (eq (char-after (- (point) 2)) ?\\ )
2449 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002450 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002451 (looking-at py-continued-re))))
2452
2453;; t iff current line is a continuation line
2454(defun py-continuation-line-p ()
2455 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002456 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002457 (or (py-backslash-continuation-line-p)
2458 (py-nesting-level))))
2459
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002460;; go to initial line of current statement; usually this is the line
2461;; we're on, but if we're on the 2nd or following lines of a
2462;; continuation block, we need to go up to the first line of the
2463;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002464;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002465;; Tricky: We want to avoid quadratic-time behavior for long continued
2466;; blocks, whether of the backslash or open-bracket varieties, or a
2467;; mix of the two. The following manages to do that in the usual
2468;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002469(defun py-goto-initial-line ()
2470 (let ( open-bracket-pos )
2471 (while (py-continuation-line-p)
2472 (beginning-of-line)
2473 (if (py-backslash-continuation-line-p)
2474 (while (py-backslash-continuation-line-p)
2475 (forward-line -1))
2476 ;; else zip out of nested brackets/braces/parens
2477 (while (setq open-bracket-pos (py-nesting-level))
2478 (goto-char open-bracket-pos)))))
2479 (beginning-of-line))
2480
2481;; go to point right beyond final line of current statement; usually
2482;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002483;; statement we need to skip over the continuation lines. Tricky:
2484;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002485(defun py-goto-beyond-final-line ()
2486 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002487 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002488 (while (and (py-continuation-line-p)
2489 (not (eobp)))
2490 ;; skip over the backslash flavor
2491 (while (and (py-backslash-continuation-line-p)
2492 (not (eobp)))
2493 (forward-line 1))
2494 ;; if in nest, zip to the end of the nest
2495 (setq state (py-parse-state))
2496 (if (and (not (zerop (car state)))
2497 (not (eobp)))
2498 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002499 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002500 (forward-line 1))))))
2501
2502;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002503;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002504(defun py-statement-opens-block-p ()
2505 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002506 (let ((start (point))
2507 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2508 (searching t)
2509 (answer nil)
2510 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002511 (goto-char start)
2512 (while searching
2513 ;; look for a colon with nothing after it except whitespace, and
2514 ;; maybe a comment
2515 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2516 finish t)
2517 (if (eq (point) finish) ; note: no `else' clause; just
2518 ; keep searching if we're not at
2519 ; the end yet
2520 ;; sure looks like it opens a block -- but it might
2521 ;; be in a comment
2522 (progn
2523 (setq searching nil) ; search is done either way
2524 (setq state (parse-partial-sexp start
2525 (match-beginning 0)))
2526 (setq answer (not (nth 4 state)))))
2527 ;; search failed: couldn't find another interesting colon
2528 (setq searching nil)))
2529 answer)))
2530
Barry Warsawf831d811996-07-31 20:42:59 +00002531(defun py-statement-closes-block-p ()
2532 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002533 ;; starts with `return', `raise', `break', `continue', and `pass'.
2534 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002535 (let ((here (point)))
2536 (back-to-indentation)
2537 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002538 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002539 (goto-char here))))
2540
Barry Warsaw7ae77681994-12-12 20:38:05 +00002541;; go to point right beyond final line of block begun by the current
2542;; line. This is the same as where py-goto-beyond-final-line goes
2543;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002544;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002545(defun py-goto-beyond-block ()
2546 (if (py-statement-opens-block-p)
2547 (py-mark-block nil 'just-move)
2548 (py-goto-beyond-final-line)))
2549
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002550;; go to start of first statement (not blank or comment or
2551;; continuation line) at or preceding point. returns t if there is
2552;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002553(defun py-goto-statement-at-or-above ()
2554 (py-goto-initial-line)
2555 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002556 ;; skip back over blank & comment lines
2557 ;; note: will skip a blank or comment line that happens to be
2558 ;; a continuation line too
2559 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2560 (progn (py-goto-initial-line) t)
2561 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002562 t))
2563
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002564;; go to start of first statement (not blank or comment or
2565;; continuation line) following the statement containing point returns
2566;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002567(defun py-goto-statement-below ()
2568 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002569 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002570 (py-goto-beyond-final-line)
2571 (while (and
2572 (looking-at py-blank-or-comment-re)
2573 (not (eobp)))
2574 (forward-line 1))
2575 (if (eobp)
2576 (progn (goto-char start) nil)
2577 t)))
2578
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002579;; go to start of statement, at or preceding point, starting with
2580;; keyword KEY. Skips blank lines and non-indenting comments upward
2581;; first. If that statement starts with KEY, done, else go back to
2582;; first enclosing block starting with KEY. If successful, leaves
2583;; point at the start of the KEY line & returns t. Else leaves point
2584;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002585(defun py-go-up-tree-to-keyword (key)
2586 ;; skip blanks and non-indenting #
2587 (py-goto-initial-line)
2588 (while (and
2589 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2590 (zerop (forward-line -1))) ; go back
2591 nil)
2592 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002593 (let* ((re (concat "[ \t]*" key "\\b"))
2594 (case-fold-search nil) ; let* so looking-at sees this
2595 (found (looking-at re))
2596 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002597 (while (not (or found dead))
2598 (condition-case nil ; in case no enclosing block
2599 (py-goto-block-up 'no-mark)
2600 (error (setq dead t)))
2601 (or dead (setq found (looking-at re))))
2602 (beginning-of-line)
2603 found))
2604
2605;; return string in buffer from start of indentation to end of line;
2606;; prefix "..." if leading whitespace was skipped
2607(defun py-suck-up-leading-text ()
2608 (save-excursion
2609 (back-to-indentation)
2610 (concat
2611 (if (bolp) "" "...")
2612 (buffer-substring (point) (progn (end-of-line) (point))))))
2613
2614;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2615;; as a Lisp symbol; return nil if none
2616(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002617 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002618 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2619 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2620 nil)))
2621
Barry Warsawb3e81d51996-09-04 15:12:42 +00002622(defun py-current-defun ()
2623 ;; tell add-log.el how to find the current function/method/variable
2624 (save-excursion
2625 (if (re-search-backward py-defun-start-re nil t)
2626 (or (match-string 3)
2627 (let ((method (match-string 2)))
2628 (if (and (not (zerop (length (match-string 1))))
2629 (re-search-backward py-class-start-re nil t))
2630 (concat (match-string 1) "." method)
2631 method)))
2632 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002633
2634
Barry Warsawfec75d61995-07-05 23:26:15 +00002635(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002636 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002637
Barry Warsaw850437a1995-03-08 21:50:28 +00002638(defun py-version ()
2639 "Echo the current version of `python-mode' in the minibuffer."
2640 (interactive)
2641 (message "Using `python-mode' version %s" py-version)
2642 (py-keep-region-active))
2643
2644;; only works under Emacs 19
2645;(eval-when-compile
2646; (require 'reporter))
2647
2648(defun py-submit-bug-report (enhancement-p)
2649 "Submit via mail a bug report on `python-mode'.
2650With \\[universal-argument] just submit an enhancement request."
2651 (interactive
2652 (list (not (y-or-n-p
2653 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002654 (let ((reporter-prompt-for-summary-p (if enhancement-p
2655 "(Very) brief summary: "
2656 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002657 (require 'reporter)
2658 (reporter-submit-bug-report
2659 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002660 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002661 ;; varlist
2662 (if enhancement-p nil
2663 '(py-python-command
2664 py-indent-offset
2665 py-block-comment-prefix
2666 py-scroll-process-buffer
2667 py-temp-directory
2668 py-beep-if-tab-change))
2669 nil ;pre-hooks
2670 nil ;post-hooks
2671 "Dear Barry,") ;salutation
2672 (if enhancement-p nil
2673 (set-mark (point))
2674 (insert
2675"Please replace this text with a sufficiently large code sample\n\
2676and an exact recipe so that I can reproduce your problem. Failure\n\
2677to do so may mean a greater delay in fixing your bug.\n\n")
2678 (exchange-point-and-mark)
2679 (py-keep-region-active))))
2680
2681
Barry Warsaw47384781997-11-26 05:27:45 +00002682(defun py-kill-emacs-hook ()
2683 (mapcar #'(lambda (filename)
2684 (py-safe (delete-file filename)))
2685 py-file-queue))
2686
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002687;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002688(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002689
2690
2691
2692(provide 'python-mode)
2693;;; python-mode.el ends here