blob: 216b5c9d6765d2484030416e6e26b799dd7d706f [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 Warsaw5ea20d51997-12-06 00:00:47 +000068;; If you are using XEmacs, you may also want to check out OO-Browser
69;; that comes bundled with it, including documentation in the info
70;; pages. For GNU Emacs you have to install it yourself. To read
71;; more about OO-Browser, follow these links:
72
73;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
74;; http://www.infodock.com/manuals/alt-oobr-cover.html
75
Barry Warsaw7b0f5681995-03-08 21:33:04 +000076;; Here's a brief to do list:
77;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000078;; - Better integration with gud-mode for debugging.
79;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000080;; - possibly force indent-tabs-mode == nil, and add a
81;; write-file-hooks that runs untabify on the whole buffer (to work
82;; around potential tab/space mismatch problems). In practice this
83;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000084;; - have py-execute-region on indented code act as if the region is
85;; left justified. Avoids syntax errors.
Barry Warsaw7ae77681994-12-12 20:38:05 +000086
Barry Warsaw7b0f5681995-03-08 21:33:04 +000087;;; Code:
88
Barry Warsawc72c11c1997-08-09 06:42:08 +000089(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +000090(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +000091 (require 'cl)
92 (require 'custom)
93 ;; Stock Emacs 19.34 has a broken/old Custom library that does more
94 ;; harm than good
95 (or (fboundp 'defcustom)
96 (error "STOP! STOP! STOP! STOP!
97
98The Custom library was not found or is out of date. A more current
99version is required. Please download and install the latest version
100of the Custom library from:
101
102 <http://www.dina.kvl.dk/~abraham/custom/>
103
104See the Python Mode home page for details:
105
106 <http://www.python.org/ftp/emacs/>
107")))
108
Barry Warsawc72c11c1997-08-09 06:42:08 +0000109
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000110
111;; user definable variables
112;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000113
Barry Warsawc72c11c1997-08-09 06:42:08 +0000114(defgroup python nil
115 "Support for the Python programming language, <http://www.python.org/>"
116 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000117
Barry Warsawc72c11c1997-08-09 06:42:08 +0000118(defcustom py-python-command "python"
119 "*Shell command used to start Python interpreter."
120 :type 'string
121 :group 'python)
122
123(defcustom py-indent-offset 4
124 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000125Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000126when you're editing someone else's Python code."
127 :type 'integer
128 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000129
Barry Warsawc72c11c1997-08-09 06:42:08 +0000130(defcustom py-align-multiline-strings-p t
131 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000132When this flag is non-nil, continuation lines are lined up under the
133preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000134lines are aligned to column zero."
135 :type '(choice (const :tag "Align under preceding line" t)
136 (const :tag "Align to column zero" nil))
137 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000138
Barry Warsawc72c11c1997-08-09 06:42:08 +0000139(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000140 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000141This should follow the convention for non-indenting comment lines so
142that the indentation commands won't get confused (i.e., the string
143should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000144`...' is arbitrary)."
145 :type 'string
146 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000147
Barry Warsawc72c11c1997-08-09 06:42:08 +0000148(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000149 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000150
Barry Warsaw6d627751996-03-06 18:41:38 +0000151When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000152if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000153
154When t, lines that begin with a single `#' are a hint to subsequent
155line indentation. If the previous line is such a comment line (as
156opposed to one that starts with `py-block-comment-prefix'), then it's
157indentation is used as a hint for this line's indentation. Lines that
158begin with `py-block-comment-prefix' are ignored for indentation
159purposes.
160
161When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000162indentation hints, unless the comment character is in column zero."
163 :type '(choice
164 (const :tag "Skip all comment lines (fast)" nil)
165 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000166 (const :tag "Single # `sets' indentation except at column zero"
167 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000168 )
169 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000170
Barry Warsawc72c11c1997-08-09 06:42:08 +0000171(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000172 "*Scroll Python process buffer as output arrives.
173If nil, the Python process buffer acts, with respect to scrolling, like
174Shell-mode buffers normally act. This is surprisingly complicated and
175so won't be explained here; in fact, you can't get the whole story
176without studying the Emacs C code.
177
178If non-nil, the behavior is different in two respects (which are
179slightly inaccurate in the interest of brevity):
180
181 - If the buffer is in a window, and you left point at its end, the
182 window will scroll as new output arrives, and point will move to the
183 buffer's end, even if the window is not the selected window (that
184 being the one the cursor is in). The usual behavior for shell-mode
185 windows is not to scroll, and to leave point where it was, if the
186 buffer is in a window other than the selected window.
187
188 - If the buffer is not visible in any window, and you left point at
189 its end, the buffer will be popped into a window as soon as more
190 output arrives. This is handy if you have a long-running
191 computation and don't want to tie up screen area waiting for the
192 output. The usual behavior for a shell-mode buffer is to stay
193 invisible until you explicitly visit it.
194
195Note the `and if you left point at its end' clauses in both of the
196above: you can `turn off' the special behaviors while output is in
197progress, by visiting the Python buffer and moving point to anywhere
198besides the end. Then the buffer won't scroll, point will remain where
199you leave it, and if you hide the buffer it will stay hidden until you
200visit it again. You can enable and disable the special behaviors as
201often as you like, while output is in progress, by (respectively) moving
202point to, or away from, the end of the buffer.
203
204Warning: If you expect a large amount of output, you'll probably be
205happier setting this option to nil.
206
207Obscure: `End of buffer' above should really say `at or beyond the
208process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000209told <grin>."
210 :type 'boolean
211 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000212
Barry Warsaw516b6201997-08-09 06:43:20 +0000213(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000214 (let ((ok '(lambda (x)
215 (and x
216 (setq x (expand-file-name x)) ; always true
217 (file-directory-p x)
218 (file-writable-p x)
219 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000220 (or (funcall ok (getenv "TMPDIR"))
221 (funcall ok "/usr/tmp")
222 (funcall ok "/tmp")
223 (funcall ok ".")
224 (error
225 "Couldn't find a usable temp directory -- set py-temp-directory")))
226 "*Directory used for temp files created by a *Python* process.
227By default, the first directory from this list that exists and that you
228can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000229/usr/tmp, /tmp, or the current directory."
230 :type 'string
231 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000232
Barry Warsaw516b6201997-08-09 06:43:20 +0000233(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000234 "*Ring the bell if tab-width is changed.
235If a comment of the form
236
237 \t# vi:set tabsize=<number>:
238
239is found before the first code line when the file is entered, and the
240current value of (the general Emacs variable) `tab-width' does not
241equal <number>, `tab-width' is set to <number>, a message saying so is
242displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000243the Emacs bell is also rung as a warning."
244 :type 'boolean
245 :group 'python)
246
Barry Warsaw9981d221997-12-03 05:25:48 +0000247(defcustom py-jump-on-exception t
248 "*Jump to innermost exception frame in *Python Output* buffer.
249When this variable is non-nil and ane exception occurs when running
250Python code synchronously in a subprocess, jump immediately to the
251source code of the innermost frame.")
252
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000253(defcustom py-backspace-function 'backward-delete-char-untabify
254 "*Function called by `py-electric-backspace' when deleting backwards."
255 :type 'function
256 :group 'python)
257
258(defcustom py-delete-function 'delete-char
259 "*Function called by `py-electric-delete' when deleting forwards."
260 :type 'function
261 :group 'python)
262
263
Barry Warsawc72c11c1997-08-09 06:42:08 +0000264
265;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
266;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
267
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000268(defconst py-emacs-features
269 (let (features)
270 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
271 ;; the same string.
272 (let ((tmp1 (make-temp-name ""))
273 (tmp2 (make-temp-name "")))
274 (if (string-equal tmp1 tmp2)
275 (push 'broken-temp-names features)))
276 ;; return the features
277 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000278 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000279There are many flavors of Emacs out there, with different levels of
280support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000281
Barry Warsawfb07f401997-02-24 03:37:22 +0000282(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000283 (let ((kw1 (mapconcat 'identity
284 '("and" "assert" "break" "class"
285 "continue" "def" "del" "elif"
286 "else" "except" "exec" "for"
287 "from" "global" "if" "import"
288 "in" "is" "lambda" "not"
289 "or" "pass" "print" "raise"
290 "return" "while"
291 )
292 "\\|"))
293 (kw2 (mapconcat 'identity
294 '("else:" "except:" "finally:" "try:")
295 "\\|"))
296 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000297 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000298 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000299 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
300 ;; block introducing keywords with immediately following colons.
301 ;; Yes "except" is in both lists.
302 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000303 ;; classes
304 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
305 1 font-lock-type-face)
306 ;; functions
307 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
308 1 font-lock-function-name-face)
309 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000310 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000311(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
312
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000313
Barry Warsaw81437461996-08-01 19:48:02 +0000314(defvar imenu-example--python-show-method-args-p nil
315 "*Controls echoing of arguments of functions & methods in the imenu buffer.
316When non-nil, arguments are printed.")
317
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000318(make-variable-buffer-local 'py-indent-offset)
319
Barry Warsawe467bfb1997-11-26 05:40:58 +0000320;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000321(defvar py-file-queue nil
322 "Queue of Python temp files awaiting execution.
323Currently-active file is at the head of the list.")
324
Barry Warsawc72c11c1997-08-09 06:42:08 +0000325
326;; Constants
327
328;; Regexp matching a Python string literal
329(defconst py-stringlit-re
330 (concat
331 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
332 "\\|" ; or
333 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
334
335;; Regexp matching Python lines that are continued via backslash.
336;; This is tricky because a trailing backslash does not mean
337;; continuation if it's in a comment
338(defconst py-continued-re
339 (concat
340 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
341 "\\\\$"))
342
343;; Regexp matching blank or comment lines.
344(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
345
346;; Regexp matching clauses to be outdented one level.
347(defconst py-outdent-re
348 (concat "\\(" (mapconcat 'identity
349 '("else:"
350 "except\\(\\s +.*\\)?:"
351 "finally:"
352 "elif\\s +.*:")
353 "\\|")
354 "\\)"))
355
356
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000357;; Regexp matching keywords which typically close a block
358(defconst py-block-closing-keywords-re
359 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
360
Barry Warsawc72c11c1997-08-09 06:42:08 +0000361;; Regexp matching lines to not outdent after.
362(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000363 (concat
364 "\\("
365 (mapconcat 'identity
366 (list "try:"
367 "except\\(\\s +.*\\)?:"
368 "while\\s +.*:"
369 "for\\s +.*:"
370 "if\\s +.*:"
371 "elif\\s +.*:"
372 (concat py-block-closing-keywords-re "[ \t\n]")
373 )
374 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000375 "\\)"))
376
377;; Regexp matching a function, method or variable assignment. If you
378;; change this, you probably have to change `py-current-defun' as
379;; well. This is only used by `py-current-defun' to find the name for
380;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000381(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000382 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
383
384;; Regexp for finding a class name. If you change this, you probably
385;; have to change `py-current-defun' as well. This is only used by
386;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000387(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
388
389;; Regexp that describes tracebacks
390(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000391 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000392
393
394
395;; Utilities
396
397(defmacro py-safe (&rest body)
398 ;; safely execute BODY, return nil if an error occurred
399 (` (condition-case nil
400 (progn (,@ body))
401 (error nil))))
402
403(defsubst py-keep-region-active ()
404 ;; Do whatever is necessary to keep the region active in XEmacs.
405 ;; Ignore byte-compiler warnings you might see. Also note that
406 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
407 ;; to take explicit action.
408 (and (boundp 'zmacs-region-stays)
409 (setq zmacs-region-stays t)))
410
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000411(defsubst py-point (position)
412 ;; Returns the value of point at certain commonly referenced POSITIONs.
413 ;; POSITION can be one of the following symbols:
414 ;;
415 ;; bol -- beginning of line
416 ;; eol -- end of line
417 ;; bod -- beginning of defun
418 ;; boi -- back to indentation
419 ;;
420 ;; This function does not modify point or mark.
421 (let ((here (point)))
422 (cond
423 ((eq position 'bol) (beginning-of-line))
424 ((eq position 'eol) (end-of-line))
425 ((eq position 'bod) (beginning-of-python-def-or-class))
426 ((eq position 'bob) (beginning-of-buffer))
427 ((eq position 'eob) (end-of-buffer))
428 ((eq position 'boi) (back-to-indentation))
429 (t (error "unknown buffer position requested: %s" position))
430 )
431 (prog1
432 (point)
433 (goto-char here))))
434
435(defsubst py-highlight-line (from to file line)
436 (cond
437 ((fboundp 'make-extent)
438 ;; XEmacs
439 (let ((e (make-extent from to)))
440 (set-extent-property e 'mouse-face 'highlight)
441 (set-extent-property e 'py-exc-info (cons file line))
442 (set-extent-property e 'keymap py-mode-output-map)))
443 (t
444 ;; Emacs -- Please port this!
445 )
446 ))
447
Barry Warsawc72c11c1997-08-09 06:42:08 +0000448
449;; Major mode boilerplate
450
Barry Warsaw7ae77681994-12-12 20:38:05 +0000451;; define a mode-specific abbrev table for those who use such things
452(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000454(define-abbrev-table 'python-mode-abbrev-table nil)
455
Barry Warsaw7ae77681994-12-12 20:38:05 +0000456(defvar python-mode-hook nil
457 "*Hook called by `python-mode'.")
458
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000459;; in previous version of python-mode.el, the hook was incorrectly
460;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000461(and (fboundp 'make-obsolete-variable)
462 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
463
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000464(defvar py-mode-map ()
465 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000466(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000467 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000468 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000469 ;; electric keys
470 (define-key py-mode-map ":" 'py-electric-colon)
471 ;; indentation level modifiers
472 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
473 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
474 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
475 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
476 ;; subprocess commands
477 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
478 (define-key py-mode-map "\C-c|" 'py-execute-region)
479 (define-key py-mode-map "\C-c!" 'py-shell)
480 ;; Caution! Enter here at your own risk. We are trying to support
481 ;; several behaviors and it gets disgusting. :-( This logic ripped
482 ;; largely from CC Mode.
483 ;;
484 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
485 ;; backwards deletion behavior to DEL, which both Delete and
486 ;; Backspace get translated to. There's no way to separate this
487 ;; behavior in a clean way, so deal with it! Besides, it's been
488 ;; this way since the dawn of time.
489 (if (not (boundp 'delete-key-deletes-forward))
490 (define-key py-mode-map "\177" 'py-electric-backspace)
491 ;; However, XEmacs 20 actually achieved enlightenment. It is
492 ;; possible to sanely define both backward and forward deletion
493 ;; behavior under X separately (TTYs are forever beyond hope, but
494 ;; who cares? XEmacs 20 does the right thing with these too).
495 (define-key py-mode-map [delete] 'py-electric-delete)
496 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000497 ;; Separate M-BS from C-M-h. The former should remain
498 ;; backward-kill-word.
499 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000500 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000501 ;; Miscellaneous
502 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
503 (define-key py-mode-map "\C-c\t" 'py-indent-region)
504 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
505 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
506 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000507 (define-key py-mode-map "\C-c#" 'py-comment-region)
508 (define-key py-mode-map "\C-c?" 'py-describe-mode)
509 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
510 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
511 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000512 (define-key py-mode-map "\C-c-" 'py-up-exception)
513 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000514 ;; information
515 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
516 (define-key py-mode-map "\C-c\C-v" 'py-version)
517 ;; py-newline-and-indent mappings
518 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000519 ;; shadow global bindings for newline-and-indent w/ the py- version.
520 ;; BAW - this is extremely bad form, but I'm not going to change it
521 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000522 (mapcar #'(lambda (key)
523 (define-key py-mode-map key 'py-newline-and-indent))
524 (where-is-internal 'newline-and-indent))
525 )
526
527(defvar py-mode-output-map nil
528 "Keymap used in *Python Output* buffers*")
529(if py-mode-output-map
530 nil
531 (setq py-mode-output-map (make-sparse-keymap))
532 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
533 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
534 ;; TBD: Disable all self-inserting keys. This is bogus, we should
535 ;; really implement this as *Python Output* buffer being read-only
536 (mapcar #' (lambda (key)
537 (define-key py-mode-output-map key
538 #'(lambda () (interactive) (beep))))
539 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000540 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000541
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000542(defvar py-mode-syntax-table nil
543 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000545 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000546 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000547 (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 ;; Add operator symbols misassigned in the std table
554 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
555 (modify-syntax-entry ?\% "." py-mode-syntax-table)
556 (modify-syntax-entry ?\& "." py-mode-syntax-table)
557 (modify-syntax-entry ?\* "." py-mode-syntax-table)
558 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
559 (modify-syntax-entry ?\- "." py-mode-syntax-table)
560 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
561 (modify-syntax-entry ?\< "." py-mode-syntax-table)
562 (modify-syntax-entry ?\= "." py-mode-syntax-table)
563 (modify-syntax-entry ?\> "." py-mode-syntax-table)
564 (modify-syntax-entry ?\| "." py-mode-syntax-table)
565 ;; For historical reasons, underscore is word class instead of
566 ;; symbol class. GNU conventions say it should be symbol class, but
567 ;; there's a natural conflict between what major mode authors want
568 ;; and what users expect from `forward-word' and `backward-word'.
569 ;; Guido and I have hashed this out and have decided to keep
570 ;; underscore in word class. If you're tempted to change it, try
571 ;; binding M-f and M-b to py-forward-into-nomenclature and
572 ;; py-backward-into-nomenclature instead.
573 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
574 ;; Both single quote and double quote are string delimiters
575 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
576 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
577 ;; backquote is open and close paren
578 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
579 ;; comment delimiters
580 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
581 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
582 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000583
Barry Warsawb3e81d51996-09-04 15:12:42 +0000584
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000585
Barry Warsaw42f707f1996-07-29 21:05:05 +0000586;; Menu definitions, only relevent if you have the easymenu.el package
587;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000588(defvar py-menu nil
589 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000590This menu will get created automatically if you have the `easymenu'
591package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000592
Barry Warsawc72c11c1997-08-09 06:42:08 +0000593(and (py-safe (require 'easymenu) t)
594 (easy-menu-define
595 py-menu py-mode-map "Python Mode menu"
596 '("Python"
597 ["Comment Out Region" py-comment-region (mark)]
598 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
599 "-"
600 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000601 ["Mark current def" py-mark-def-or-class t]
602 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000603 "-"
604 ["Shift region left" py-shift-region-left (mark)]
605 ["Shift region right" py-shift-region-right (mark)]
606 "-"
607 ["Execute buffer" py-execute-buffer t]
608 ["Execute region" py-execute-region (mark)]
609 ["Start interpreter..." py-shell t]
610 "-"
611 ["Go to start of block" py-goto-block-up t]
612 ["Go to start of class" (beginning-of-python-def-or-class t) t]
613 ["Move to end of class" (end-of-python-def-or-class t) t]
614 ["Move to start of def" beginning-of-python-def-or-class t]
615 ["Move to end of def" end-of-python-def-or-class t]
616 "-"
617 ["Describe mode" py-describe-mode t]
618 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000619
Barry Warsaw81437461996-08-01 19:48:02 +0000620
621
622;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
623(defvar imenu-example--python-class-regexp
624 (concat ; <<classes>>
625 "\\(" ;
626 "^[ \t]*" ; newline and maybe whitespace
627 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
628 ; possibly multiple superclasses
629 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
630 "[ \t]*:" ; and the final :
631 "\\)" ; >>classes<<
632 )
633 "Regexp for Python classes for use with the imenu package."
634 )
635
636(defvar imenu-example--python-method-regexp
637 (concat ; <<methods and functions>>
638 "\\(" ;
639 "^[ \t]*" ; new line and maybe whitespace
640 "\\(def[ \t]+" ; function definitions start with def
641 "\\([a-zA-Z0-9_]+\\)" ; name is here
642 ; function arguments...
643 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
644 "\\)" ; end of def
645 "[ \t]*:" ; and then the :
646 "\\)" ; >>methods and functions<<
647 )
648 "Regexp for Python methods/functions for use with the imenu package."
649 )
650
651(defvar imenu-example--python-method-no-arg-parens '(2 8)
652 "Indicies into groups of the Python regexp for use with imenu.
653
654Using these values will result in smaller imenu lists, as arguments to
655functions are not listed.
656
657See the variable `imenu-example--python-show-method-args-p' for more
658information.")
659
660(defvar imenu-example--python-method-arg-parens '(2 7)
661 "Indicies into groups of the Python regexp for use with imenu.
662Using these values will result in large imenu lists, as arguments to
663functions are listed.
664
665See the variable `imenu-example--python-show-method-args-p' for more
666information.")
667
668;; Note that in this format, this variable can still be used with the
669;; imenu--generic-function. Otherwise, there is no real reason to have
670;; it.
671(defvar imenu-example--generic-python-expression
672 (cons
673 (concat
674 imenu-example--python-class-regexp
675 "\\|" ; or...
676 imenu-example--python-method-regexp
677 )
678 imenu-example--python-method-no-arg-parens)
679 "Generic Python expression which may be used directly with imenu.
680Used by setting the variable `imenu-generic-expression' to this value.
681Also, see the function \\[imenu-example--create-python-index] for a
682better alternative for finding the index.")
683
684;; These next two variables are used when searching for the python
685;; class/definitions. Just saving some time in accessing the
686;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000687(defvar imenu-example--python-generic-regexp nil)
688(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000689
690
Barry Warsaw81437461996-08-01 19:48:02 +0000691(defun imenu-example--create-python-index ()
692 "Python interface function for imenu package.
693Finds all python classes and functions/methods. Calls function
694\\[imenu-example--create-python-index-engine]. See that function for
695the details of how this works."
696 (setq imenu-example--python-generic-regexp
697 (car imenu-example--generic-python-expression))
698 (setq imenu-example--python-generic-parens
699 (if imenu-example--python-show-method-args-p
700 imenu-example--python-method-arg-parens
701 imenu-example--python-method-no-arg-parens))
702 (goto-char (point-min))
703 (imenu-example--create-python-index-engine nil))
704
705(defun imenu-example--create-python-index-engine (&optional start-indent)
706 "Function for finding imenu definitions in Python.
707
708Finds all definitions (classes, methods, or functions) in a Python
709file for the imenu package.
710
711Returns a possibly nested alist of the form
712
713 (INDEX-NAME . INDEX-POSITION)
714
715The second element of the alist may be an alist, producing a nested
716list as in
717
718 (INDEX-NAME . INDEX-ALIST)
719
720This function should not be called directly, as it calls itself
721recursively and requires some setup. Rather this is the engine for
722the function \\[imenu-example--create-python-index].
723
724It works recursively by looking for all definitions at the current
725indention level. When it finds one, it adds it to the alist. If it
726finds a definition at a greater indentation level, it removes the
727previous definition from the alist. In it's place it adds all
728definitions found at the next indentation level. When it finds a
729definition that is less indented then the current level, it retuns the
730alist it has created thus far.
731
732The optional argument START-INDENT indicates the starting indentation
733at which to continue looking for Python classes, methods, or
734functions. If this is not supplied, the function uses the indentation
735of the first definition found."
736 (let ((index-alist '())
737 (sub-method-alist '())
738 looking-p
739 def-name prev-name
740 cur-indent def-pos
741 (class-paren (first imenu-example--python-generic-parens))
742 (def-paren (second imenu-example--python-generic-parens)))
743 (setq looking-p
744 (re-search-forward imenu-example--python-generic-regexp
745 (point-max) t))
746 (while looking-p
747 (save-excursion
748 ;; used to set def-name to this value but generic-extract-name is
749 ;; new to imenu-1.14. this way it still works with imenu-1.11
750 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
751 (let ((cur-paren (if (match-beginning class-paren)
752 class-paren def-paren)))
753 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000754 (buffer-substring-no-properties (match-beginning cur-paren)
755 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000756 (beginning-of-line)
757 (setq cur-indent (current-indentation)))
758
759 ;; HACK: want to go to the next correct definition location. we
760 ;; explicitly list them here. would be better to have them in a
761 ;; list.
762 (setq def-pos
763 (or (match-beginning class-paren)
764 (match-beginning def-paren)))
765
766 ;; if we don't have a starting indent level, take this one
767 (or start-indent
768 (setq start-indent cur-indent))
769
770 ;; if we don't have class name yet, take this one
771 (or prev-name
772 (setq prev-name def-name))
773
774 ;; what level is the next definition on? must be same, deeper
775 ;; or shallower indentation
776 (cond
777 ;; at the same indent level, add it to the list...
778 ((= start-indent cur-indent)
779
780 ;; if we don't have push, use the following...
781 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
782 (push (cons def-name def-pos) index-alist))
783
784 ;; deeper indented expression, recur...
785 ((< start-indent cur-indent)
786
787 ;; the point is currently on the expression we're supposed to
788 ;; start on, so go back to the last expression. The recursive
789 ;; call will find this place again and add it to the correct
790 ;; list
791 (re-search-backward imenu-example--python-generic-regexp
792 (point-min) 'move)
793 (setq sub-method-alist (imenu-example--create-python-index-engine
794 cur-indent))
795
796 (if sub-method-alist
797 ;; we put the last element on the index-alist on the start
798 ;; of the submethod alist so the user can still get to it.
799 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000800 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000801 (cons save-elmt sub-method-alist))
802 index-alist))))
803
804 ;; found less indented expression, we're done.
805 (t
806 (setq looking-p nil)
807 (re-search-backward imenu-example--python-generic-regexp
808 (point-min) t)))
809 (setq prev-name def-name)
810 (and looking-p
811 (setq looking-p
812 (re-search-forward imenu-example--python-generic-regexp
813 (point-max) 'move))))
814 (nreverse index-alist)))
815
Barry Warsaw42f707f1996-07-29 21:05:05 +0000816
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000817;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000818(defun python-mode ()
819 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000820To submit a problem report, enter `\\[py-submit-bug-report]' from a
821`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
822documentation. To see what version of `python-mode' you are running,
823enter `\\[py-version]'.
824
825This mode knows about Python indentation, tokens, comments and
826continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000827
828COMMANDS
829\\{py-mode-map}
830VARIABLES
831
Barry Warsaw42f707f1996-07-29 21:05:05 +0000832py-indent-offset\t\tindentation increment
833py-block-comment-prefix\t\tcomment string used by comment-region
834py-python-command\t\tshell command to invoke Python interpreter
835py-scroll-process-buffer\t\talways scroll Python process buffer
836py-temp-directory\t\tdirectory used for temp files (if needed)
837py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000838 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000839 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000840 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000841 (make-local-variable 'font-lock-defaults)
842 (make-local-variable 'paragraph-separate)
843 (make-local-variable 'paragraph-start)
844 (make-local-variable 'require-final-newline)
845 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000846 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000847 (make-local-variable 'comment-start-skip)
848 (make-local-variable 'comment-column)
849 (make-local-variable 'indent-region-function)
850 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000851 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000852 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000853 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000854 (setq major-mode 'python-mode
855 mode-name "Python"
856 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000857 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000858 paragraph-separate "^[ \t]*$"
859 paragraph-start "^[ \t]*$"
860 require-final-newline t
861 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000862 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000863 comment-start-skip "# *"
864 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000865 indent-region-function 'py-indent-region
866 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000867 ;; tell add-log.el how to find the current function/method/variable
868 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000869 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000870 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000871 ;; add the menu
872 (if py-menu
873 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000874 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000875 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000876 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000878 ;;
879 ;; not sure where the magic comment has to be; to save time
880 ;; searching for a rarity, we give up if it's not found prior to the
881 ;; first executable statement.
882 ;;
883 ;; BAW - on first glance, this seems like complete hackery. Why was
884 ;; this necessary, and is it still necessary?
885 (let ((case-fold-search nil)
886 (start (point))
887 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000888 (if (re-search-forward
889 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
890 (prog2 (py-next-statement 1) (point) (goto-char 1))
891 t)
892 (progn
893 (setq new-tab-width
894 (string-to-int
895 (buffer-substring (match-beginning 1) (match-end 1))))
896 (if (= tab-width new-tab-width)
897 nil
898 (setq tab-width new-tab-width)
899 (message "Caution: tab-width changed to %d" new-tab-width)
900 (if py-beep-if-tab-change (beep)))))
901 (goto-char start))
902
Barry Warsaw755c6711996-08-01 20:02:55 +0000903 ;; install imenu
Barry Warsaw27ee1151997-12-03 05:03:44 +0000904 (if (py-safe (require 'imenu))
905 (progn
906 (make-variable-buffer-local 'imenu-create-index-function)
907 (setq imenu-create-index-function
908 (function imenu-example--create-python-index))
909 (setq imenu-generic-expression
910 imenu-example--generic-python-expression)
911 (if (fboundp 'imenu-add-to-menubar)
912 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
913 ))
Barry Warsaw755c6711996-08-01 20:02:55 +0000914
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000915 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916 (if python-mode-hook
917 (run-hooks 'python-mode-hook)
918 (run-hooks 'py-mode-hook)))
919
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920
Barry Warsawb91b7431995-03-14 15:55:20 +0000921;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000922(defun py-outdent-p ()
923 ;; returns non-nil if the current line should outdent one level
924 (save-excursion
925 (and (progn (back-to-indentation)
926 (looking-at py-outdent-re))
927 (progn (backward-to-indentation 1)
928 (while (or (looking-at py-blank-or-comment-re)
929 (bobp))
930 (backward-to-indentation 1))
931 (not (looking-at py-no-outdent-re)))
932 )))
933
Barry Warsawb91b7431995-03-14 15:55:20 +0000934(defun py-electric-colon (arg)
935 "Insert a colon.
936In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000937argument is provided, that many colons are inserted non-electrically.
938Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000939 (interactive "P")
940 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000941 ;; are we in a string or comment?
942 (if (save-excursion
943 (let ((pps (parse-partial-sexp (save-excursion
944 (beginning-of-python-def-or-class)
945 (point))
946 (point))))
947 (not (or (nth 3 pps) (nth 4 pps)))))
948 (save-excursion
949 (let ((here (point))
950 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000951 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000952 (if (and (not arg)
953 (py-outdent-p)
954 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000955 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000956 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000957 )
958 (setq outdent py-indent-offset))
959 ;; Don't indent, only outdent. This assumes that any lines that
960 ;; are already outdented relative to py-compute-indentation were
961 ;; put there on purpose. Its highly annoying to have `:' indent
962 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
963 ;; there a better way to determine this???
964 (if (< (current-indentation) indent) nil
965 (goto-char here)
966 (beginning-of-line)
967 (delete-horizontal-space)
968 (indent-to (- indent outdent))
969 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000970
971
Barry Warsawa97a3f31997-11-04 18:47:06 +0000972;; Python subprocess utilities and filters
973(defun py-execute-file (proc filename)
974 ;; Send a properly formatted execfile('FILENAME') to the underlying
975 ;; Python interpreter process FILENAME. Make that process's buffer
976 ;; visible and force display. Also make comint believe the user
977 ;; typed this string so that kill-output-from-shell does The Right
978 ;; Thing.
979 (let ((curbuf (current-buffer))
980 (procbuf (process-buffer proc))
981 (comint-scroll-to-bottom-on-output t)
982 (msg (format "## working on region in file %s...\n" filename))
983 (cmd (format "execfile('%s')\n" filename)))
984 (unwind-protect
985 (progn
986 (set-buffer procbuf)
987 (goto-char (point-max))
988 (move-marker (process-mark proc) (point))
989 (funcall (process-filter proc) proc msg))
990 (set-buffer curbuf))
991 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992
993(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000994 (let ((curbuf (current-buffer))
995 (pbuf (process-buffer pyproc))
996 (pmark (process-mark pyproc))
997 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000998 ;; make sure we switch to a different buffer at least once. if we
999 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001000 ;; window, and point is before the end, and lots of output is
1001 ;; coming at a fast pace, then (a) simple cursor-movement commands
1002 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1003 ;; to have a visible effect (the window just doesn't get updated,
1004 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1005 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007 ;; #b makes no sense to me at all. #a almost makes sense: unless
1008 ;; we actually change buffers, set_buffer_internal in buffer.c
1009 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1010 ;; seems to make the Emacs command loop reluctant to update the
1011 ;; display. Perhaps the default process filter in process.c's
1012 ;; read_process_output has update_mode_lines++ for a similar
1013 ;; reason? beats me ...
1014
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001015 (unwind-protect
1016 ;; make sure current buffer is restored
1017 ;; BAW - we want to check to see if this still applies
1018 (progn
1019 ;; mysterious ugly hack
1020 (if (eq curbuf pbuf)
1021 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001023 (set-buffer pbuf)
1024 (let* ((start (point))
1025 (goback (< start pmark))
1026 (goend (and (not goback) (= start (point-max))))
1027 (buffer-read-only nil))
1028 (goto-char pmark)
1029 (insert string)
1030 (move-marker pmark (point))
1031 (setq file-finished
1032 (and py-file-queue
1033 (equal ">>> "
1034 (buffer-substring
1035 (prog2 (beginning-of-line) (point)
1036 (goto-char pmark))
1037 (point)))))
1038 (if goback (goto-char start)
1039 ;; else
1040 (if py-scroll-process-buffer
1041 (let* ((pop-up-windows t)
1042 (pwin (display-buffer pbuf)))
1043 (set-window-point pwin (point)))))
1044 (set-buffer curbuf)
1045 (if file-finished
1046 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001047 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001048 (setq py-file-queue (cdr py-file-queue))
1049 (if py-file-queue
1050 (py-execute-file pyproc (car py-file-queue)))))
1051 (and goend
1052 (progn (set-buffer pbuf)
1053 (goto-char (point-max))))
1054 ))
1055 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001056
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001057(defun py-postprocess-output-buffer (buf)
Barry Warsaw9981d221997-12-03 05:25:48 +00001058 (let (line file bol)
1059 (save-excursion
1060 (set-buffer buf)
1061 (beginning-of-buffer)
1062 (while (re-search-forward py-traceback-line-re nil t)
1063 (setq file (match-string 1)
1064 line (string-to-int (match-string 2))
1065 bol (py-point 'bol))
1066 (py-highlight-line bol (py-point 'eol) file line))
1067 (when (and py-jump-on-exception line)
1068 (beep)
1069 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001070 )))
1071
Barry Warsaw9981d221997-12-03 05:25:48 +00001072
Barry Warsawa97a3f31997-11-04 18:47:06 +00001073
1074;;; Subprocess commands
1075
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001076;; only used when (memq 'broken-temp-names py-emacs-features)
1077(defvar py-serial-number 0)
1078(defvar py-exception-buffer nil)
1079(defconst py-output-buffer "*Python Output*")
1080
Barry Warsawa97a3f31997-11-04 18:47:06 +00001081;;;###autoload
1082(defun py-shell ()
1083 "Start an interactive Python interpreter in another window.
1084This is like Shell mode, except that Python is running in the window
1085instead of a shell. See the `Interactive Shell' and `Shell Mode'
1086sections of the Emacs manual for details, especially for the key
1087bindings active in the `*Python*' buffer.
1088
1089See the docs for variable `py-scroll-buffer' for info on scrolling
1090behavior in the process window.
1091
1092Warning: Don't use an interactive Python if you change sys.ps1 or
1093sys.ps2 from their default values, or if you're running code that
1094prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1095distinguish your output from Python's output, and assumes that `>>> '
1096at the start of a line is a prompt from Python. Similarly, the Emacs
1097Shell mode code assumes that both `>>> ' and `... ' at the start of a
1098line are Python prompts. Bad things can happen if you fool either
1099mode.
1100
1101Warning: If you do any editing *in* the process buffer *while* the
1102buffer is accepting output from Python, do NOT attempt to `undo' the
1103changes. Some of the output (nowhere near the parts you changed!) may
1104be lost if you do. This appears to be an Emacs bug, an unfortunate
1105interaction between undo and process filters; the same problem exists in
1106non-Python process buffers using the default (Emacs-supplied) process
1107filter."
1108 ;; BAW - should undo be disabled in the python process buffer, if
1109 ;; this bug still exists?
1110 (interactive)
1111 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001112 (switch-to-buffer-other-window
1113 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001114 (make-local-variable 'comint-prompt-regexp)
1115 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1116 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1117 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001118 ;; set up keybindings for this subshell
1119 (local-set-key [tab] 'self-insert-command)
1120 (local-set-key "\C-c-" 'py-up-exception)
1121 (local-set-key "\C-c=" 'py-down-exception)
1122 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001123
Barry Warsawa97a3f31997-11-04 18:47:06 +00001124(defun py-clear-queue ()
1125 "Clear the queue of temporary files waiting to execute."
1126 (interactive)
1127 (let ((n (length py-file-queue)))
1128 (mapcar 'delete-file py-file-queue)
1129 (setq py-file-queue nil)
1130 (message "%d pending files de-queued." n)))
1131
1132(defun py-execute-region (start end &optional async)
1133 "Execute the the region in a Python interpreter.
1134The region is first copied into a temporary file (in the directory
1135`py-temp-directory'). If there is no Python interpreter shell
1136running, this file is executed synchronously using
1137`shell-command-on-region'. If the program is long running, use an
1138optional \\[universal-argument] to run the command asynchronously in
1139its own buffer.
1140
1141If the Python interpreter shell is running, the region is execfile()'d
1142in that shell. If you try to execute regions too quickly,
1143`python-mode' will queue them up and execute them one at a time when
1144it sees a `>>> ' prompt from Python. Each time this happens, the
1145process buffer is popped into a window (if it's not already in some
1146window) so you can see it, and a comment of the form
1147
1148 \t## working on region in file <name>...
1149
1150is inserted at the end. See also the command `py-clear-queue'."
1151 (interactive "r\nP")
1152 (or (< start end)
1153 (error "Region is empty"))
1154 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001155 (temp (if (memq 'broken-temp-names py-emacs-features)
1156 (prog1
1157 (format "python-%d" py-serial-number)
1158 (setq py-serial-number (1+ py-serial-number)))
1159 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001160 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001161 (write-region start end file nil 'nomsg)
1162 (cond
1163 ;; always run the code in it's own asynchronous subprocess
1164 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001165 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001166 (start-process "Python" buf py-python-command "-u" file)
1167 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001168 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001169 ))
1170 ;; if the Python interpreter shell is running, queue it up for
1171 ;; execution there.
1172 (proc
1173 ;; use the existing python shell
1174 (if (not py-file-queue)
1175 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001176 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001177 (push file py-file-queue)
1178 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001179 (t
1180 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001181 (shell-command-on-region start end py-python-command py-output-buffer)
1182 (setq py-exception-buffer (current-buffer))
1183 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001184 ))))
1185
1186;; Code execution command
1187(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001188 "Send the contents of the buffer to a Python interpreter.
1189If there is a *Python* process buffer it is used. If a clipping
1190restriction is in effect, only the accessible portion of the buffer is
1191sent. A trailing newline will be supplied if needed.
1192
1193See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001194 (interactive "P")
1195 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001196
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001197
1198
1199(defun py-jump-to-exception (file line)
1200 (let ((buffer (cond ((string-equal file "<stdin>")
1201 py-exception-buffer)
1202 ((and (consp py-exception-buffer)
1203 (string-equal file (car py-exception-buffer)))
1204 (cdr py-exception-buffer))
1205 ((py-safe (find-file-noselect file)))
1206 ;; could not figure out what file the exception
1207 ;; is pointing to, so prompt for it
1208 (t (find-file (read-file-name "Exception file: "
1209 nil
1210 file t))))))
1211 (pop-to-buffer buffer)
1212 (goto-line line)
1213 (message "Jumping to exception in file %s on line %d" file line)))
1214
1215(defun py-mouseto-exception (event)
1216 (interactive "e")
1217 (cond
1218 ((fboundp 'event-point)
1219 ;; XEmacs
1220 (let* ((point (event-point event))
1221 (buffer (event-buffer event))
1222 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1223 (info (and e (extent-property e 'py-exc-info))))
1224 (message "Event point: %d, info: %s" point info)
1225 (and info
1226 (py-jump-to-exception (car info) (cdr info)))
1227 ))
1228 ;; Emacs -- Please port this!
1229 ))
1230
1231(defun py-goto-exception ()
1232 "Go to the line indicated by the traceback."
1233 (interactive)
1234 (let (file line)
1235 (save-excursion
1236 (beginning-of-line)
1237 (if (looking-at py-traceback-line-re)
1238 (setq file (match-string 1)
1239 line (string-to-int (match-string 2)))))
1240 (if (not file)
1241 (error "Not on a traceback line."))
1242 (py-jump-to-exception file line)))
1243
1244(defun py-find-next-exception (start buffer searchdir errwhere)
1245 ;; Go to start position in buffer, search in the specified
1246 ;; direction, and jump to the exception found. If at the end of the
1247 ;; exception, print error message
1248 (let (file line)
1249 (save-excursion
1250 (set-buffer buffer)
1251 (goto-char (py-point start))
1252 (if (funcall searchdir py-traceback-line-re nil t)
1253 (setq file (match-string 1)
1254 line (string-to-int (match-string 2)))))
1255 (if (and file line)
1256 (py-jump-to-exception file line)
1257 (error "%s of traceback" errwhere))))
1258
1259(defun py-down-exception (&optional bottom)
1260 "Go to the next line down in the traceback.
1261With optional \\[universal-argument], jump to the bottom (innermost)
1262exception in the exception stack."
1263 (interactive "P")
1264 (let* ((proc (get-process "Python"))
1265 (buffer (if proc "*Python*" py-output-buffer)))
1266 (if bottom
1267 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1268 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1269
1270(defun py-up-exception (&optional top)
1271 "Go to the previous line up in the traceback.
1272With optional \\[universal-argument], jump to the top (outermost)
1273exception in the exception stack."
1274 (interactive "P")
1275 (let* ((proc (get-process "Python"))
1276 (buffer (if proc "*Python*" py-output-buffer)))
1277 (if top
1278 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001279 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001280
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001282;; Electric deletion
1283(defun py-electric-backspace (arg)
1284 "Deletes preceding character or levels of indentation.
1285Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001286with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001287
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001288If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001289
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001290Otherwise, if point is at the leftmost non-whitespace character of a
1291line that is neither a continuation line nor a non-indenting comment
1292line, or if point is at the end of a blank line, this command reduces
1293the indentation to match that of the line that opened the current
1294block of code. The line that opened the block is displayed in the
1295echo area to help you keep track of where you are. With numeric arg,
1296outdents that many blocks (but not past column zero).
1297
1298Otherwise the preceding character is deleted, converting a tab to
1299spaces if needed so that only a single column position is deleted.
1300Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001301 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001302 (if (or (/= (current-indentation) (current-column))
1303 (bolp)
1304 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001305 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001306 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001307 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001308 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001309 ;; force non-blank so py-goto-block-up doesn't ignore it
1310 (insert-char ?* 1)
1311 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001312 (let ((base-indent 0) ; indentation of base line
1313 (base-text "") ; and text of base line
1314 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001315 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001316 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001317 (condition-case nil ; in case no enclosing block
1318 (progn
1319 (py-goto-block-up 'no-mark)
1320 (setq base-indent (current-indentation)
1321 base-text (py-suck-up-leading-text)
1322 base-found-p t))
1323 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001324 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001325 (delete-char 1) ; toss the dummy character
1326 (delete-horizontal-space)
1327 (indent-to base-indent)
1328 (if base-found-p
1329 (message "Closes block: %s" base-text)))))
1330
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001331
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001332(defun py-electric-delete (arg)
1333 "Deletes preceding or following character or levels of whitespace.
1334
1335The behavior of this function depends on the variable
1336`delete-key-deletes-forward'. If this variable is nil (or does not
1337exist, as in older Emacsen), then this function behaves identical to
1338\\[c-electric-backspace].
1339
1340If `delete-key-deletes-forward' is non-nil and is supported in your
1341Emacs, then deletion occurs in the forward direction, by calling the
1342function in `py-delete-function'."
1343 (interactive "*p")
1344 (if (and (boundp 'delete-key-deletes-forward)
1345 delete-key-deletes-forward)
1346 (funcall py-delete-function arg)
1347 ;; else
1348 (py-electric-backspace arg)))
1349
1350;; required for pending-del and delsel modes
1351(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1352(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1353(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1354(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1355
1356
1357
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001358(defun py-indent-line (&optional arg)
1359 "Fix the indentation of the current line according to Python rules.
1360With \\[universal-argument], ignore outdenting rules for block
1361closing statements (e.g. return, raise, break, continue, pass)
1362
1363This function is normally bound to `indent-line-function' so
1364\\[indent-for-tab-command] will call it."
1365 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001366 (let* ((ci (current-indentation))
1367 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001368 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001369 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001370 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001371 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001372 (if (/= ci need)
1373 (save-excursion
1374 (beginning-of-line)
1375 (delete-horizontal-space)
1376 (indent-to need)))
1377 (if move-to-indentation-p (back-to-indentation))))
1378
1379(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001380 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001381This is just `strives to' because correct indentation can't be computed
1382from scratch for Python code. In general, deletes the whitespace before
1383point, inserts a newline, and takes an educated guess as to how you want
1384the new line indented."
1385 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001386 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001387 (if (< ci (current-column)) ; if point beyond indentation
1388 (newline-and-indent)
1389 ;; else try to act like newline-and-indent "normally" acts
1390 (beginning-of-line)
1391 (insert-char ?\n 1)
1392 (move-to-column ci))))
1393
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001394(defun py-compute-indentation (honor-block-close-p)
1395 ;; implements all the rules for indentation computation. when
1396 ;; honor-block-close-p is non-nil, statements such as return, raise,
1397 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001398 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001399 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001400 (pps (parse-partial-sexp bod (point)))
1401 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001402 (beginning-of-line)
1403 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001404 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001405 ((or (and (nth 3 pps) (nth 3 boipps))
1406 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001407 (save-excursion
1408 (if (not py-align-multiline-strings-p) 0
1409 ;; skip back over blank & non-indenting comment lines
1410 ;; note: will skip a blank or non-indenting comment line
1411 ;; that happens to be a continuation line too
1412 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1413 (back-to-indentation)
1414 (current-column))))
1415 ;; are we on a continuation line?
1416 ((py-continuation-line-p)
1417 (let ((startpos (point))
1418 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001419 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001420 (if open-bracket-pos
1421 (progn
1422 ;; align with first item in list; else a normal
1423 ;; indent beyond the line with the open bracket
1424 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1425 ;; is the first list item on the same line?
1426 (skip-chars-forward " \t")
1427 (if (null (memq (following-char) '(?\n ?# ?\\)))
1428 ; yes, so line up with it
1429 (current-column)
1430 ;; first list item on another line, or doesn't exist yet
1431 (forward-line 1)
1432 (while (and (< (point) startpos)
1433 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1434 (forward-line 1))
1435 (if (< (point) startpos)
1436 ;; again mimic the first list item
1437 (current-indentation)
1438 ;; else they're about to enter the first item
1439 (goto-char open-bracket-pos)
1440 (+ (current-indentation) py-indent-offset))))
1441
1442 ;; else on backslash continuation line
1443 (forward-line -1)
1444 (if (py-continuation-line-p) ; on at least 3rd line in block
1445 (current-indentation) ; so just continue the pattern
1446 ;; else started on 2nd line in block, so indent more.
1447 ;; if base line is an assignment with a start on a RHS,
1448 ;; indent to 2 beyond the leftmost "="; else skip first
1449 ;; chunk of non-whitespace characters on base line, + 1 more
1450 ;; column
1451 (end-of-line)
1452 (setq endpos (point) searching t)
1453 (back-to-indentation)
1454 (setq startpos (point))
1455 ;; look at all "=" from left to right, stopping at first
1456 ;; one not nested in a list or string
1457 (while searching
1458 (skip-chars-forward "^=" endpos)
1459 (if (= (point) endpos)
1460 (setq searching nil)
1461 (forward-char 1)
1462 (setq state (parse-partial-sexp startpos (point)))
1463 (if (and (zerop (car state)) ; not in a bracket
1464 (null (nth 3 state))) ; & not in a string
1465 (progn
1466 (setq searching nil) ; done searching in any case
1467 (setq found
1468 (not (or
1469 (eq (following-char) ?=)
1470 (memq (char-after (- (point) 2))
1471 '(?< ?> ?!)))))))))
1472 (if (or (not found) ; not an assignment
1473 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1474 (progn
1475 (goto-char startpos)
1476 (skip-chars-forward "^ \t\n")))
1477 (1+ (current-column))))))
1478
1479 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001480 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001481
Barry Warsawa7891711996-08-01 15:53:09 +00001482 ;; Dfn: "Indenting comment line". A line containing only a
1483 ;; comment, but which is treated like a statement for
1484 ;; indentation calculation purposes. Such lines are only
1485 ;; treated specially by the mode; they are not treated
1486 ;; specially by the Python interpreter.
1487
1488 ;; The rules for indenting comment lines are a line where:
1489 ;; - the first non-whitespace character is `#', and
1490 ;; - the character following the `#' is whitespace, and
1491 ;; - the line is outdented with respect to (i.e. to the left
1492 ;; of) the indentation of the preceding non-blank line.
1493
1494 ;; The first non-blank line following an indenting comment
1495 ;; line is given the same amount of indentation as the
1496 ;; indenting comment line.
1497
1498 ;; All other comment-only lines are ignored for indentation
1499 ;; purposes.
1500
1501 ;; Are we looking at a comment-only line which is *not* an
1502 ;; indenting comment line? If so, we assume that its been
1503 ;; placed at the desired indentation, so leave it alone.
1504 ;; Indenting comment lines are aligned as statements down
1505 ;; below.
1506 ((and (looking-at "[ \t]*#[^ \t\n]")
1507 ;; NOTE: this test will not be performed in older Emacsen
1508 (fboundp 'forward-comment)
1509 (<= (current-indentation)
1510 (save-excursion
1511 (forward-comment (- (point-max)))
1512 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001513 (current-indentation))
1514
1515 ;; else indentation based on that of the statement that
1516 ;; precedes us; use the first line of that statement to
1517 ;; establish the base, in case the user forced a non-std
1518 ;; indentation for the continuation lines (if any)
1519 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001520 ;; skip back over blank & non-indenting comment lines note:
1521 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001522 ;; happens to be a continuation line too. use fast Emacs 19
1523 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001524 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001525 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001526 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001527 (let (done)
1528 (while (not done)
1529 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1530 nil 'move)
1531 (setq done (or (eq py-honor-comment-indentation t)
1532 (bobp)
1533 (/= (following-char) ?#)
1534 (not (zerop (current-column)))))
1535 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001536 ;; if we landed inside a string, go to the beginning of that
1537 ;; string. this handles triple quoted, multi-line spanning
1538 ;; strings.
1539 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001540 (+ (current-indentation)
1541 (if (py-statement-opens-block-p)
1542 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001543 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001544 (- py-indent-offset)
1545 0)))
1546 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547
1548(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001549 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001550By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001551`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001554their own buffer-local copy), both those currently existing and those
1555created later in the Emacs session.
1556
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001557Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001558There's no excuse for such foolishness, but sometimes you have to deal
1559with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560`py-indent-offset' to what it thinks it was when they created the
1561mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001562
1563Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001564looking for a line that opens a block of code. `py-indent-offset' is
1565set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566statement following it. If the search doesn't succeed going forward,
1567it's tried again going backward."
1568 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001569 (let (new-value
1570 (start (point))
1571 restart
1572 (found nil)
1573 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001574 (py-goto-initial-line)
1575 (while (not (or found (eobp)))
1576 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1577 (progn
1578 (setq restart (point))
1579 (py-goto-initial-line)
1580 (if (py-statement-opens-block-p)
1581 (setq found t)
1582 (goto-char restart)))))
1583 (if found
1584 ()
1585 (goto-char start)
1586 (py-goto-initial-line)
1587 (while (not (or found (bobp)))
1588 (setq found
1589 (and
1590 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1591 (or (py-goto-initial-line) t) ; always true -- side effect
1592 (py-statement-opens-block-p)))))
1593 (setq colon-indent (current-indentation)
1594 found (and found (zerop (py-next-statement 1)))
1595 new-value (- (current-indentation) colon-indent))
1596 (goto-char start)
1597 (if found
1598 (progn
1599 (funcall (if global 'kill-local-variable 'make-local-variable)
1600 'py-indent-offset)
1601 (setq py-indent-offset new-value)
1602 (message "%s value of py-indent-offset set to %d"
1603 (if global "Global" "Local")
1604 py-indent-offset))
1605 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1606
1607(defun py-shift-region (start end count)
1608 (save-excursion
1609 (goto-char end) (beginning-of-line) (setq end (point))
1610 (goto-char start) (beginning-of-line) (setq start (point))
1611 (indent-rigidly start end count)))
1612
1613(defun py-shift-region-left (start end &optional count)
1614 "Shift region of Python code to the left.
1615The lines from the line containing the start of the current region up
1616to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001617shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001618
1619If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001620many columns. With no active region, outdent only the current line.
1621You cannot outdent the region if any line is already at column zero."
1622 (interactive
1623 (let ((p (point))
1624 (m (mark))
1625 (arg current-prefix-arg))
1626 (if m
1627 (list (min p m) (max p m) arg)
1628 (list p (save-excursion (forward-line 1) (point)) arg))))
1629 ;; if any line is at column zero, don't shift the region
1630 (save-excursion
1631 (goto-char start)
1632 (while (< (point) end)
1633 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001634 (if (and (zerop (current-column))
1635 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001636 (error "Region is at left edge."))
1637 (forward-line 1)))
1638 (py-shift-region start end (- (prefix-numeric-value
1639 (or count py-indent-offset))))
1640 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641
1642(defun py-shift-region-right (start end &optional count)
1643 "Shift region of Python code to the right.
1644The lines from the line containing the start of the current region up
1645to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001646shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001647
1648If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001649many columns. With no active region, indent only the current line."
1650 (interactive
1651 (let ((p (point))
1652 (m (mark))
1653 (arg current-prefix-arg))
1654 (if m
1655 (list (min p m) (max p m) arg)
1656 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001658 (or count py-indent-offset)))
1659 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660
1661(defun py-indent-region (start end &optional indent-offset)
1662 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001663
Barry Warsaw7ae77681994-12-12 20:38:05 +00001664The lines from the line containing the start of the current region up
1665to (but not including) the line containing the end of the region are
1666reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001667character in the first column, the first line is left alone and the
1668rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001669region is reindented with respect to the (closest code or indenting
1670comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001671
1672This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001673control structures are introduced or removed, or to reformat code
1674using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001675
1676If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001677the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001678used.
1679
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001680Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001681is called! This function does not compute proper indentation from
1682scratch (that's impossible in Python), it merely adjusts the existing
1683indentation to be correct in context.
1684
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001685Warning: This function really has no idea what to do with
1686non-indenting comment lines, and shifts them as if they were indenting
1687comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001688
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001689Special cases: whitespace is deleted from blank lines; continuation
1690lines are shifted by the same amount their initial line was shifted,
1691in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001692initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001693 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001694 (save-excursion
1695 (goto-char end) (beginning-of-line) (setq end (point-marker))
1696 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001697 (let ((py-indent-offset (prefix-numeric-value
1698 (or indent-offset py-indent-offset)))
1699 (indents '(-1)) ; stack of active indent levels
1700 (target-column 0) ; column to which to indent
1701 (base-shifted-by 0) ; amount last base line was shifted
1702 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001703 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001704 0))
1705 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001706 (while (< (point) end)
1707 (setq ci (current-indentation))
1708 ;; figure out appropriate target column
1709 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001710 ((or (eq (following-char) ?#) ; comment in column 1
1711 (looking-at "[ \t]*$")) ; entirely blank
1712 (setq target-column 0))
1713 ((py-continuation-line-p) ; shift relative to base line
1714 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715 (t ; new base line
1716 (if (> ci (car indents)) ; going deeper; push it
1717 (setq indents (cons ci indents))
1718 ;; else we should have seen this indent before
1719 (setq indents (memq ci indents)) ; pop deeper indents
1720 (if (null indents)
1721 (error "Bad indentation in region, at line %d"
1722 (save-restriction
1723 (widen)
1724 (1+ (count-lines 1 (point)))))))
1725 (setq target-column (+ indent-base
1726 (* py-indent-offset
1727 (- (length indents) 2))))
1728 (setq base-shifted-by (- target-column ci))))
1729 ;; shift as needed
1730 (if (/= ci target-column)
1731 (progn
1732 (delete-horizontal-space)
1733 (indent-to target-column)))
1734 (forward-line 1))))
1735 (set-marker end nil))
1736
Barry Warsawa7891711996-08-01 15:53:09 +00001737(defun py-comment-region (beg end &optional arg)
1738 "Like `comment-region' but uses double hash (`#') comment starter."
1739 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001740 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001741 (comment-region beg end arg)))
1742
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743
1744;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001745(defun py-previous-statement (count)
1746 "Go to the start of previous Python statement.
1747If the statement at point is the i'th Python statement, goes to the
1748start of statement i-COUNT. If there is no such statement, goes to the
1749first statement. Returns count of statements left to move.
1750`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752 (if (< count 0) (py-next-statement (- count))
1753 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001754 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001755 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757 (> count 0)
1758 (zerop (forward-line -1))
1759 (py-goto-statement-at-or-above))
1760 (setq count (1- count)))
1761 (if (> count 0) (goto-char start)))
1762 count))
1763
1764(defun py-next-statement (count)
1765 "Go to the start of next Python statement.
1766If the statement at point is the i'th Python statement, goes to the
1767start of statement i+COUNT. If there is no such statement, goes to the
1768last statement. Returns count of statements left to move. `Statements'
1769do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771 (if (< count 0) (py-previous-statement (- count))
1772 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001775 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776 (> count 0)
1777 (py-goto-statement-below))
1778 (setq count (1- count)))
1779 (if (> count 0) (goto-char start)))
1780 count))
1781
1782(defun py-goto-block-up (&optional nomark)
1783 "Move up to start of current block.
1784Go to the statement that starts the smallest enclosing block; roughly
1785speaking, this will be the closest preceding statement that ends with a
1786colon and is indented less than the statement you started on. If
1787successful, also sets the mark to the starting point.
1788
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789`\\[py-mark-block]' can be used afterward to mark the whole code
1790block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791
1792If called from a program, the mark will not be set if optional argument
1793NOMARK is not nil."
1794 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001795 (let ((start (point))
1796 (found nil)
1797 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001798 (py-goto-initial-line)
1799 ;; if on blank or non-indenting comment line, use the preceding stmt
1800 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1801 (progn
1802 (py-goto-statement-at-or-above)
1803 (setq found (py-statement-opens-block-p))))
1804 ;; search back for colon line indented less
1805 (setq initial-indent (current-indentation))
1806 (if (zerop initial-indent)
1807 ;; force fast exit
1808 (goto-char (point-min)))
1809 (while (not (or found (bobp)))
1810 (setq found
1811 (and
1812 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1813 (or (py-goto-initial-line) t) ; always true -- side effect
1814 (< (current-indentation) initial-indent)
1815 (py-statement-opens-block-p))))
1816 (if found
1817 (progn
1818 (or nomark (push-mark start))
1819 (back-to-indentation))
1820 (goto-char start)
1821 (error "Enclosing block not found"))))
1822
1823(defun beginning-of-python-def-or-class (&optional class)
1824 "Move point to start of def (or class, with prefix arg).
1825
1826Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827arg, looks for a `class' instead. The docs assume the `def' case;
1828just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001830If point is in a def statement already, and after the `d', simply
1831moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833Else (point is not in a def statement, or at or before the `d' of a
1834def statement), searches for the closest preceding def statement, and
1835leaves point at its start. If no such statement can be found, leaves
1836point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001837
1838Returns t iff a def statement is found by these rules.
1839
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001840Note that doing this command repeatedly will take you closer to the
1841start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001844`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001845 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1847 (start-of-line (progn (beginning-of-line) (point)))
1848 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001849 (if (or (/= start-of-stmt start-of-line)
1850 (not at-or-before-p))
1851 (end-of-line)) ; OK to match on this line
1852 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854
1855(defun end-of-python-def-or-class (&optional class)
1856 "Move point beyond end of def (or class, with prefix arg) body.
1857
1858By default, looks for an appropriate `def'. If you supply a prefix arg,
1859looks for a `class' instead. The docs assume the `def' case; just
1860substitute `class' for `def' for the other case.
1861
1862If point is in a def statement already, this is the def we use.
1863
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001864Else if the def found by `\\[beginning-of-python-def-or-class]'
1865contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866
1867Else we search forward for the closest following def, and use that.
1868
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869If a def can be found by these rules, point is moved to the start of
1870the line immediately following the def block, and the position of the
1871start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001872
1873Else point is moved to the end of the buffer, and nil is returned.
1874
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875Note that doing this command repeatedly will take you closer to the
1876end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001877
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001879`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001881 (let ((start (progn (py-goto-initial-line) (point)))
1882 (which (if class "class" "def"))
1883 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884 ;; move point to start of appropriate def/class
1885 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1886 (setq state 'at-beginning)
1887 ;; else see if beginning-of-python-def-or-class hits container
1888 (if (and (beginning-of-python-def-or-class class)
1889 (progn (py-goto-beyond-block)
1890 (> (point) start)))
1891 (setq state 'at-end)
1892 ;; else search forward
1893 (goto-char start)
1894 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1895 (progn (setq state 'at-beginning)
1896 (beginning-of-line)))))
1897 (cond
1898 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1899 ((eq state 'at-end) t)
1900 ((eq state 'not-found) nil)
1901 (t (error "internal error in end-of-python-def-or-class")))))
1902
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001903
1904;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905(defun py-mark-block (&optional extend just-move)
1906 "Mark following block of lines. With prefix arg, mark structure.
1907Easier to use than explain. It sets the region to an `interesting'
1908block of succeeding lines. If point is on a blank line, it goes down to
1909the next non-blank line. That will be the start of the region. The end
1910of the region depends on the kind of line at the start:
1911
1912 - If a comment, the region will include all succeeding comment lines up
1913 to (but not including) the next non-comment line (if any).
1914
1915 - Else if a prefix arg is given, and the line begins one of these
1916 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001917
1918 if elif else try except finally for while def class
1919
Barry Warsaw7ae77681994-12-12 20:38:05 +00001920 the region will be set to the body of the structure, including
1921 following blocks that `belong' to it, but excluding trailing blank
1922 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001923 and all (if any) of the following `except' and `finally' blocks
1924 that belong to the `try' structure will be in the region. Ditto
1925 for if/elif/else, for/else and while/else structures, and (a bit
1926 degenerate, since they're always one-block structures) def and
1927 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001928
1929 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930 block (see list above), and the block is not a `one-liner' (i.e.,
1931 the statement ends with a colon, not with code), the region will
1932 include all succeeding lines up to (but not including) the next
1933 code statement (if any) that's indented no more than the starting
1934 line, except that trailing blank and comment lines are excluded.
1935 E.g., if the starting line begins a multi-statement `def'
1936 structure, the region will be set to the full function definition,
1937 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938
1939 - Else the region will include all succeeding lines up to (but not
1940 including) the next blank line, or code or indenting-comment line
1941 indented strictly less than the starting line. Trailing indenting
1942 comment lines are included in this case, but not trailing blank
1943 lines.
1944
1945A msg identifying the location of the mark is displayed in the echo
1946area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1947
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001948If called from a program, optional argument EXTEND plays the role of
1949the prefix arg, and if optional argument JUST-MOVE is not nil, just
1950moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (interactive "P") ; raw prefix arg
1952 (py-goto-initial-line)
1953 ;; skip over blank lines
1954 (while (and
1955 (looking-at "[ \t]*$") ; while blank line
1956 (not (eobp))) ; & somewhere to go
1957 (forward-line 1))
1958 (if (eobp)
1959 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001960 (let ((initial-pos (point))
1961 (initial-indent (current-indentation))
1962 last-pos ; position of last stmt in region
1963 (followers
1964 '((if elif else) (elif elif else) (else)
1965 (try except finally) (except except) (finally)
1966 (for else) (while else)
1967 (def) (class) ) )
1968 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001969
1970 (cond
1971 ;; if comment line, suck up the following comment lines
1972 ((looking-at "[ \t]*#")
1973 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1974 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1975 (setq last-pos (point)))
1976
1977 ;; else if line is a block line and EXTEND given, suck up
1978 ;; the whole structure
1979 ((and extend
1980 (setq first-symbol (py-suck-up-first-keyword) )
1981 (assq first-symbol followers))
1982 (while (and
1983 (or (py-goto-beyond-block) t) ; side effect
1984 (forward-line -1) ; side effect
1985 (setq last-pos (point)) ; side effect
1986 (py-goto-statement-below)
1987 (= (current-indentation) initial-indent)
1988 (setq next-symbol (py-suck-up-first-keyword))
1989 (memq next-symbol (cdr (assq first-symbol followers))))
1990 (setq first-symbol next-symbol)))
1991
1992 ;; else if line *opens* a block, search for next stmt indented <=
1993 ((py-statement-opens-block-p)
1994 (while (and
1995 (setq last-pos (point)) ; always true -- side effect
1996 (py-goto-statement-below)
1997 (> (current-indentation) initial-indent))
1998 nil))
1999
2000 ;; else plain code line; stop at next blank line, or stmt or
2001 ;; indenting comment line indented <
2002 (t
2003 (while (and
2004 (setq last-pos (point)) ; always true -- side effect
2005 (or (py-goto-beyond-final-line) t)
2006 (not (looking-at "[ \t]*$")) ; stop at blank line
2007 (or
2008 (>= (current-indentation) initial-indent)
2009 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2010 nil)))
2011
2012 ;; skip to end of last stmt
2013 (goto-char last-pos)
2014 (py-goto-beyond-final-line)
2015
2016 ;; set mark & display
2017 (if just-move
2018 () ; just return
2019 (push-mark (point) 'no-msg)
2020 (forward-line -1)
2021 (message "Mark set after: %s" (py-suck-up-leading-text))
2022 (goto-char initial-pos))))
2023
Barry Warsaw2518c671997-11-05 00:51:08 +00002024(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025 "Set region to body of def (or class, with prefix arg) enclosing point.
2026Pushes the current mark, then point, on the mark ring (all language
2027modes do this, but although it's handy it's never documented ...).
2028
2029In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2031`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002032
2033And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002034Turned out that was more confusing than useful: the `goto start' and
2035`goto end' commands are usually used to search through a file, and
2036people expect them to act a lot like `search backward' and `search
2037forward' string-search commands. But because Python `def' and `class'
2038can nest to arbitrary levels, finding the smallest def containing
2039point cannot be done via a simple backward search: the def containing
2040point may not be the closest preceding def, or even the closest
2041preceding def that's indented less. The fancy algorithm required is
2042appropriate for the usual uses of this `mark' command, but not for the
2043`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002044
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045So the def marked by this command may not be the one either of the
2046`goto' commands find: If point is on a blank or non-indenting comment
2047line, moves back to start of the closest preceding code statement or
2048indenting comment line. If this is a `def' statement, that's the def
2049we use. Else searches for the smallest enclosing `def' block and uses
2050that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002051
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002052When an enclosing def is found: The mark is left immediately beyond
2053the last line of the def block. Point is left at the start of the
2054def, except that: if the def is preceded by a number of comment lines
2055followed by (at most) one optional blank line, point is left at the
2056start of the comments; else if the def is preceded by a blank line,
2057point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002058
2059The intent is to mark the containing def/class and its associated
2060documentation, to make moving and duplicating functions and classes
2061pleasant."
2062 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002063 (let ((start (point))
2064 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002065 (push-mark start)
2066 (if (not (py-go-up-tree-to-keyword which))
2067 (progn (goto-char start)
2068 (error "Enclosing %s not found" which))
2069 ;; else enclosing def/class found
2070 (setq start (point))
2071 (py-goto-beyond-block)
2072 (push-mark (point))
2073 (goto-char start)
2074 (if (zerop (forward-line -1)) ; if there is a preceding line
2075 (progn
2076 (if (looking-at "[ \t]*$") ; it's blank
2077 (setq start (point)) ; so reset start point
2078 (goto-char start)) ; else try again
2079 (if (zerop (forward-line -1))
2080 (if (looking-at "[ \t]*#") ; a comment
2081 ;; look back for non-comment line
2082 ;; tricky: note that the regexp matches a blank
2083 ;; line, cuz \n is in the 2nd character class
2084 (and
2085 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2086 (forward-line 1))
2087 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002088 (goto-char start)))))))
2089 (exchange-point-and-mark)
2090 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002091
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002092;; ripped from cc-mode
2093(defun py-forward-into-nomenclature (&optional arg)
2094 "Move forward to end of a nomenclature section or word.
2095With arg, to it arg times.
2096
2097A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2098 (interactive "p")
2099 (let ((case-fold-search nil))
2100 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002101 (re-search-forward
2102 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2103 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002104 (while (and (< arg 0)
2105 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002106 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002107 (point-min) 0))
2108 (forward-char 1)
2109 (setq arg (1+ arg)))))
2110 (py-keep-region-active))
2111
2112(defun py-backward-into-nomenclature (&optional arg)
2113 "Move backward to beginning of a nomenclature section or word.
2114With optional ARG, move that many times. If ARG is negative, move
2115forward.
2116
2117A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2118 (interactive "p")
2119 (py-forward-into-nomenclature (- arg))
2120 (py-keep-region-active))
2121
2122
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002123
2124;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002125
2126;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002127;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2128;; out of the right places, along with the keys they're on & current
2129;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002130(defun py-dump-help-string (str)
2131 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002132 (let ((locals (buffer-local-variables))
2133 funckind funcname func funcdoc
2134 (start 0) mstart end
2135 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002136 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2137 (setq mstart (match-beginning 0) end (match-end 0)
2138 funckind (substring str (match-beginning 1) (match-end 1))
2139 funcname (substring str (match-beginning 2) (match-end 2))
2140 func (intern funcname))
2141 (princ (substitute-command-keys (substring str start mstart)))
2142 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002143 ((equal funckind "c") ; command
2144 (setq funcdoc (documentation func)
2145 keys (concat
2146 "Key(s): "
2147 (mapconcat 'key-description
2148 (where-is-internal func py-mode-map)
2149 ", "))))
2150 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002151 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002152 keys (if (assq func locals)
2153 (concat
2154 "Local/Global values: "
2155 (prin1-to-string (symbol-value func))
2156 " / "
2157 (prin1-to-string (default-value func)))
2158 (concat
2159 "Value: "
2160 (prin1-to-string (symbol-value func))))))
2161 (t ; unexpected
2162 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002163 (princ (format "\n-> %s:\t%s\t%s\n\n"
2164 (if (equal funckind "c") "Command" "Variable")
2165 funcname keys))
2166 (princ funcdoc)
2167 (terpri)
2168 (setq start end))
2169 (princ (substitute-command-keys (substring str start))))
2170 (print-help-return-message)))
2171
2172(defun py-describe-mode ()
2173 "Dump long form of Python-mode docs."
2174 (interactive)
2175 (py-dump-help-string "Major mode for editing Python files.
2176Knows about Python indentation, tokens, comments and continuation lines.
2177Paragraphs are separated by blank lines only.
2178
2179Major sections below begin with the string `@'; specific function and
2180variable docs begin with `->'.
2181
2182@EXECUTING PYTHON CODE
2183
2184\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2185\\[py-execute-region]\tsends the current region
2186\\[py-shell]\tstarts a Python interpreter window; this will be used by
2187\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2188%c:py-execute-buffer
2189%c:py-execute-region
2190%c:py-shell
2191
2192@VARIABLES
2193
2194py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002195py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002196
2197py-python-command\tshell command to invoke Python interpreter
2198py-scroll-process-buffer\talways scroll Python process buffer
2199py-temp-directory\tdirectory used for temp files (if needed)
2200
2201py-beep-if-tab-change\tring the bell if tab-width is changed
2202%v:py-indent-offset
2203%v:py-block-comment-prefix
2204%v:py-python-command
2205%v:py-scroll-process-buffer
2206%v:py-temp-directory
2207%v:py-beep-if-tab-change
2208
2209@KINDS OF LINES
2210
2211Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212preceding line ends with a backslash that's not part of a comment, or
2213the paren/bracket/brace nesting level at the start of the line is
2214non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002215
2216An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002217possibly blanks or tabs), a `comment line' (leftmost non-blank
2218character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002219
2220Comment Lines
2221
2222Although all comment lines are treated alike by Python, Python mode
2223recognizes two kinds that act differently with respect to indentation.
2224
2225An `indenting comment line' is a comment line with a blank, tab or
2226nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002227treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002228indenting comment line will be indented like the comment line. All
2229other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002230following the initial `#') are `non-indenting comment lines', and
2231their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002232
2233Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002234whenever possible. Non-indenting comment lines are useful in cases
2235like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002236
2237\ta = b # a very wordy single-line comment that ends up being
2238\t #... continued onto another line
2239
2240\tif a == b:
2241##\t\tprint 'panic!' # old code we've `commented out'
2242\t\treturn a
2243
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002244Since the `#...' and `##' comment lines have a non-whitespace
2245character following the initial `#', Python mode ignores them when
2246computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002247
2248Continuation Lines and Statements
2249
2250The Python-mode commands generally work on statements instead of on
2251individual lines, where a `statement' is a comment or blank line, or a
2252code line and all of its following continuation lines (if any)
2253considered as a single logical unit. The commands in this mode
2254generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002255statement containing point, even if point happens to be in the middle
2256of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002257
2258
2259@INDENTATION
2260
2261Primarily for entering new code:
2262\t\\[indent-for-tab-command]\t indent line appropriately
2263\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002264\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002265
2266Primarily for reindenting existing code:
2267\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2268\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2269
2270\t\\[py-indent-region]\t reindent region to match its context
2271\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2272\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2273
2274Unlike most programming languages, Python uses indentation, and only
2275indentation, to specify block structure. Hence the indentation supplied
2276automatically by Python-mode is just an educated guess: only you know
2277the block structure you intend, so only you can supply correct
2278indentation.
2279
2280The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2281the indentation of preceding statements. E.g., assuming
2282py-indent-offset is 4, after you enter
2283\tif a > 0: \\[py-newline-and-indent]
2284the cursor will be moved to the position of the `_' (_ is not a
2285character in the file, it's just used here to indicate the location of
2286the cursor):
2287\tif a > 0:
2288\t _
2289If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2290to
2291\tif a > 0:
2292\t c = d
2293\t _
2294Python-mode cannot know whether that's what you intended, or whether
2295\tif a > 0:
2296\t c = d
2297\t_
2298was your intent. In general, Python-mode either reproduces the
2299indentation of the (closest code or indenting-comment) preceding
2300statement, or adds an extra py-indent-offset blanks if the preceding
2301statement has `:' as its last significant (non-whitespace and non-
2302comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002303\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304
2305Continuation lines are given extra indentation. If you don't like the
2306suggested indentation, change it to something you do like, and Python-
2307mode will strive to indent later lines of the statement in the same way.
2308
2309If a line is a continuation line by virtue of being in an unclosed
2310paren/bracket/brace structure (`list', for short), the suggested
2311indentation depends on whether the current line contains the first item
2312in the list. If it does, it's indented py-indent-offset columns beyond
2313the indentation of the line containing the open bracket. If you don't
2314like that, change it by hand. The remaining items in the list will mimic
2315whatever indentation you give to the first item.
2316
2317If a line is a continuation line because the line preceding it ends with
2318a backslash, the third and following lines of the statement inherit their
2319indentation from the line preceding them. The indentation of the second
2320line in the statement depends on the form of the first (base) line: if
2321the base line is an assignment statement with anything more interesting
2322than the backslash following the leftmost assigning `=', the second line
2323is indented two columns beyond that `='. Else it's indented to two
2324columns beyond the leftmost solid chunk of non-whitespace characters on
2325the base line.
2326
2327Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2328repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2329structure you intend.
2330%c:indent-for-tab-command
2331%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002332%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333
2334
2335The next function may be handy when editing code you didn't write:
2336%c:py-guess-indent-offset
2337
2338
2339The remaining `indent' functions apply to a region of Python code. They
2340assume the block structure (equals indentation, in Python) of the region
2341is correct, and alter the indentation in various ways while preserving
2342the block structure:
2343%c:py-indent-region
2344%c:py-shift-region-left
2345%c:py-shift-region-right
2346
2347@MARKING & MANIPULATING REGIONS OF CODE
2348
2349\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002350\\[py-mark-def-or-class]\t mark smallest enclosing def
2351\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002352\\[comment-region]\t comment out region of code
2353\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002354%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002355%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002356%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002357
2358@MOVING POINT
2359
2360\\[py-previous-statement]\t move to statement preceding point
2361\\[py-next-statement]\t move to statement following point
2362\\[py-goto-block-up]\t move up to start of current block
2363\\[beginning-of-python-def-or-class]\t move to start of def
2364\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2365\\[end-of-python-def-or-class]\t move to end of def
2366\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2367
2368The first two move to one statement beyond the statement that contains
2369point. A numeric prefix argument tells them to move that many
2370statements instead. Blank lines, comment lines, and continuation lines
2371do not count as `statements' for these commands. So, e.g., you can go
2372to the first code statement in a file by entering
2373\t\\[beginning-of-buffer]\t to move to the top of the file
2374\t\\[py-next-statement]\t to skip over initial comments and blank lines
2375Or do `\\[py-previous-statement]' with a huge prefix argument.
2376%c:py-previous-statement
2377%c:py-next-statement
2378%c:py-goto-block-up
2379%c:beginning-of-python-def-or-class
2380%c:end-of-python-def-or-class
2381
2382@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2383
2384`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2385
2386`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2387overall class and def structure of a module.
2388
2389`\\[back-to-indentation]' moves point to a line's first non-blank character.
2390
2391`\\[indent-relative]' is handy for creating odd indentation.
2392
2393@OTHER EMACS HINTS
2394
2395If you don't like the default value of a variable, change its value to
2396whatever you do like by putting a `setq' line in your .emacs file.
2397E.g., to set the indentation increment to 4, put this line in your
2398.emacs:
2399\t(setq py-indent-offset 4)
2400To see the value of a variable, do `\\[describe-variable]' and enter the variable
2401name at the prompt.
2402
2403When entering a key sequence like `C-c C-n', it is not necessary to
2404release the CONTROL key after doing the `C-c' part -- it suffices to
2405press the CONTROL key, press and release `c' (while still holding down
2406CONTROL), press and release `n' (while still holding down CONTROL), &
2407then release CONTROL.
2408
2409Entering Python mode calls with no arguments the value of the variable
2410`python-mode-hook', if that value exists and is not nil; for backward
2411compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2412the Elisp manual for details.
2413
2414Obscure: When python-mode is first loaded, it looks for all bindings
2415to newline-and-indent in the global keymap, and shadows them with
2416local bindings to py-newline-and-indent."))
2417
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002418
2419;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420(defvar py-parse-state-re
2421 (concat
2422 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2423 "\\|"
2424 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002425
Barry Warsaw7ae77681994-12-12 20:38:05 +00002426;; returns the parse state at point (see parse-partial-sexp docs)
2427(defun py-parse-state ()
2428 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002429 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002430 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002431 (while (not done)
2432 ;; back up to the first preceding line (if any; else start of
2433 ;; buffer) that begins with a popular Python keyword, or a
2434 ;; non- whitespace and non-comment character. These are good
2435 ;; places to start parsing to see whether where we started is
2436 ;; at a non-zero nesting level. It may be slow for people who
2437 ;; write huge code blocks or huge lists ... tough beans.
2438 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002439 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002440 (beginning-of-line)
2441 (save-excursion
2442 (setq pps (parse-partial-sexp (point) here)))
2443 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002444 (setq done (or (zerop ci)
2445 (not (nth 3 pps))
2446 (bobp)))
2447 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002448 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002449
2450;; if point is at a non-zero nesting level, returns the number of the
2451;; character that opens the smallest enclosing unclosed list; else
2452;; returns nil.
2453(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002454 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002455 (if (zerop (car status))
2456 nil ; not in a nest
2457 (car (cdr status))))) ; char# of open bracket
2458
2459;; t iff preceding line ends with backslash that's not in a comment
2460(defun py-backslash-continuation-line-p ()
2461 (save-excursion
2462 (beginning-of-line)
2463 (and
2464 ;; use a cheap test first to avoid the regexp if possible
2465 ;; use 'eq' because char-after may return nil
2466 (eq (char-after (- (point) 2)) ?\\ )
2467 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002468 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002469 (looking-at py-continued-re))))
2470
2471;; t iff current line is a continuation line
2472(defun py-continuation-line-p ()
2473 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002474 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002475 (or (py-backslash-continuation-line-p)
2476 (py-nesting-level))))
2477
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002478;; go to initial line of current statement; usually this is the line
2479;; we're on, but if we're on the 2nd or following lines of a
2480;; continuation block, we need to go up to the first line of the
2481;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002482;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002483;; Tricky: We want to avoid quadratic-time behavior for long continued
2484;; blocks, whether of the backslash or open-bracket varieties, or a
2485;; mix of the two. The following manages to do that in the usual
2486;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002487(defun py-goto-initial-line ()
2488 (let ( open-bracket-pos )
2489 (while (py-continuation-line-p)
2490 (beginning-of-line)
2491 (if (py-backslash-continuation-line-p)
2492 (while (py-backslash-continuation-line-p)
2493 (forward-line -1))
2494 ;; else zip out of nested brackets/braces/parens
2495 (while (setq open-bracket-pos (py-nesting-level))
2496 (goto-char open-bracket-pos)))))
2497 (beginning-of-line))
2498
2499;; go to point right beyond final line of current statement; usually
2500;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002501;; statement we need to skip over the continuation lines. Tricky:
2502;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002503(defun py-goto-beyond-final-line ()
2504 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002505 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002506 (while (and (py-continuation-line-p)
2507 (not (eobp)))
2508 ;; skip over the backslash flavor
2509 (while (and (py-backslash-continuation-line-p)
2510 (not (eobp)))
2511 (forward-line 1))
2512 ;; if in nest, zip to the end of the nest
2513 (setq state (py-parse-state))
2514 (if (and (not (zerop (car state)))
2515 (not (eobp)))
2516 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002517 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002518 (forward-line 1))))))
2519
2520;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002521;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002522(defun py-statement-opens-block-p ()
2523 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002524 (let ((start (point))
2525 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2526 (searching t)
2527 (answer nil)
2528 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002529 (goto-char start)
2530 (while searching
2531 ;; look for a colon with nothing after it except whitespace, and
2532 ;; maybe a comment
2533 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2534 finish t)
2535 (if (eq (point) finish) ; note: no `else' clause; just
2536 ; keep searching if we're not at
2537 ; the end yet
2538 ;; sure looks like it opens a block -- but it might
2539 ;; be in a comment
2540 (progn
2541 (setq searching nil) ; search is done either way
2542 (setq state (parse-partial-sexp start
2543 (match-beginning 0)))
2544 (setq answer (not (nth 4 state)))))
2545 ;; search failed: couldn't find another interesting colon
2546 (setq searching nil)))
2547 answer)))
2548
Barry Warsawf831d811996-07-31 20:42:59 +00002549(defun py-statement-closes-block-p ()
2550 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002551 ;; starts with `return', `raise', `break', `continue', and `pass'.
2552 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002553 (let ((here (point)))
2554 (back-to-indentation)
2555 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002556 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002557 (goto-char here))))
2558
Barry Warsaw7ae77681994-12-12 20:38:05 +00002559;; go to point right beyond final line of block begun by the current
2560;; line. This is the same as where py-goto-beyond-final-line goes
2561;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002562;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002563(defun py-goto-beyond-block ()
2564 (if (py-statement-opens-block-p)
2565 (py-mark-block nil 'just-move)
2566 (py-goto-beyond-final-line)))
2567
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002568;; go to start of first statement (not blank or comment or
2569;; continuation line) at or preceding point. returns t if there is
2570;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002571(defun py-goto-statement-at-or-above ()
2572 (py-goto-initial-line)
2573 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002574 ;; skip back over blank & comment lines
2575 ;; note: will skip a blank or comment line that happens to be
2576 ;; a continuation line too
2577 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2578 (progn (py-goto-initial-line) t)
2579 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002580 t))
2581
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002582;; go to start of first statement (not blank or comment or
2583;; continuation line) following the statement containing point returns
2584;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002585(defun py-goto-statement-below ()
2586 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002587 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002588 (py-goto-beyond-final-line)
2589 (while (and
2590 (looking-at py-blank-or-comment-re)
2591 (not (eobp)))
2592 (forward-line 1))
2593 (if (eobp)
2594 (progn (goto-char start) nil)
2595 t)))
2596
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002597;; go to start of statement, at or preceding point, starting with
2598;; keyword KEY. Skips blank lines and non-indenting comments upward
2599;; first. If that statement starts with KEY, done, else go back to
2600;; first enclosing block starting with KEY. If successful, leaves
2601;; point at the start of the KEY line & returns t. Else leaves point
2602;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002603(defun py-go-up-tree-to-keyword (key)
2604 ;; skip blanks and non-indenting #
2605 (py-goto-initial-line)
2606 (while (and
2607 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2608 (zerop (forward-line -1))) ; go back
2609 nil)
2610 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002611 (let* ((re (concat "[ \t]*" key "\\b"))
2612 (case-fold-search nil) ; let* so looking-at sees this
2613 (found (looking-at re))
2614 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002615 (while (not (or found dead))
2616 (condition-case nil ; in case no enclosing block
2617 (py-goto-block-up 'no-mark)
2618 (error (setq dead t)))
2619 (or dead (setq found (looking-at re))))
2620 (beginning-of-line)
2621 found))
2622
2623;; return string in buffer from start of indentation to end of line;
2624;; prefix "..." if leading whitespace was skipped
2625(defun py-suck-up-leading-text ()
2626 (save-excursion
2627 (back-to-indentation)
2628 (concat
2629 (if (bolp) "" "...")
2630 (buffer-substring (point) (progn (end-of-line) (point))))))
2631
2632;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2633;; as a Lisp symbol; return nil if none
2634(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002635 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002636 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2637 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2638 nil)))
2639
Barry Warsawb3e81d51996-09-04 15:12:42 +00002640(defun py-current-defun ()
2641 ;; tell add-log.el how to find the current function/method/variable
2642 (save-excursion
2643 (if (re-search-backward py-defun-start-re nil t)
2644 (or (match-string 3)
2645 (let ((method (match-string 2)))
2646 (if (and (not (zerop (length (match-string 1))))
2647 (re-search-backward py-class-start-re nil t))
2648 (concat (match-string 1) "." method)
2649 method)))
2650 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002651
2652
Barry Warsawfec75d61995-07-05 23:26:15 +00002653(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002654 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002655
Barry Warsaw850437a1995-03-08 21:50:28 +00002656(defun py-version ()
2657 "Echo the current version of `python-mode' in the minibuffer."
2658 (interactive)
2659 (message "Using `python-mode' version %s" py-version)
2660 (py-keep-region-active))
2661
2662;; only works under Emacs 19
2663;(eval-when-compile
2664; (require 'reporter))
2665
2666(defun py-submit-bug-report (enhancement-p)
2667 "Submit via mail a bug report on `python-mode'.
2668With \\[universal-argument] just submit an enhancement request."
2669 (interactive
2670 (list (not (y-or-n-p
2671 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002672 (let ((reporter-prompt-for-summary-p (if enhancement-p
2673 "(Very) brief summary: "
2674 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002675 (require 'reporter)
2676 (reporter-submit-bug-report
2677 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002678 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002679 ;; varlist
2680 (if enhancement-p nil
2681 '(py-python-command
2682 py-indent-offset
2683 py-block-comment-prefix
2684 py-scroll-process-buffer
2685 py-temp-directory
2686 py-beep-if-tab-change))
2687 nil ;pre-hooks
2688 nil ;post-hooks
2689 "Dear Barry,") ;salutation
2690 (if enhancement-p nil
2691 (set-mark (point))
2692 (insert
2693"Please replace this text with a sufficiently large code sample\n\
2694and an exact recipe so that I can reproduce your problem. Failure\n\
2695to do so may mean a greater delay in fixing your bug.\n\n")
2696 (exchange-point-and-mark)
2697 (py-keep-region-active))))
2698
2699
Barry Warsaw47384781997-11-26 05:27:45 +00002700(defun py-kill-emacs-hook ()
2701 (mapcar #'(lambda (filename)
2702 (py-safe (delete-file filename)))
2703 py-file-queue))
2704
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002705;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002706(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002707
2708
2709
2710(provide 'python-mode)
2711;;; python-mode.el ends here