blob: f87857652b50028bcc9092a490a7f060ce9ddf2f [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 Warsawaffc0ca1997-11-03 16:59:38 +000033;; python-mode.el is currently distributed with XEmacs 19 and XEmacs
34;; 20. Since this file is not GPL'd it is not distributed with Emacs,
Barry Warsawa97a3f31997-11-04 18:47:06 +000035;; but it is compatible with 19.34 and the current 20 series Emacsen.
36;; By default, in XEmacs when you visit a .py file, it is put in
37;; Python mode. In Emacs, you need to add the following to your
38;; .emacs file (you don't need this for XEmacs):
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000040;; (autoload 'python-mode "python-mode" "Python editing mode." t)
41;; (setq auto-mode-alist
42;; (cons '("\\.py$" . python-mode) auto-mode-alist))
43;; (setq interpreter-mode-alist
44;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000045;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000046;; Assuming python-mode.el is on your load-path, it will be invoked
47;; when you visit a .py file, or a file with a first line that looks
48;; like:
49;;
50;; #! /usr/bin/env python
51
Barry Warsaw44b72201996-07-05 20:11:35 +000052;; If you want font-lock support for Python source code (a.k.a. syntax
53;; coloring, highlighting), add this to your .emacs file:
54;;
55;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000056;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000057;; Again, this should not be necessary for XEmacs, since it Just Works.
Barry Warsaw7ae77681994-12-12 20:38:05 +000058
Barry Warsawaffc0ca1997-11-03 16:59:38 +000059;; To submit bug reports, use C-c C-b. Please include a complete, but
60;; concise code sample and a recipe for reproducing the bug. Send
61;; suggestions and other comments to python-mode@python.org.
62
63;; When in a Python mode buffer, do a C-h m for more help. It's
64;; doubtful that a texinfo manual would be very useful.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000065
Barry Warsaw7b0f5681995-03-08 21:33:04 +000066;; Here's a brief to do list:
67;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000068;; - Better integration with gud-mode for debugging.
69;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000070;; - possibly force indent-tabs-mode == nil, and add a
71;; write-file-hooks that runs untabify on the whole buffer (to work
72;; around potential tab/space mismatch problems). In practice this
73;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000074;; - have py-execute-region on indented code act as if the region is
75;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000076;; - Add a py-goto-error or some such that would scan an exception in
77;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000078
Barry Warsaw7b0f5681995-03-08 21:33:04 +000079;;; Code:
80
Barry Warsawc72c11c1997-08-09 06:42:08 +000081(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +000082(eval-when-compile
83 (require 'cl))
Barry Warsawc72c11c1997-08-09 06:42:08 +000084
Barry Warsaw7b0f5681995-03-08 21:33:04 +000085
86;; user definable variables
87;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000088
Barry Warsawc72c11c1997-08-09 06:42:08 +000089(defgroup python nil
90 "Support for the Python programming language, <http://www.python.org/>"
91 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000092
Barry Warsawc72c11c1997-08-09 06:42:08 +000093(defcustom py-python-command "python"
94 "*Shell command used to start Python interpreter."
95 :type 'string
96 :group 'python)
97
98(defcustom py-indent-offset 4
99 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000100Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000101when you're editing someone else's Python code."
102 :type 'integer
103 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000104
Barry Warsawc72c11c1997-08-09 06:42:08 +0000105(defcustom py-align-multiline-strings-p t
106 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000107When this flag is non-nil, continuation lines are lined up under the
108preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000109lines are aligned to column zero."
110 :type '(choice (const :tag "Align under preceding line" t)
111 (const :tag "Align to column zero" nil))
112 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000113
Barry Warsawc72c11c1997-08-09 06:42:08 +0000114(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000115 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000116This should follow the convention for non-indenting comment lines so
117that the indentation commands won't get confused (i.e., the string
118should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000119`...' is arbitrary)."
120 :type 'string
121 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000122
Barry Warsawc72c11c1997-08-09 06:42:08 +0000123(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000124 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000125
Barry Warsaw6d627751996-03-06 18:41:38 +0000126When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000127if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000128
129When t, lines that begin with a single `#' are a hint to subsequent
130line indentation. If the previous line is such a comment line (as
131opposed to one that starts with `py-block-comment-prefix'), then it's
132indentation is used as a hint for this line's indentation. Lines that
133begin with `py-block-comment-prefix' are ignored for indentation
134purposes.
135
136When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000137indentation hints, unless the comment character is in column zero."
138 :type '(choice
139 (const :tag "Skip all comment lines (fast)" nil)
140 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000141 (const :tag "Single # `sets' indentation except at column zero"
142 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000143 )
144 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000145
Barry Warsawc72c11c1997-08-09 06:42:08 +0000146(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000147 "*Scroll Python process buffer as output arrives.
148If nil, the Python process buffer acts, with respect to scrolling, like
149Shell-mode buffers normally act. This is surprisingly complicated and
150so won't be explained here; in fact, you can't get the whole story
151without studying the Emacs C code.
152
153If non-nil, the behavior is different in two respects (which are
154slightly inaccurate in the interest of brevity):
155
156 - If the buffer is in a window, and you left point at its end, the
157 window will scroll as new output arrives, and point will move to the
158 buffer's end, even if the window is not the selected window (that
159 being the one the cursor is in). The usual behavior for shell-mode
160 windows is not to scroll, and to leave point where it was, if the
161 buffer is in a window other than the selected window.
162
163 - If the buffer is not visible in any window, and you left point at
164 its end, the buffer will be popped into a window as soon as more
165 output arrives. This is handy if you have a long-running
166 computation and don't want to tie up screen area waiting for the
167 output. The usual behavior for a shell-mode buffer is to stay
168 invisible until you explicitly visit it.
169
170Note the `and if you left point at its end' clauses in both of the
171above: you can `turn off' the special behaviors while output is in
172progress, by visiting the Python buffer and moving point to anywhere
173besides the end. Then the buffer won't scroll, point will remain where
174you leave it, and if you hide the buffer it will stay hidden until you
175visit it again. You can enable and disable the special behaviors as
176often as you like, while output is in progress, by (respectively) moving
177point to, or away from, the end of the buffer.
178
179Warning: If you expect a large amount of output, you'll probably be
180happier setting this option to nil.
181
182Obscure: `End of buffer' above should really say `at or beyond the
183process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000184told <grin>."
185 :type 'boolean
186 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000187
Barry Warsaw516b6201997-08-09 06:43:20 +0000188(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000189 (let ((ok '(lambda (x)
190 (and x
191 (setq x (expand-file-name x)) ; always true
192 (file-directory-p x)
193 (file-writable-p x)
194 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000195 (or (funcall ok (getenv "TMPDIR"))
196 (funcall ok "/usr/tmp")
197 (funcall ok "/tmp")
198 (funcall ok ".")
199 (error
200 "Couldn't find a usable temp directory -- set py-temp-directory")))
201 "*Directory used for temp files created by a *Python* process.
202By default, the first directory from this list that exists and that you
203can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000204/usr/tmp, /tmp, or the current directory."
205 :type 'string
206 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000207
Barry Warsaw516b6201997-08-09 06:43:20 +0000208(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000209 "*Ring the bell if tab-width is changed.
210If a comment of the form
211
212 \t# vi:set tabsize=<number>:
213
214is found before the first code line when the file is entered, and the
215current value of (the general Emacs variable) `tab-width' does not
216equal <number>, `tab-width' is set to <number>, a message saying so is
217displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000218the Emacs bell is also rung as a warning."
219 :type 'boolean
220 :group 'python)
221
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000222(defcustom py-backspace-function 'backward-delete-char-untabify
223 "*Function called by `py-electric-backspace' when deleting backwards."
224 :type 'function
225 :group 'python)
226
227(defcustom py-delete-function 'delete-char
228 "*Function called by `py-electric-delete' when deleting forwards."
229 :type 'function
230 :group 'python)
231
232
Barry Warsawc72c11c1997-08-09 06:42:08 +0000233
234;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
235;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
236
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000237(defconst py-emacs-features
238 (let (features)
239 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
240 ;; the same string.
241 (let ((tmp1 (make-temp-name ""))
242 (tmp2 (make-temp-name "")))
243 (if (string-equal tmp1 tmp2)
244 (push 'broken-temp-names features)))
245 ;; return the features
246 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000247 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000248There are many flavors of Emacs out there, with different levels of
249support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250
Barry Warsawfb07f401997-02-24 03:37:22 +0000251(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000252 (let ((kw1 (mapconcat 'identity
253 '("and" "assert" "break" "class"
254 "continue" "def" "del" "elif"
255 "else" "except" "exec" "for"
256 "from" "global" "if" "import"
257 "in" "is" "lambda" "not"
258 "or" "pass" "print" "raise"
259 "return" "while"
260 )
261 "\\|"))
262 (kw2 (mapconcat 'identity
263 '("else:" "except:" "finally:" "try:")
264 "\\|"))
265 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000266 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000267 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000268 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
269 ;; block introducing keywords with immediately following colons.
270 ;; Yes "except" is in both lists.
271 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000272 ;; classes
273 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
274 1 font-lock-type-face)
275 ;; functions
276 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
277 1 font-lock-function-name-face)
278 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000279 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000280(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
281
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000282
Barry Warsaw81437461996-08-01 19:48:02 +0000283(defvar imenu-example--python-show-method-args-p nil
284 "*Controls echoing of arguments of functions & methods in the imenu buffer.
285When non-nil, arguments are printed.")
286
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000287(make-variable-buffer-local 'py-indent-offset)
288
Barry Warsawe467bfb1997-11-26 05:40:58 +0000289;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000290(defvar py-file-queue nil
291 "Queue of Python temp files awaiting execution.
292Currently-active file is at the head of the list.")
293
Barry Warsawc72c11c1997-08-09 06:42:08 +0000294
295;; Constants
296
297;; Regexp matching a Python string literal
298(defconst py-stringlit-re
299 (concat
300 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
301 "\\|" ; or
302 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
303
304;; Regexp matching Python lines that are continued via backslash.
305;; This is tricky because a trailing backslash does not mean
306;; continuation if it's in a comment
307(defconst py-continued-re
308 (concat
309 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
310 "\\\\$"))
311
312;; Regexp matching blank or comment lines.
313(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
314
315;; Regexp matching clauses to be outdented one level.
316(defconst py-outdent-re
317 (concat "\\(" (mapconcat 'identity
318 '("else:"
319 "except\\(\\s +.*\\)?:"
320 "finally:"
321 "elif\\s +.*:")
322 "\\|")
323 "\\)"))
324
325
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000326;; Regexp matching keywords which typically close a block
327(defconst py-block-closing-keywords-re
328 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
329
Barry Warsawc72c11c1997-08-09 06:42:08 +0000330;; Regexp matching lines to not outdent after.
331(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000332 (concat
333 "\\("
334 (mapconcat 'identity
335 (list "try:"
336 "except\\(\\s +.*\\)?:"
337 "while\\s +.*:"
338 "for\\s +.*:"
339 "if\\s +.*:"
340 "elif\\s +.*:"
341 (concat py-block-closing-keywords-re "[ \t\n]")
342 )
343 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000344 "\\)"))
345
346;; Regexp matching a function, method or variable assignment. If you
347;; change this, you probably have to change `py-current-defun' as
348;; well. This is only used by `py-current-defun' to find the name for
349;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000350(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000351 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
352
353;; Regexp for finding a class name. If you change this, you probably
354;; have to change `py-current-defun' as well. This is only used by
355;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000356(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
357
358;; Regexp that describes tracebacks
359(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000360 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000361
362
363
364;; Utilities
365
366(defmacro py-safe (&rest body)
367 ;; safely execute BODY, return nil if an error occurred
368 (` (condition-case nil
369 (progn (,@ body))
370 (error nil))))
371
372(defsubst py-keep-region-active ()
373 ;; Do whatever is necessary to keep the region active in XEmacs.
374 ;; Ignore byte-compiler warnings you might see. Also note that
375 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
376 ;; to take explicit action.
377 (and (boundp 'zmacs-region-stays)
378 (setq zmacs-region-stays t)))
379
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000380(defsubst py-point (position)
381 ;; Returns the value of point at certain commonly referenced POSITIONs.
382 ;; POSITION can be one of the following symbols:
383 ;;
384 ;; bol -- beginning of line
385 ;; eol -- end of line
386 ;; bod -- beginning of defun
387 ;; boi -- back to indentation
388 ;;
389 ;; This function does not modify point or mark.
390 (let ((here (point)))
391 (cond
392 ((eq position 'bol) (beginning-of-line))
393 ((eq position 'eol) (end-of-line))
394 ((eq position 'bod) (beginning-of-python-def-or-class))
395 ((eq position 'bob) (beginning-of-buffer))
396 ((eq position 'eob) (end-of-buffer))
397 ((eq position 'boi) (back-to-indentation))
398 (t (error "unknown buffer position requested: %s" position))
399 )
400 (prog1
401 (point)
402 (goto-char here))))
403
404(defsubst py-highlight-line (from to file line)
405 (cond
406 ((fboundp 'make-extent)
407 ;; XEmacs
408 (let ((e (make-extent from to)))
409 (set-extent-property e 'mouse-face 'highlight)
410 (set-extent-property e 'py-exc-info (cons file line))
411 (set-extent-property e 'keymap py-mode-output-map)))
412 (t
413 ;; Emacs -- Please port this!
414 )
415 ))
416
Barry Warsawc72c11c1997-08-09 06:42:08 +0000417
418;; Major mode boilerplate
419
Barry Warsaw7ae77681994-12-12 20:38:05 +0000420;; define a mode-specific abbrev table for those who use such things
421(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000422 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000423(define-abbrev-table 'python-mode-abbrev-table nil)
424
Barry Warsaw7ae77681994-12-12 20:38:05 +0000425(defvar python-mode-hook nil
426 "*Hook called by `python-mode'.")
427
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000428;; in previous version of python-mode.el, the hook was incorrectly
429;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000430(and (fboundp 'make-obsolete-variable)
431 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
432
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000433(defvar py-mode-map ()
434 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000435(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000436 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000437 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000438 ;; electric keys
439 (define-key py-mode-map ":" 'py-electric-colon)
440 ;; indentation level modifiers
441 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
442 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
443 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
444 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
445 ;; subprocess commands
446 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
447 (define-key py-mode-map "\C-c|" 'py-execute-region)
448 (define-key py-mode-map "\C-c!" 'py-shell)
449 ;; Caution! Enter here at your own risk. We are trying to support
450 ;; several behaviors and it gets disgusting. :-( This logic ripped
451 ;; largely from CC Mode.
452 ;;
453 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
454 ;; backwards deletion behavior to DEL, which both Delete and
455 ;; Backspace get translated to. There's no way to separate this
456 ;; behavior in a clean way, so deal with it! Besides, it's been
457 ;; this way since the dawn of time.
458 (if (not (boundp 'delete-key-deletes-forward))
459 (define-key py-mode-map "\177" 'py-electric-backspace)
460 ;; However, XEmacs 20 actually achieved enlightenment. It is
461 ;; possible to sanely define both backward and forward deletion
462 ;; behavior under X separately (TTYs are forever beyond hope, but
463 ;; who cares? XEmacs 20 does the right thing with these too).
464 (define-key py-mode-map [delete] 'py-electric-delete)
465 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000466 ;; Separate M-BS from C-M-h. The former should remain
467 ;; backward-kill-word.
468 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000469 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000470 ;; Miscellaneous
471 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
472 (define-key py-mode-map "\C-c\t" 'py-indent-region)
473 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
474 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
475 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000476 (define-key py-mode-map "\C-c#" 'py-comment-region)
477 (define-key py-mode-map "\C-c?" 'py-describe-mode)
478 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
479 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
480 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000481 (define-key py-mode-map "\C-c-" 'py-up-exception)
482 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000483 ;; information
484 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
485 (define-key py-mode-map "\C-c\C-v" 'py-version)
486 ;; py-newline-and-indent mappings
487 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000488 ;; shadow global bindings for newline-and-indent w/ the py- version.
489 ;; BAW - this is extremely bad form, but I'm not going to change it
490 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000491 (mapcar #'(lambda (key)
492 (define-key py-mode-map key 'py-newline-and-indent))
493 (where-is-internal 'newline-and-indent))
494 )
495
496(defvar py-mode-output-map nil
497 "Keymap used in *Python Output* buffers*")
498(if py-mode-output-map
499 nil
500 (setq py-mode-output-map (make-sparse-keymap))
501 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
502 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
503 ;; TBD: Disable all self-inserting keys. This is bogus, we should
504 ;; really implement this as *Python Output* buffer being read-only
505 (mapcar #' (lambda (key)
506 (define-key py-mode-output-map key
507 #'(lambda () (interactive) (beep))))
508 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000509 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000510
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000511(defvar py-mode-syntax-table nil
512 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000513(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000514 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000515 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000516 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
517 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
518 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
519 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
520 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
521 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
522 ;; Add operator symbols misassigned in the std table
523 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
524 (modify-syntax-entry ?\% "." py-mode-syntax-table)
525 (modify-syntax-entry ?\& "." py-mode-syntax-table)
526 (modify-syntax-entry ?\* "." py-mode-syntax-table)
527 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
528 (modify-syntax-entry ?\- "." py-mode-syntax-table)
529 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
530 (modify-syntax-entry ?\< "." py-mode-syntax-table)
531 (modify-syntax-entry ?\= "." py-mode-syntax-table)
532 (modify-syntax-entry ?\> "." py-mode-syntax-table)
533 (modify-syntax-entry ?\| "." py-mode-syntax-table)
534 ;; For historical reasons, underscore is word class instead of
535 ;; symbol class. GNU conventions say it should be symbol class, but
536 ;; there's a natural conflict between what major mode authors want
537 ;; and what users expect from `forward-word' and `backward-word'.
538 ;; Guido and I have hashed this out and have decided to keep
539 ;; underscore in word class. If you're tempted to change it, try
540 ;; binding M-f and M-b to py-forward-into-nomenclature and
541 ;; py-backward-into-nomenclature instead.
542 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
543 ;; Both single quote and double quote are string delimiters
544 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
545 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
546 ;; backquote is open and close paren
547 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
548 ;; comment delimiters
549 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
550 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
551 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000552
Barry Warsawb3e81d51996-09-04 15:12:42 +0000553
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000554
Barry Warsaw42f707f1996-07-29 21:05:05 +0000555;; Menu definitions, only relevent if you have the easymenu.el package
556;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000557(defvar py-menu nil
558 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000559This menu will get created automatically if you have the `easymenu'
560package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000561
Barry Warsawc72c11c1997-08-09 06:42:08 +0000562(and (py-safe (require 'easymenu) t)
563 (easy-menu-define
564 py-menu py-mode-map "Python Mode menu"
565 '("Python"
566 ["Comment Out Region" py-comment-region (mark)]
567 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
568 "-"
569 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000570 ["Mark current def" py-mark-def-or-class t]
571 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000572 "-"
573 ["Shift region left" py-shift-region-left (mark)]
574 ["Shift region right" py-shift-region-right (mark)]
575 "-"
576 ["Execute buffer" py-execute-buffer t]
577 ["Execute region" py-execute-region (mark)]
578 ["Start interpreter..." py-shell t]
579 "-"
580 ["Go to start of block" py-goto-block-up t]
581 ["Go to start of class" (beginning-of-python-def-or-class t) t]
582 ["Move to end of class" (end-of-python-def-or-class t) t]
583 ["Move to start of def" beginning-of-python-def-or-class t]
584 ["Move to end of def" end-of-python-def-or-class t]
585 "-"
586 ["Describe mode" py-describe-mode t]
587 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000588
Barry Warsaw81437461996-08-01 19:48:02 +0000589
590
591;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
592(defvar imenu-example--python-class-regexp
593 (concat ; <<classes>>
594 "\\(" ;
595 "^[ \t]*" ; newline and maybe whitespace
596 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
597 ; possibly multiple superclasses
598 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
599 "[ \t]*:" ; and the final :
600 "\\)" ; >>classes<<
601 )
602 "Regexp for Python classes for use with the imenu package."
603 )
604
605(defvar imenu-example--python-method-regexp
606 (concat ; <<methods and functions>>
607 "\\(" ;
608 "^[ \t]*" ; new line and maybe whitespace
609 "\\(def[ \t]+" ; function definitions start with def
610 "\\([a-zA-Z0-9_]+\\)" ; name is here
611 ; function arguments...
612 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
613 "\\)" ; end of def
614 "[ \t]*:" ; and then the :
615 "\\)" ; >>methods and functions<<
616 )
617 "Regexp for Python methods/functions for use with the imenu package."
618 )
619
620(defvar imenu-example--python-method-no-arg-parens '(2 8)
621 "Indicies into groups of the Python regexp for use with imenu.
622
623Using these values will result in smaller imenu lists, as arguments to
624functions are not listed.
625
626See the variable `imenu-example--python-show-method-args-p' for more
627information.")
628
629(defvar imenu-example--python-method-arg-parens '(2 7)
630 "Indicies into groups of the Python regexp for use with imenu.
631Using these values will result in large imenu lists, as arguments to
632functions are listed.
633
634See the variable `imenu-example--python-show-method-args-p' for more
635information.")
636
637;; Note that in this format, this variable can still be used with the
638;; imenu--generic-function. Otherwise, there is no real reason to have
639;; it.
640(defvar imenu-example--generic-python-expression
641 (cons
642 (concat
643 imenu-example--python-class-regexp
644 "\\|" ; or...
645 imenu-example--python-method-regexp
646 )
647 imenu-example--python-method-no-arg-parens)
648 "Generic Python expression which may be used directly with imenu.
649Used by setting the variable `imenu-generic-expression' to this value.
650Also, see the function \\[imenu-example--create-python-index] for a
651better alternative for finding the index.")
652
653;; These next two variables are used when searching for the python
654;; class/definitions. Just saving some time in accessing the
655;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000656(defvar imenu-example--python-generic-regexp nil)
657(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000658
659
660;;;###autoload
661(eval-when-compile
662 ;; Imenu isn't used in XEmacs, so just ignore load errors
663 (condition-case ()
664 (progn
665 (require 'cl)
666 (require 'imenu))
667 (error nil)))
668
669(defun imenu-example--create-python-index ()
670 "Python interface function for imenu package.
671Finds all python classes and functions/methods. Calls function
672\\[imenu-example--create-python-index-engine]. See that function for
673the details of how this works."
674 (setq imenu-example--python-generic-regexp
675 (car imenu-example--generic-python-expression))
676 (setq imenu-example--python-generic-parens
677 (if imenu-example--python-show-method-args-p
678 imenu-example--python-method-arg-parens
679 imenu-example--python-method-no-arg-parens))
680 (goto-char (point-min))
681 (imenu-example--create-python-index-engine nil))
682
683(defun imenu-example--create-python-index-engine (&optional start-indent)
684 "Function for finding imenu definitions in Python.
685
686Finds all definitions (classes, methods, or functions) in a Python
687file for the imenu package.
688
689Returns a possibly nested alist of the form
690
691 (INDEX-NAME . INDEX-POSITION)
692
693The second element of the alist may be an alist, producing a nested
694list as in
695
696 (INDEX-NAME . INDEX-ALIST)
697
698This function should not be called directly, as it calls itself
699recursively and requires some setup. Rather this is the engine for
700the function \\[imenu-example--create-python-index].
701
702It works recursively by looking for all definitions at the current
703indention level. When it finds one, it adds it to the alist. If it
704finds a definition at a greater indentation level, it removes the
705previous definition from the alist. In it's place it adds all
706definitions found at the next indentation level. When it finds a
707definition that is less indented then the current level, it retuns the
708alist it has created thus far.
709
710The optional argument START-INDENT indicates the starting indentation
711at which to continue looking for Python classes, methods, or
712functions. If this is not supplied, the function uses the indentation
713of the first definition found."
714 (let ((index-alist '())
715 (sub-method-alist '())
716 looking-p
717 def-name prev-name
718 cur-indent def-pos
719 (class-paren (first imenu-example--python-generic-parens))
720 (def-paren (second imenu-example--python-generic-parens)))
721 (setq looking-p
722 (re-search-forward imenu-example--python-generic-regexp
723 (point-max) t))
724 (while looking-p
725 (save-excursion
726 ;; used to set def-name to this value but generic-extract-name is
727 ;; new to imenu-1.14. this way it still works with imenu-1.11
728 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
729 (let ((cur-paren (if (match-beginning class-paren)
730 class-paren def-paren)))
731 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000732 (buffer-substring-no-properties (match-beginning cur-paren)
733 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000734 (beginning-of-line)
735 (setq cur-indent (current-indentation)))
736
737 ;; HACK: want to go to the next correct definition location. we
738 ;; explicitly list them here. would be better to have them in a
739 ;; list.
740 (setq def-pos
741 (or (match-beginning class-paren)
742 (match-beginning def-paren)))
743
744 ;; if we don't have a starting indent level, take this one
745 (or start-indent
746 (setq start-indent cur-indent))
747
748 ;; if we don't have class name yet, take this one
749 (or prev-name
750 (setq prev-name def-name))
751
752 ;; what level is the next definition on? must be same, deeper
753 ;; or shallower indentation
754 (cond
755 ;; at the same indent level, add it to the list...
756 ((= start-indent cur-indent)
757
758 ;; if we don't have push, use the following...
759 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
760 (push (cons def-name def-pos) index-alist))
761
762 ;; deeper indented expression, recur...
763 ((< start-indent cur-indent)
764
765 ;; the point is currently on the expression we're supposed to
766 ;; start on, so go back to the last expression. The recursive
767 ;; call will find this place again and add it to the correct
768 ;; list
769 (re-search-backward imenu-example--python-generic-regexp
770 (point-min) 'move)
771 (setq sub-method-alist (imenu-example--create-python-index-engine
772 cur-indent))
773
774 (if sub-method-alist
775 ;; we put the last element on the index-alist on the start
776 ;; of the submethod alist so the user can still get to it.
777 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000778 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000779 (cons save-elmt sub-method-alist))
780 index-alist))))
781
782 ;; found less indented expression, we're done.
783 (t
784 (setq looking-p nil)
785 (re-search-backward imenu-example--python-generic-regexp
786 (point-min) t)))
787 (setq prev-name def-name)
788 (and looking-p
789 (setq looking-p
790 (re-search-forward imenu-example--python-generic-regexp
791 (point-max) 'move))))
792 (nreverse index-alist)))
793
Barry Warsaw42f707f1996-07-29 21:05:05 +0000794
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000795;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000796(defun python-mode ()
797 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000798To submit a problem report, enter `\\[py-submit-bug-report]' from a
799`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
800documentation. To see what version of `python-mode' you are running,
801enter `\\[py-version]'.
802
803This mode knows about Python indentation, tokens, comments and
804continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000805
806COMMANDS
807\\{py-mode-map}
808VARIABLES
809
Barry Warsaw42f707f1996-07-29 21:05:05 +0000810py-indent-offset\t\tindentation increment
811py-block-comment-prefix\t\tcomment string used by comment-region
812py-python-command\t\tshell command to invoke Python interpreter
813py-scroll-process-buffer\t\talways scroll Python process buffer
814py-temp-directory\t\tdirectory used for temp files (if needed)
815py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000816 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000817 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000818 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000819 (make-local-variable 'font-lock-defaults)
820 (make-local-variable 'paragraph-separate)
821 (make-local-variable 'paragraph-start)
822 (make-local-variable 'require-final-newline)
823 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000824 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000825 (make-local-variable 'comment-start-skip)
826 (make-local-variable 'comment-column)
827 (make-local-variable 'indent-region-function)
828 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000829 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000830 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000831 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000832 (setq major-mode 'python-mode
833 mode-name "Python"
834 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000835 paragraph-separate "^[ \t]*$"
836 paragraph-start "^[ \t]*$"
837 require-final-newline t
838 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000839 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000840 comment-start-skip "# *"
841 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000842 indent-region-function 'py-indent-region
843 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000844 ;; tell add-log.el how to find the current function/method/variable
845 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000846 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000847 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000848 ;; add the menu
849 (if py-menu
850 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000851 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000852 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000853 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000854 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000855 ;;
856 ;; not sure where the magic comment has to be; to save time
857 ;; searching for a rarity, we give up if it's not found prior to the
858 ;; first executable statement.
859 ;;
860 ;; BAW - on first glance, this seems like complete hackery. Why was
861 ;; this necessary, and is it still necessary?
862 (let ((case-fold-search nil)
863 (start (point))
864 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000865 (if (re-search-forward
866 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
867 (prog2 (py-next-statement 1) (point) (goto-char 1))
868 t)
869 (progn
870 (setq new-tab-width
871 (string-to-int
872 (buffer-substring (match-beginning 1) (match-end 1))))
873 (if (= tab-width new-tab-width)
874 nil
875 (setq tab-width new-tab-width)
876 (message "Caution: tab-width changed to %d" new-tab-width)
877 (if py-beep-if-tab-change (beep)))))
878 (goto-char start))
879
Barry Warsaw755c6711996-08-01 20:02:55 +0000880 ;; install imenu
Barry Warsawc8520351997-11-26 06:14:40 +0000881 (make-variable-buffer-local 'imenu-create-index-function)
Barry Warsaw755c6711996-08-01 20:02:55 +0000882 (setq imenu-create-index-function
883 (function imenu-example--create-python-index))
Barry Warsawe467bfb1997-11-26 05:40:58 +0000884 (setq imenu-generic-expression
885 imenu-example--generic-python-expression)
Barry Warsaw755c6711996-08-01 20:02:55 +0000886 (if (fboundp 'imenu-add-to-menubar)
887 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
888
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000890 (if python-mode-hook
891 (run-hooks 'python-mode-hook)
892 (run-hooks 'py-mode-hook)))
893
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000894
Barry Warsawb91b7431995-03-14 15:55:20 +0000895;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000896(defun py-outdent-p ()
897 ;; returns non-nil if the current line should outdent one level
898 (save-excursion
899 (and (progn (back-to-indentation)
900 (looking-at py-outdent-re))
901 (progn (backward-to-indentation 1)
902 (while (or (looking-at py-blank-or-comment-re)
903 (bobp))
904 (backward-to-indentation 1))
905 (not (looking-at py-no-outdent-re)))
906 )))
907
Barry Warsawb91b7431995-03-14 15:55:20 +0000908(defun py-electric-colon (arg)
909 "Insert a colon.
910In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000911argument is provided, that many colons are inserted non-electrically.
912Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000913 (interactive "P")
914 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000915 ;; are we in a string or comment?
916 (if (save-excursion
917 (let ((pps (parse-partial-sexp (save-excursion
918 (beginning-of-python-def-or-class)
919 (point))
920 (point))))
921 (not (or (nth 3 pps) (nth 4 pps)))))
922 (save-excursion
923 (let ((here (point))
924 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000925 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000926 (if (and (not arg)
927 (py-outdent-p)
928 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000929 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000930 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000931 )
932 (setq outdent py-indent-offset))
933 ;; Don't indent, only outdent. This assumes that any lines that
934 ;; are already outdented relative to py-compute-indentation were
935 ;; put there on purpose. Its highly annoying to have `:' indent
936 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
937 ;; there a better way to determine this???
938 (if (< (current-indentation) indent) nil
939 (goto-char here)
940 (beginning-of-line)
941 (delete-horizontal-space)
942 (indent-to (- indent outdent))
943 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000944
945
Barry Warsawa97a3f31997-11-04 18:47:06 +0000946;; Python subprocess utilities and filters
947(defun py-execute-file (proc filename)
948 ;; Send a properly formatted execfile('FILENAME') to the underlying
949 ;; Python interpreter process FILENAME. Make that process's buffer
950 ;; visible and force display. Also make comint believe the user
951 ;; typed this string so that kill-output-from-shell does The Right
952 ;; Thing.
953 (let ((curbuf (current-buffer))
954 (procbuf (process-buffer proc))
955 (comint-scroll-to-bottom-on-output t)
956 (msg (format "## working on region in file %s...\n" filename))
957 (cmd (format "execfile('%s')\n" filename)))
958 (unwind-protect
959 (progn
960 (set-buffer procbuf)
961 (goto-char (point-max))
962 (move-marker (process-mark proc) (point))
963 (funcall (process-filter proc) proc msg))
964 (set-buffer curbuf))
965 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000966
967(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000968 (let ((curbuf (current-buffer))
969 (pbuf (process-buffer pyproc))
970 (pmark (process-mark pyproc))
971 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000972 ;; make sure we switch to a different buffer at least once. if we
973 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000974 ;; window, and point is before the end, and lots of output is
975 ;; coming at a fast pace, then (a) simple cursor-movement commands
976 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
977 ;; to have a visible effect (the window just doesn't get updated,
978 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
979 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000980 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981 ;; #b makes no sense to me at all. #a almost makes sense: unless
982 ;; we actually change buffers, set_buffer_internal in buffer.c
983 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
984 ;; seems to make the Emacs command loop reluctant to update the
985 ;; display. Perhaps the default process filter in process.c's
986 ;; read_process_output has update_mode_lines++ for a similar
987 ;; reason? beats me ...
988
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000989 (unwind-protect
990 ;; make sure current buffer is restored
991 ;; BAW - we want to check to see if this still applies
992 (progn
993 ;; mysterious ugly hack
994 (if (eq curbuf pbuf)
995 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000997 (set-buffer pbuf)
998 (let* ((start (point))
999 (goback (< start pmark))
1000 (goend (and (not goback) (= start (point-max))))
1001 (buffer-read-only nil))
1002 (goto-char pmark)
1003 (insert string)
1004 (move-marker pmark (point))
1005 (setq file-finished
1006 (and py-file-queue
1007 (equal ">>> "
1008 (buffer-substring
1009 (prog2 (beginning-of-line) (point)
1010 (goto-char pmark))
1011 (point)))))
1012 (if goback (goto-char start)
1013 ;; else
1014 (if py-scroll-process-buffer
1015 (let* ((pop-up-windows t)
1016 (pwin (display-buffer pbuf)))
1017 (set-window-point pwin (point)))))
1018 (set-buffer curbuf)
1019 (if file-finished
1020 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001021 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001022 (setq py-file-queue (cdr py-file-queue))
1023 (if py-file-queue
1024 (py-execute-file pyproc (car py-file-queue)))))
1025 (and goend
1026 (progn (set-buffer pbuf)
1027 (goto-char (point-max))))
1028 ))
1029 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001030
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001031(defun py-postprocess-output-buffer (buf)
1032 (save-excursion
1033 (set-buffer buf)
1034 (beginning-of-buffer)
1035 (while (re-search-forward py-traceback-line-re nil t)
1036 (let ((file (match-string 1))
1037 (line (string-to-int (match-string 2))))
1038 (py-highlight-line (py-point 'bol) (py-point 'eol) file line))
1039 )))
1040
Barry Warsawa97a3f31997-11-04 18:47:06 +00001041
1042;;; Subprocess commands
1043
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001044;; only used when (memq 'broken-temp-names py-emacs-features)
1045(defvar py-serial-number 0)
1046(defvar py-exception-buffer nil)
1047(defconst py-output-buffer "*Python Output*")
1048
Barry Warsawa97a3f31997-11-04 18:47:06 +00001049;;;###autoload
1050(defun py-shell ()
1051 "Start an interactive Python interpreter in another window.
1052This is like Shell mode, except that Python is running in the window
1053instead of a shell. See the `Interactive Shell' and `Shell Mode'
1054sections of the Emacs manual for details, especially for the key
1055bindings active in the `*Python*' buffer.
1056
1057See the docs for variable `py-scroll-buffer' for info on scrolling
1058behavior in the process window.
1059
1060Warning: Don't use an interactive Python if you change sys.ps1 or
1061sys.ps2 from their default values, or if you're running code that
1062prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1063distinguish your output from Python's output, and assumes that `>>> '
1064at the start of a line is a prompt from Python. Similarly, the Emacs
1065Shell mode code assumes that both `>>> ' and `... ' at the start of a
1066line are Python prompts. Bad things can happen if you fool either
1067mode.
1068
1069Warning: If you do any editing *in* the process buffer *while* the
1070buffer is accepting output from Python, do NOT attempt to `undo' the
1071changes. Some of the output (nowhere near the parts you changed!) may
1072be lost if you do. This appears to be an Emacs bug, an unfortunate
1073interaction between undo and process filters; the same problem exists in
1074non-Python process buffers using the default (Emacs-supplied) process
1075filter."
1076 ;; BAW - should undo be disabled in the python process buffer, if
1077 ;; this bug still exists?
1078 (interactive)
1079 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001080 (switch-to-buffer-other-window
1081 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001082 (make-local-variable 'comint-prompt-regexp)
1083 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1084 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1085 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001086 ;; set up keybindings for this subshell
1087 (local-set-key [tab] 'self-insert-command)
1088 (local-set-key "\C-c-" 'py-up-exception)
1089 (local-set-key "\C-c=" 'py-down-exception)
1090 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001091
Barry Warsawa97a3f31997-11-04 18:47:06 +00001092(defun py-clear-queue ()
1093 "Clear the queue of temporary files waiting to execute."
1094 (interactive)
1095 (let ((n (length py-file-queue)))
1096 (mapcar 'delete-file py-file-queue)
1097 (setq py-file-queue nil)
1098 (message "%d pending files de-queued." n)))
1099
1100(defun py-execute-region (start end &optional async)
1101 "Execute the the region in a Python interpreter.
1102The region is first copied into a temporary file (in the directory
1103`py-temp-directory'). If there is no Python interpreter shell
1104running, this file is executed synchronously using
1105`shell-command-on-region'. If the program is long running, use an
1106optional \\[universal-argument] to run the command asynchronously in
1107its own buffer.
1108
1109If the Python interpreter shell is running, the region is execfile()'d
1110in that shell. If you try to execute regions too quickly,
1111`python-mode' will queue them up and execute them one at a time when
1112it sees a `>>> ' prompt from Python. Each time this happens, the
1113process buffer is popped into a window (if it's not already in some
1114window) so you can see it, and a comment of the form
1115
1116 \t## working on region in file <name>...
1117
1118is inserted at the end. See also the command `py-clear-queue'."
1119 (interactive "r\nP")
1120 (or (< start end)
1121 (error "Region is empty"))
1122 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001123 (temp (if (memq 'broken-temp-names py-emacs-features)
1124 (prog1
1125 (format "python-%d" py-serial-number)
1126 (setq py-serial-number (1+ py-serial-number)))
1127 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001128 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001129 (write-region start end file nil 'nomsg)
1130 (cond
1131 ;; always run the code in it's own asynchronous subprocess
1132 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001133 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001134 (start-process "Python" buf py-python-command "-u" file)
1135 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001136 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001137 ))
1138 ;; if the Python interpreter shell is running, queue it up for
1139 ;; execution there.
1140 (proc
1141 ;; use the existing python shell
1142 (if (not py-file-queue)
1143 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001144 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001145 (push file py-file-queue)
1146 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001147 (t
1148 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001149 (shell-command-on-region start end py-python-command py-output-buffer)
1150 (setq py-exception-buffer (current-buffer))
1151 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001152 ))))
1153
1154;; Code execution command
1155(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001156 "Send the contents of the buffer to a Python interpreter.
1157If there is a *Python* process buffer it is used. If a clipping
1158restriction is in effect, only the accessible portion of the buffer is
1159sent. A trailing newline will be supplied if needed.
1160
1161See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001162 (interactive "P")
1163 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001164
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001165
1166
1167(defun py-jump-to-exception (file line)
1168 (let ((buffer (cond ((string-equal file "<stdin>")
1169 py-exception-buffer)
1170 ((and (consp py-exception-buffer)
1171 (string-equal file (car py-exception-buffer)))
1172 (cdr py-exception-buffer))
1173 ((py-safe (find-file-noselect file)))
1174 ;; could not figure out what file the exception
1175 ;; is pointing to, so prompt for it
1176 (t (find-file (read-file-name "Exception file: "
1177 nil
1178 file t))))))
1179 (pop-to-buffer buffer)
1180 (goto-line line)
1181 (message "Jumping to exception in file %s on line %d" file line)))
1182
1183(defun py-mouseto-exception (event)
1184 (interactive "e")
1185 (cond
1186 ((fboundp 'event-point)
1187 ;; XEmacs
1188 (let* ((point (event-point event))
1189 (buffer (event-buffer event))
1190 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1191 (info (and e (extent-property e 'py-exc-info))))
1192 (message "Event point: %d, info: %s" point info)
1193 (and info
1194 (py-jump-to-exception (car info) (cdr info)))
1195 ))
1196 ;; Emacs -- Please port this!
1197 ))
1198
1199(defun py-goto-exception ()
1200 "Go to the line indicated by the traceback."
1201 (interactive)
1202 (let (file line)
1203 (save-excursion
1204 (beginning-of-line)
1205 (if (looking-at py-traceback-line-re)
1206 (setq file (match-string 1)
1207 line (string-to-int (match-string 2)))))
1208 (if (not file)
1209 (error "Not on a traceback line."))
1210 (py-jump-to-exception file line)))
1211
1212(defun py-find-next-exception (start buffer searchdir errwhere)
1213 ;; Go to start position in buffer, search in the specified
1214 ;; direction, and jump to the exception found. If at the end of the
1215 ;; exception, print error message
1216 (let (file line)
1217 (save-excursion
1218 (set-buffer buffer)
1219 (goto-char (py-point start))
1220 (if (funcall searchdir py-traceback-line-re nil t)
1221 (setq file (match-string 1)
1222 line (string-to-int (match-string 2)))))
1223 (if (and file line)
1224 (py-jump-to-exception file line)
1225 (error "%s of traceback" errwhere))))
1226
1227(defun py-down-exception (&optional bottom)
1228 "Go to the next line down in the traceback.
1229With optional \\[universal-argument], jump to the bottom (innermost)
1230exception in the exception stack."
1231 (interactive "P")
1232 (let* ((proc (get-process "Python"))
1233 (buffer (if proc "*Python*" py-output-buffer)))
1234 (if bottom
1235 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1236 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1237
1238(defun py-up-exception (&optional top)
1239 "Go to the previous line up in the traceback.
1240With optional \\[universal-argument], jump to the top (outermost)
1241exception in the exception stack."
1242 (interactive "P")
1243 (let* ((proc (get-process "Python"))
1244 (buffer (if proc "*Python*" py-output-buffer)))
1245 (if top
1246 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001247 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001248
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001249
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001250;; Electric deletion
1251(defun py-electric-backspace (arg)
1252 "Deletes preceding character or levels of indentation.
1253Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001254with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001255
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001256If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001258Otherwise, if point is at the leftmost non-whitespace character of a
1259line that is neither a continuation line nor a non-indenting comment
1260line, or if point is at the end of a blank line, this command reduces
1261the indentation to match that of the line that opened the current
1262block of code. The line that opened the block is displayed in the
1263echo area to help you keep track of where you are. With numeric arg,
1264outdents that many blocks (but not past column zero).
1265
1266Otherwise the preceding character is deleted, converting a tab to
1267spaces if needed so that only a single column position is deleted.
1268Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001269 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001270 (if (or (/= (current-indentation) (current-column))
1271 (bolp)
1272 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001273 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001274 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001275 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001276 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277 ;; force non-blank so py-goto-block-up doesn't ignore it
1278 (insert-char ?* 1)
1279 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001280 (let ((base-indent 0) ; indentation of base line
1281 (base-text "") ; and text of base line
1282 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001283 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001284 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001285 (condition-case nil ; in case no enclosing block
1286 (progn
1287 (py-goto-block-up 'no-mark)
1288 (setq base-indent (current-indentation)
1289 base-text (py-suck-up-leading-text)
1290 base-found-p t))
1291 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001292 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001293 (delete-char 1) ; toss the dummy character
1294 (delete-horizontal-space)
1295 (indent-to base-indent)
1296 (if base-found-p
1297 (message "Closes block: %s" base-text)))))
1298
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001299
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001300(defun py-electric-delete (arg)
1301 "Deletes preceding or following character or levels of whitespace.
1302
1303The behavior of this function depends on the variable
1304`delete-key-deletes-forward'. If this variable is nil (or does not
1305exist, as in older Emacsen), then this function behaves identical to
1306\\[c-electric-backspace].
1307
1308If `delete-key-deletes-forward' is non-nil and is supported in your
1309Emacs, then deletion occurs in the forward direction, by calling the
1310function in `py-delete-function'."
1311 (interactive "*p")
1312 (if (and (boundp 'delete-key-deletes-forward)
1313 delete-key-deletes-forward)
1314 (funcall py-delete-function arg)
1315 ;; else
1316 (py-electric-backspace arg)))
1317
1318;; required for pending-del and delsel modes
1319(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1320(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1321(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1322(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1323
1324
1325
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001326(defun py-indent-line (&optional arg)
1327 "Fix the indentation of the current line according to Python rules.
1328With \\[universal-argument], ignore outdenting rules for block
1329closing statements (e.g. return, raise, break, continue, pass)
1330
1331This function is normally bound to `indent-line-function' so
1332\\[indent-for-tab-command] will call it."
1333 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001334 (let* ((ci (current-indentation))
1335 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001336 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001337 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001338 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001339 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340 (if (/= ci need)
1341 (save-excursion
1342 (beginning-of-line)
1343 (delete-horizontal-space)
1344 (indent-to need)))
1345 (if move-to-indentation-p (back-to-indentation))))
1346
1347(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001349This is just `strives to' because correct indentation can't be computed
1350from scratch for Python code. In general, deletes the whitespace before
1351point, inserts a newline, and takes an educated guess as to how you want
1352the new line indented."
1353 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001354 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001355 (if (< ci (current-column)) ; if point beyond indentation
1356 (newline-and-indent)
1357 ;; else try to act like newline-and-indent "normally" acts
1358 (beginning-of-line)
1359 (insert-char ?\n 1)
1360 (move-to-column ci))))
1361
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001362(defun py-compute-indentation (honor-block-close-p)
1363 ;; implements all the rules for indentation computation. when
1364 ;; honor-block-close-p is non-nil, statements such as return, raise,
1365 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001366 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001367 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001368 (pps (parse-partial-sexp bod (point)))
1369 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001370 (beginning-of-line)
1371 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001372 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001373 ((or (and (nth 3 pps) (nth 3 boipps))
1374 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001375 (save-excursion
1376 (if (not py-align-multiline-strings-p) 0
1377 ;; skip back over blank & non-indenting comment lines
1378 ;; note: will skip a blank or non-indenting comment line
1379 ;; that happens to be a continuation line too
1380 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1381 (back-to-indentation)
1382 (current-column))))
1383 ;; are we on a continuation line?
1384 ((py-continuation-line-p)
1385 (let ((startpos (point))
1386 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001387 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001388 (if open-bracket-pos
1389 (progn
1390 ;; align with first item in list; else a normal
1391 ;; indent beyond the line with the open bracket
1392 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1393 ;; is the first list item on the same line?
1394 (skip-chars-forward " \t")
1395 (if (null (memq (following-char) '(?\n ?# ?\\)))
1396 ; yes, so line up with it
1397 (current-column)
1398 ;; first list item on another line, or doesn't exist yet
1399 (forward-line 1)
1400 (while (and (< (point) startpos)
1401 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1402 (forward-line 1))
1403 (if (< (point) startpos)
1404 ;; again mimic the first list item
1405 (current-indentation)
1406 ;; else they're about to enter the first item
1407 (goto-char open-bracket-pos)
1408 (+ (current-indentation) py-indent-offset))))
1409
1410 ;; else on backslash continuation line
1411 (forward-line -1)
1412 (if (py-continuation-line-p) ; on at least 3rd line in block
1413 (current-indentation) ; so just continue the pattern
1414 ;; else started on 2nd line in block, so indent more.
1415 ;; if base line is an assignment with a start on a RHS,
1416 ;; indent to 2 beyond the leftmost "="; else skip first
1417 ;; chunk of non-whitespace characters on base line, + 1 more
1418 ;; column
1419 (end-of-line)
1420 (setq endpos (point) searching t)
1421 (back-to-indentation)
1422 (setq startpos (point))
1423 ;; look at all "=" from left to right, stopping at first
1424 ;; one not nested in a list or string
1425 (while searching
1426 (skip-chars-forward "^=" endpos)
1427 (if (= (point) endpos)
1428 (setq searching nil)
1429 (forward-char 1)
1430 (setq state (parse-partial-sexp startpos (point)))
1431 (if (and (zerop (car state)) ; not in a bracket
1432 (null (nth 3 state))) ; & not in a string
1433 (progn
1434 (setq searching nil) ; done searching in any case
1435 (setq found
1436 (not (or
1437 (eq (following-char) ?=)
1438 (memq (char-after (- (point) 2))
1439 '(?< ?> ?!)))))))))
1440 (if (or (not found) ; not an assignment
1441 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1442 (progn
1443 (goto-char startpos)
1444 (skip-chars-forward "^ \t\n")))
1445 (1+ (current-column))))))
1446
1447 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001448 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001449
Barry Warsawa7891711996-08-01 15:53:09 +00001450 ;; Dfn: "Indenting comment line". A line containing only a
1451 ;; comment, but which is treated like a statement for
1452 ;; indentation calculation purposes. Such lines are only
1453 ;; treated specially by the mode; they are not treated
1454 ;; specially by the Python interpreter.
1455
1456 ;; The rules for indenting comment lines are a line where:
1457 ;; - the first non-whitespace character is `#', and
1458 ;; - the character following the `#' is whitespace, and
1459 ;; - the line is outdented with respect to (i.e. to the left
1460 ;; of) the indentation of the preceding non-blank line.
1461
1462 ;; The first non-blank line following an indenting comment
1463 ;; line is given the same amount of indentation as the
1464 ;; indenting comment line.
1465
1466 ;; All other comment-only lines are ignored for indentation
1467 ;; purposes.
1468
1469 ;; Are we looking at a comment-only line which is *not* an
1470 ;; indenting comment line? If so, we assume that its been
1471 ;; placed at the desired indentation, so leave it alone.
1472 ;; Indenting comment lines are aligned as statements down
1473 ;; below.
1474 ((and (looking-at "[ \t]*#[^ \t\n]")
1475 ;; NOTE: this test will not be performed in older Emacsen
1476 (fboundp 'forward-comment)
1477 (<= (current-indentation)
1478 (save-excursion
1479 (forward-comment (- (point-max)))
1480 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001481 (current-indentation))
1482
1483 ;; else indentation based on that of the statement that
1484 ;; precedes us; use the first line of that statement to
1485 ;; establish the base, in case the user forced a non-std
1486 ;; indentation for the continuation lines (if any)
1487 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001488 ;; skip back over blank & non-indenting comment lines note:
1489 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001490 ;; happens to be a continuation line too. use fast Emacs 19
1491 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001492 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001493 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001494 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001495 (let (done)
1496 (while (not done)
1497 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1498 nil 'move)
1499 (setq done (or (eq py-honor-comment-indentation t)
1500 (bobp)
1501 (/= (following-char) ?#)
1502 (not (zerop (current-column)))))
1503 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001504 ;; if we landed inside a string, go to the beginning of that
1505 ;; string. this handles triple quoted, multi-line spanning
1506 ;; strings.
1507 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001508 (+ (current-indentation)
1509 (if (py-statement-opens-block-p)
1510 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001511 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001512 (- py-indent-offset)
1513 0)))
1514 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001515
1516(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001518By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001519`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001520Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001522their own buffer-local copy), both those currently existing and those
1523created later in the Emacs session.
1524
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001525Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001526There's no excuse for such foolishness, but sometimes you have to deal
1527with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001528`py-indent-offset' to what it thinks it was when they created the
1529mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001530
1531Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001532looking for a line that opens a block of code. `py-indent-offset' is
1533set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001534statement following it. If the search doesn't succeed going forward,
1535it's tried again going backward."
1536 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537 (let (new-value
1538 (start (point))
1539 restart
1540 (found nil)
1541 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001542 (py-goto-initial-line)
1543 (while (not (or found (eobp)))
1544 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1545 (progn
1546 (setq restart (point))
1547 (py-goto-initial-line)
1548 (if (py-statement-opens-block-p)
1549 (setq found t)
1550 (goto-char restart)))))
1551 (if found
1552 ()
1553 (goto-char start)
1554 (py-goto-initial-line)
1555 (while (not (or found (bobp)))
1556 (setq found
1557 (and
1558 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1559 (or (py-goto-initial-line) t) ; always true -- side effect
1560 (py-statement-opens-block-p)))))
1561 (setq colon-indent (current-indentation)
1562 found (and found (zerop (py-next-statement 1)))
1563 new-value (- (current-indentation) colon-indent))
1564 (goto-char start)
1565 (if found
1566 (progn
1567 (funcall (if global 'kill-local-variable 'make-local-variable)
1568 'py-indent-offset)
1569 (setq py-indent-offset new-value)
1570 (message "%s value of py-indent-offset set to %d"
1571 (if global "Global" "Local")
1572 py-indent-offset))
1573 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1574
1575(defun py-shift-region (start end count)
1576 (save-excursion
1577 (goto-char end) (beginning-of-line) (setq end (point))
1578 (goto-char start) (beginning-of-line) (setq start (point))
1579 (indent-rigidly start end count)))
1580
1581(defun py-shift-region-left (start end &optional count)
1582 "Shift region of Python code to the left.
1583The lines from the line containing the start of the current region up
1584to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001585shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586
1587If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001588many columns. With no active region, outdent only the current line.
1589You cannot outdent the region if any line is already at column zero."
1590 (interactive
1591 (let ((p (point))
1592 (m (mark))
1593 (arg current-prefix-arg))
1594 (if m
1595 (list (min p m) (max p m) arg)
1596 (list p (save-excursion (forward-line 1) (point)) arg))))
1597 ;; if any line is at column zero, don't shift the region
1598 (save-excursion
1599 (goto-char start)
1600 (while (< (point) end)
1601 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001602 (if (and (zerop (current-column))
1603 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001604 (error "Region is at left edge."))
1605 (forward-line 1)))
1606 (py-shift-region start end (- (prefix-numeric-value
1607 (or count py-indent-offset))))
1608 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001609
1610(defun py-shift-region-right (start end &optional count)
1611 "Shift region of Python code to the right.
1612The lines from the line containing the start of the current region up
1613to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001614shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001615
1616If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001617many columns. With no active region, indent only the current line."
1618 (interactive
1619 (let ((p (point))
1620 (m (mark))
1621 (arg current-prefix-arg))
1622 (if m
1623 (list (min p m) (max p m) arg)
1624 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001625 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001626 (or count py-indent-offset)))
1627 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001628
1629(defun py-indent-region (start end &optional indent-offset)
1630 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001631
Barry Warsaw7ae77681994-12-12 20:38:05 +00001632The lines from the line containing the start of the current region up
1633to (but not including) the line containing the end of the region are
1634reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001635character in the first column, the first line is left alone and the
1636rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001637region is reindented with respect to the (closest code or indenting
1638comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001639
1640This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001641control structures are introduced or removed, or to reformat code
1642using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001643
1644If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001645the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001646used.
1647
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001648Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001649is called! This function does not compute proper indentation from
1650scratch (that's impossible in Python), it merely adjusts the existing
1651indentation to be correct in context.
1652
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001653Warning: This function really has no idea what to do with
1654non-indenting comment lines, and shifts them as if they were indenting
1655comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001657Special cases: whitespace is deleted from blank lines; continuation
1658lines are shifted by the same amount their initial line was shifted,
1659in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001661 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001662 (save-excursion
1663 (goto-char end) (beginning-of-line) (setq end (point-marker))
1664 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001665 (let ((py-indent-offset (prefix-numeric-value
1666 (or indent-offset py-indent-offset)))
1667 (indents '(-1)) ; stack of active indent levels
1668 (target-column 0) ; column to which to indent
1669 (base-shifted-by 0) ; amount last base line was shifted
1670 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001671 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001672 0))
1673 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674 (while (< (point) end)
1675 (setq ci (current-indentation))
1676 ;; figure out appropriate target column
1677 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001678 ((or (eq (following-char) ?#) ; comment in column 1
1679 (looking-at "[ \t]*$")) ; entirely blank
1680 (setq target-column 0))
1681 ((py-continuation-line-p) ; shift relative to base line
1682 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683 (t ; new base line
1684 (if (> ci (car indents)) ; going deeper; push it
1685 (setq indents (cons ci indents))
1686 ;; else we should have seen this indent before
1687 (setq indents (memq ci indents)) ; pop deeper indents
1688 (if (null indents)
1689 (error "Bad indentation in region, at line %d"
1690 (save-restriction
1691 (widen)
1692 (1+ (count-lines 1 (point)))))))
1693 (setq target-column (+ indent-base
1694 (* py-indent-offset
1695 (- (length indents) 2))))
1696 (setq base-shifted-by (- target-column ci))))
1697 ;; shift as needed
1698 (if (/= ci target-column)
1699 (progn
1700 (delete-horizontal-space)
1701 (indent-to target-column)))
1702 (forward-line 1))))
1703 (set-marker end nil))
1704
Barry Warsawa7891711996-08-01 15:53:09 +00001705(defun py-comment-region (beg end &optional arg)
1706 "Like `comment-region' but uses double hash (`#') comment starter."
1707 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001708 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001709 (comment-region beg end arg)))
1710
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001711
1712;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713(defun py-previous-statement (count)
1714 "Go to the start of previous Python statement.
1715If the statement at point is the i'th Python statement, goes to the
1716start of statement i-COUNT. If there is no such statement, goes to the
1717first statement. Returns count of statements left to move.
1718`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001719 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001720 (if (< count 0) (py-next-statement (- count))
1721 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001722 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001724 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001725 (> count 0)
1726 (zerop (forward-line -1))
1727 (py-goto-statement-at-or-above))
1728 (setq count (1- count)))
1729 (if (> count 0) (goto-char start)))
1730 count))
1731
1732(defun py-next-statement (count)
1733 "Go to the start of next Python statement.
1734If the statement at point is the i'th Python statement, goes to the
1735start of statement i+COUNT. If there is no such statement, goes to the
1736last statement. Returns count of statements left to move. `Statements'
1737do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001738 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739 (if (< count 0) (py-previous-statement (- count))
1740 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001742 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744 (> count 0)
1745 (py-goto-statement-below))
1746 (setq count (1- count)))
1747 (if (> count 0) (goto-char start)))
1748 count))
1749
1750(defun py-goto-block-up (&optional nomark)
1751 "Move up to start of current block.
1752Go to the statement that starts the smallest enclosing block; roughly
1753speaking, this will be the closest preceding statement that ends with a
1754colon and is indented less than the statement you started on. If
1755successful, also sets the mark to the starting point.
1756
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001757`\\[py-mark-block]' can be used afterward to mark the whole code
1758block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001759
1760If called from a program, the mark will not be set if optional argument
1761NOMARK is not nil."
1762 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001763 (let ((start (point))
1764 (found nil)
1765 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766 (py-goto-initial-line)
1767 ;; if on blank or non-indenting comment line, use the preceding stmt
1768 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1769 (progn
1770 (py-goto-statement-at-or-above)
1771 (setq found (py-statement-opens-block-p))))
1772 ;; search back for colon line indented less
1773 (setq initial-indent (current-indentation))
1774 (if (zerop initial-indent)
1775 ;; force fast exit
1776 (goto-char (point-min)))
1777 (while (not (or found (bobp)))
1778 (setq found
1779 (and
1780 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1781 (or (py-goto-initial-line) t) ; always true -- side effect
1782 (< (current-indentation) initial-indent)
1783 (py-statement-opens-block-p))))
1784 (if found
1785 (progn
1786 (or nomark (push-mark start))
1787 (back-to-indentation))
1788 (goto-char start)
1789 (error "Enclosing block not found"))))
1790
1791(defun beginning-of-python-def-or-class (&optional class)
1792 "Move point to start of def (or class, with prefix arg).
1793
1794Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001795arg, looks for a `class' instead. The docs assume the `def' case;
1796just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001798If point is in a def statement already, and after the `d', simply
1799moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001800
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001801Else (point is not in a def statement, or at or before the `d' of a
1802def statement), searches for the closest preceding def statement, and
1803leaves point at its start. If no such statement can be found, leaves
1804point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001805
1806Returns t iff a def statement is found by these rules.
1807
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001808Note that doing this command repeatedly will take you closer to the
1809start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001810
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001811If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001812`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001814 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1815 (start-of-line (progn (beginning-of-line) (point)))
1816 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001817 (if (or (/= start-of-stmt start-of-line)
1818 (not at-or-before-p))
1819 (end-of-line)) ; OK to match on this line
1820 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822
1823(defun end-of-python-def-or-class (&optional class)
1824 "Move point beyond end of def (or class, with prefix arg) body.
1825
1826By default, looks for an appropriate `def'. If you supply a prefix arg,
1827looks for a `class' instead. The docs assume the `def' case; just
1828substitute `class' for `def' for the other case.
1829
1830If point is in a def statement already, this is the def we use.
1831
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001832Else if the def found by `\\[beginning-of-python-def-or-class]'
1833contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
1835Else we search forward for the closest following def, and use that.
1836
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837If a def can be found by these rules, point is moved to the start of
1838the line immediately following the def block, and the position of the
1839start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840
1841Else point is moved to the end of the buffer, and nil is returned.
1842
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843Note that doing this command repeatedly will take you closer to the
1844end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001845
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001847`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849 (let ((start (progn (py-goto-initial-line) (point)))
1850 (which (if class "class" "def"))
1851 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001852 ;; move point to start of appropriate def/class
1853 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1854 (setq state 'at-beginning)
1855 ;; else see if beginning-of-python-def-or-class hits container
1856 (if (and (beginning-of-python-def-or-class class)
1857 (progn (py-goto-beyond-block)
1858 (> (point) start)))
1859 (setq state 'at-end)
1860 ;; else search forward
1861 (goto-char start)
1862 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1863 (progn (setq state 'at-beginning)
1864 (beginning-of-line)))))
1865 (cond
1866 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1867 ((eq state 'at-end) t)
1868 ((eq state 'not-found) nil)
1869 (t (error "internal error in end-of-python-def-or-class")))))
1870
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871
1872;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001873(defun py-mark-block (&optional extend just-move)
1874 "Mark following block of lines. With prefix arg, mark structure.
1875Easier to use than explain. It sets the region to an `interesting'
1876block of succeeding lines. If point is on a blank line, it goes down to
1877the next non-blank line. That will be the start of the region. The end
1878of the region depends on the kind of line at the start:
1879
1880 - If a comment, the region will include all succeeding comment lines up
1881 to (but not including) the next non-comment line (if any).
1882
1883 - Else if a prefix arg is given, and the line begins one of these
1884 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885
1886 if elif else try except finally for while def class
1887
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888 the region will be set to the body of the structure, including
1889 following blocks that `belong' to it, but excluding trailing blank
1890 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001891 and all (if any) of the following `except' and `finally' blocks
1892 that belong to the `try' structure will be in the region. Ditto
1893 for if/elif/else, for/else and while/else structures, and (a bit
1894 degenerate, since they're always one-block structures) def and
1895 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896
1897 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001898 block (see list above), and the block is not a `one-liner' (i.e.,
1899 the statement ends with a colon, not with code), the region will
1900 include all succeeding lines up to (but not including) the next
1901 code statement (if any) that's indented no more than the starting
1902 line, except that trailing blank and comment lines are excluded.
1903 E.g., if the starting line begins a multi-statement `def'
1904 structure, the region will be set to the full function definition,
1905 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001906
1907 - Else the region will include all succeeding lines up to (but not
1908 including) the next blank line, or code or indenting-comment line
1909 indented strictly less than the starting line. Trailing indenting
1910 comment lines are included in this case, but not trailing blank
1911 lines.
1912
1913A msg identifying the location of the mark is displayed in the echo
1914area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1915
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001916If called from a program, optional argument EXTEND plays the role of
1917the prefix arg, and if optional argument JUST-MOVE is not nil, just
1918moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001919 (interactive "P") ; raw prefix arg
1920 (py-goto-initial-line)
1921 ;; skip over blank lines
1922 (while (and
1923 (looking-at "[ \t]*$") ; while blank line
1924 (not (eobp))) ; & somewhere to go
1925 (forward-line 1))
1926 (if (eobp)
1927 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001928 (let ((initial-pos (point))
1929 (initial-indent (current-indentation))
1930 last-pos ; position of last stmt in region
1931 (followers
1932 '((if elif else) (elif elif else) (else)
1933 (try except finally) (except except) (finally)
1934 (for else) (while else)
1935 (def) (class) ) )
1936 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937
1938 (cond
1939 ;; if comment line, suck up the following comment lines
1940 ((looking-at "[ \t]*#")
1941 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1942 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1943 (setq last-pos (point)))
1944
1945 ;; else if line is a block line and EXTEND given, suck up
1946 ;; the whole structure
1947 ((and extend
1948 (setq first-symbol (py-suck-up-first-keyword) )
1949 (assq first-symbol followers))
1950 (while (and
1951 (or (py-goto-beyond-block) t) ; side effect
1952 (forward-line -1) ; side effect
1953 (setq last-pos (point)) ; side effect
1954 (py-goto-statement-below)
1955 (= (current-indentation) initial-indent)
1956 (setq next-symbol (py-suck-up-first-keyword))
1957 (memq next-symbol (cdr (assq first-symbol followers))))
1958 (setq first-symbol next-symbol)))
1959
1960 ;; else if line *opens* a block, search for next stmt indented <=
1961 ((py-statement-opens-block-p)
1962 (while (and
1963 (setq last-pos (point)) ; always true -- side effect
1964 (py-goto-statement-below)
1965 (> (current-indentation) initial-indent))
1966 nil))
1967
1968 ;; else plain code line; stop at next blank line, or stmt or
1969 ;; indenting comment line indented <
1970 (t
1971 (while (and
1972 (setq last-pos (point)) ; always true -- side effect
1973 (or (py-goto-beyond-final-line) t)
1974 (not (looking-at "[ \t]*$")) ; stop at blank line
1975 (or
1976 (>= (current-indentation) initial-indent)
1977 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1978 nil)))
1979
1980 ;; skip to end of last stmt
1981 (goto-char last-pos)
1982 (py-goto-beyond-final-line)
1983
1984 ;; set mark & display
1985 (if just-move
1986 () ; just return
1987 (push-mark (point) 'no-msg)
1988 (forward-line -1)
1989 (message "Mark set after: %s" (py-suck-up-leading-text))
1990 (goto-char initial-pos))))
1991
Barry Warsaw2518c671997-11-05 00:51:08 +00001992(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001993 "Set region to body of def (or class, with prefix arg) enclosing point.
1994Pushes the current mark, then point, on the mark ring (all language
1995modes do this, but although it's handy it's never documented ...).
1996
1997In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001998hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1999`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002000
2001And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002Turned out that was more confusing than useful: the `goto start' and
2003`goto end' commands are usually used to search through a file, and
2004people expect them to act a lot like `search backward' and `search
2005forward' string-search commands. But because Python `def' and `class'
2006can nest to arbitrary levels, finding the smallest def containing
2007point cannot be done via a simple backward search: the def containing
2008point may not be the closest preceding def, or even the closest
2009preceding def that's indented less. The fancy algorithm required is
2010appropriate for the usual uses of this `mark' command, but not for the
2011`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013So the def marked by this command may not be the one either of the
2014`goto' commands find: If point is on a blank or non-indenting comment
2015line, moves back to start of the closest preceding code statement or
2016indenting comment line. If this is a `def' statement, that's the def
2017we use. Else searches for the smallest enclosing `def' block and uses
2018that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020When an enclosing def is found: The mark is left immediately beyond
2021the last line of the def block. Point is left at the start of the
2022def, except that: if the def is preceded by a number of comment lines
2023followed by (at most) one optional blank line, point is left at the
2024start of the comments; else if the def is preceded by a blank line,
2025point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002026
2027The intent is to mark the containing def/class and its associated
2028documentation, to make moving and duplicating functions and classes
2029pleasant."
2030 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002031 (let ((start (point))
2032 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002033 (push-mark start)
2034 (if (not (py-go-up-tree-to-keyword which))
2035 (progn (goto-char start)
2036 (error "Enclosing %s not found" which))
2037 ;; else enclosing def/class found
2038 (setq start (point))
2039 (py-goto-beyond-block)
2040 (push-mark (point))
2041 (goto-char start)
2042 (if (zerop (forward-line -1)) ; if there is a preceding line
2043 (progn
2044 (if (looking-at "[ \t]*$") ; it's blank
2045 (setq start (point)) ; so reset start point
2046 (goto-char start)) ; else try again
2047 (if (zerop (forward-line -1))
2048 (if (looking-at "[ \t]*#") ; a comment
2049 ;; look back for non-comment line
2050 ;; tricky: note that the regexp matches a blank
2051 ;; line, cuz \n is in the 2nd character class
2052 (and
2053 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2054 (forward-line 1))
2055 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002056 (goto-char start)))))))
2057 (exchange-point-and-mark)
2058 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002060;; ripped from cc-mode
2061(defun py-forward-into-nomenclature (&optional arg)
2062 "Move forward to end of a nomenclature section or word.
2063With arg, to it arg times.
2064
2065A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2066 (interactive "p")
2067 (let ((case-fold-search nil))
2068 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002069 (re-search-forward
2070 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2071 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002072 (while (and (< arg 0)
2073 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002074 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002075 (point-min) 0))
2076 (forward-char 1)
2077 (setq arg (1+ arg)))))
2078 (py-keep-region-active))
2079
2080(defun py-backward-into-nomenclature (&optional arg)
2081 "Move backward to beginning of a nomenclature section or word.
2082With optional ARG, move that many times. If ARG is negative, move
2083forward.
2084
2085A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2086 (interactive "p")
2087 (py-forward-into-nomenclature (- arg))
2088 (py-keep-region-active))
2089
2090
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002091
2092;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002093
2094;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002095;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2096;; out of the right places, along with the keys they're on & current
2097;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098(defun py-dump-help-string (str)
2099 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002100 (let ((locals (buffer-local-variables))
2101 funckind funcname func funcdoc
2102 (start 0) mstart end
2103 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002104 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2105 (setq mstart (match-beginning 0) end (match-end 0)
2106 funckind (substring str (match-beginning 1) (match-end 1))
2107 funcname (substring str (match-beginning 2) (match-end 2))
2108 func (intern funcname))
2109 (princ (substitute-command-keys (substring str start mstart)))
2110 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002111 ((equal funckind "c") ; command
2112 (setq funcdoc (documentation func)
2113 keys (concat
2114 "Key(s): "
2115 (mapconcat 'key-description
2116 (where-is-internal func py-mode-map)
2117 ", "))))
2118 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002119 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002120 keys (if (assq func locals)
2121 (concat
2122 "Local/Global values: "
2123 (prin1-to-string (symbol-value func))
2124 " / "
2125 (prin1-to-string (default-value func)))
2126 (concat
2127 "Value: "
2128 (prin1-to-string (symbol-value func))))))
2129 (t ; unexpected
2130 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002131 (princ (format "\n-> %s:\t%s\t%s\n\n"
2132 (if (equal funckind "c") "Command" "Variable")
2133 funcname keys))
2134 (princ funcdoc)
2135 (terpri)
2136 (setq start end))
2137 (princ (substitute-command-keys (substring str start))))
2138 (print-help-return-message)))
2139
2140(defun py-describe-mode ()
2141 "Dump long form of Python-mode docs."
2142 (interactive)
2143 (py-dump-help-string "Major mode for editing Python files.
2144Knows about Python indentation, tokens, comments and continuation lines.
2145Paragraphs are separated by blank lines only.
2146
2147Major sections below begin with the string `@'; specific function and
2148variable docs begin with `->'.
2149
2150@EXECUTING PYTHON CODE
2151
2152\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2153\\[py-execute-region]\tsends the current region
2154\\[py-shell]\tstarts a Python interpreter window; this will be used by
2155\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2156%c:py-execute-buffer
2157%c:py-execute-region
2158%c:py-shell
2159
2160@VARIABLES
2161
2162py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002163py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002164
2165py-python-command\tshell command to invoke Python interpreter
2166py-scroll-process-buffer\talways scroll Python process buffer
2167py-temp-directory\tdirectory used for temp files (if needed)
2168
2169py-beep-if-tab-change\tring the bell if tab-width is changed
2170%v:py-indent-offset
2171%v:py-block-comment-prefix
2172%v:py-python-command
2173%v:py-scroll-process-buffer
2174%v:py-temp-directory
2175%v:py-beep-if-tab-change
2176
2177@KINDS OF LINES
2178
2179Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002180preceding line ends with a backslash that's not part of a comment, or
2181the paren/bracket/brace nesting level at the start of the line is
2182non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183
2184An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002185possibly blanks or tabs), a `comment line' (leftmost non-blank
2186character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002187
2188Comment Lines
2189
2190Although all comment lines are treated alike by Python, Python mode
2191recognizes two kinds that act differently with respect to indentation.
2192
2193An `indenting comment line' is a comment line with a blank, tab or
2194nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002195treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002196indenting comment line will be indented like the comment line. All
2197other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002198following the initial `#') are `non-indenting comment lines', and
2199their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200
2201Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002202whenever possible. Non-indenting comment lines are useful in cases
2203like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002204
2205\ta = b # a very wordy single-line comment that ends up being
2206\t #... continued onto another line
2207
2208\tif a == b:
2209##\t\tprint 'panic!' # old code we've `commented out'
2210\t\treturn a
2211
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212Since the `#...' and `##' comment lines have a non-whitespace
2213character following the initial `#', Python mode ignores them when
2214computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002215
2216Continuation Lines and Statements
2217
2218The Python-mode commands generally work on statements instead of on
2219individual lines, where a `statement' is a comment or blank line, or a
2220code line and all of its following continuation lines (if any)
2221considered as a single logical unit. The commands in this mode
2222generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002223statement containing point, even if point happens to be in the middle
2224of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002225
2226
2227@INDENTATION
2228
2229Primarily for entering new code:
2230\t\\[indent-for-tab-command]\t indent line appropriately
2231\t\\[py-newline-and-indent]\t insert newline, then indent
2232\t\\[py-delete-char]\t reduce indentation, or delete single character
2233
2234Primarily for reindenting existing code:
2235\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2236\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2237
2238\t\\[py-indent-region]\t reindent region to match its context
2239\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2240\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2241
2242Unlike most programming languages, Python uses indentation, and only
2243indentation, to specify block structure. Hence the indentation supplied
2244automatically by Python-mode is just an educated guess: only you know
2245the block structure you intend, so only you can supply correct
2246indentation.
2247
2248The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2249the indentation of preceding statements. E.g., assuming
2250py-indent-offset is 4, after you enter
2251\tif a > 0: \\[py-newline-and-indent]
2252the cursor will be moved to the position of the `_' (_ is not a
2253character in the file, it's just used here to indicate the location of
2254the cursor):
2255\tif a > 0:
2256\t _
2257If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2258to
2259\tif a > 0:
2260\t c = d
2261\t _
2262Python-mode cannot know whether that's what you intended, or whether
2263\tif a > 0:
2264\t c = d
2265\t_
2266was your intent. In general, Python-mode either reproduces the
2267indentation of the (closest code or indenting-comment) preceding
2268statement, or adds an extra py-indent-offset blanks if the preceding
2269statement has `:' as its last significant (non-whitespace and non-
2270comment) character. If the suggested indentation is too much, use
2271\\[py-delete-char] to reduce it.
2272
2273Continuation lines are given extra indentation. If you don't like the
2274suggested indentation, change it to something you do like, and Python-
2275mode will strive to indent later lines of the statement in the same way.
2276
2277If a line is a continuation line by virtue of being in an unclosed
2278paren/bracket/brace structure (`list', for short), the suggested
2279indentation depends on whether the current line contains the first item
2280in the list. If it does, it's indented py-indent-offset columns beyond
2281the indentation of the line containing the open bracket. If you don't
2282like that, change it by hand. The remaining items in the list will mimic
2283whatever indentation you give to the first item.
2284
2285If a line is a continuation line because the line preceding it ends with
2286a backslash, the third and following lines of the statement inherit their
2287indentation from the line preceding them. The indentation of the second
2288line in the statement depends on the form of the first (base) line: if
2289the base line is an assignment statement with anything more interesting
2290than the backslash following the leftmost assigning `=', the second line
2291is indented two columns beyond that `='. Else it's indented to two
2292columns beyond the leftmost solid chunk of non-whitespace characters on
2293the base line.
2294
2295Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2296repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2297structure you intend.
2298%c:indent-for-tab-command
2299%c:py-newline-and-indent
2300%c:py-delete-char
2301
2302
2303The next function may be handy when editing code you didn't write:
2304%c:py-guess-indent-offset
2305
2306
2307The remaining `indent' functions apply to a region of Python code. They
2308assume the block structure (equals indentation, in Python) of the region
2309is correct, and alter the indentation in various ways while preserving
2310the block structure:
2311%c:py-indent-region
2312%c:py-shift-region-left
2313%c:py-shift-region-right
2314
2315@MARKING & MANIPULATING REGIONS OF CODE
2316
2317\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002318\\[py-mark-def-or-class]\t mark smallest enclosing def
2319\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002320\\[comment-region]\t comment out region of code
2321\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002323%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002324%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002325
2326@MOVING POINT
2327
2328\\[py-previous-statement]\t move to statement preceding point
2329\\[py-next-statement]\t move to statement following point
2330\\[py-goto-block-up]\t move up to start of current block
2331\\[beginning-of-python-def-or-class]\t move to start of def
2332\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2333\\[end-of-python-def-or-class]\t move to end of def
2334\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2335
2336The first two move to one statement beyond the statement that contains
2337point. A numeric prefix argument tells them to move that many
2338statements instead. Blank lines, comment lines, and continuation lines
2339do not count as `statements' for these commands. So, e.g., you can go
2340to the first code statement in a file by entering
2341\t\\[beginning-of-buffer]\t to move to the top of the file
2342\t\\[py-next-statement]\t to skip over initial comments and blank lines
2343Or do `\\[py-previous-statement]' with a huge prefix argument.
2344%c:py-previous-statement
2345%c:py-next-statement
2346%c:py-goto-block-up
2347%c:beginning-of-python-def-or-class
2348%c:end-of-python-def-or-class
2349
2350@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2351
2352`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2353
2354`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2355overall class and def structure of a module.
2356
2357`\\[back-to-indentation]' moves point to a line's first non-blank character.
2358
2359`\\[indent-relative]' is handy for creating odd indentation.
2360
2361@OTHER EMACS HINTS
2362
2363If you don't like the default value of a variable, change its value to
2364whatever you do like by putting a `setq' line in your .emacs file.
2365E.g., to set the indentation increment to 4, put this line in your
2366.emacs:
2367\t(setq py-indent-offset 4)
2368To see the value of a variable, do `\\[describe-variable]' and enter the variable
2369name at the prompt.
2370
2371When entering a key sequence like `C-c C-n', it is not necessary to
2372release the CONTROL key after doing the `C-c' part -- it suffices to
2373press the CONTROL key, press and release `c' (while still holding down
2374CONTROL), press and release `n' (while still holding down CONTROL), &
2375then release CONTROL.
2376
2377Entering Python mode calls with no arguments the value of the variable
2378`python-mode-hook', if that value exists and is not nil; for backward
2379compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2380the Elisp manual for details.
2381
2382Obscure: When python-mode is first loaded, it looks for all bindings
2383to newline-and-indent in the global keymap, and shadows them with
2384local bindings to py-newline-and-indent."))
2385
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002386
2387;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002388(defvar py-parse-state-re
2389 (concat
2390 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2391 "\\|"
2392 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002393
Barry Warsaw7ae77681994-12-12 20:38:05 +00002394;; returns the parse state at point (see parse-partial-sexp docs)
2395(defun py-parse-state ()
2396 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002397 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002398 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002399 (while (not done)
2400 ;; back up to the first preceding line (if any; else start of
2401 ;; buffer) that begins with a popular Python keyword, or a
2402 ;; non- whitespace and non-comment character. These are good
2403 ;; places to start parsing to see whether where we started is
2404 ;; at a non-zero nesting level. It may be slow for people who
2405 ;; write huge code blocks or huge lists ... tough beans.
2406 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002407 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002408 (beginning-of-line)
2409 (save-excursion
2410 (setq pps (parse-partial-sexp (point) here)))
2411 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002412 (setq done (or (zerop ci)
2413 (not (nth 3 pps))
2414 (bobp)))
2415 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002416 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002417
2418;; if point is at a non-zero nesting level, returns the number of the
2419;; character that opens the smallest enclosing unclosed list; else
2420;; returns nil.
2421(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002422 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002423 (if (zerop (car status))
2424 nil ; not in a nest
2425 (car (cdr status))))) ; char# of open bracket
2426
2427;; t iff preceding line ends with backslash that's not in a comment
2428(defun py-backslash-continuation-line-p ()
2429 (save-excursion
2430 (beginning-of-line)
2431 (and
2432 ;; use a cheap test first to avoid the regexp if possible
2433 ;; use 'eq' because char-after may return nil
2434 (eq (char-after (- (point) 2)) ?\\ )
2435 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002436 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002437 (looking-at py-continued-re))))
2438
2439;; t iff current line is a continuation line
2440(defun py-continuation-line-p ()
2441 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002442 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002443 (or (py-backslash-continuation-line-p)
2444 (py-nesting-level))))
2445
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002446;; go to initial line of current statement; usually this is the line
2447;; we're on, but if we're on the 2nd or following lines of a
2448;; continuation block, we need to go up to the first line of the
2449;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002450;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002451;; Tricky: We want to avoid quadratic-time behavior for long continued
2452;; blocks, whether of the backslash or open-bracket varieties, or a
2453;; mix of the two. The following manages to do that in the usual
2454;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002455(defun py-goto-initial-line ()
2456 (let ( open-bracket-pos )
2457 (while (py-continuation-line-p)
2458 (beginning-of-line)
2459 (if (py-backslash-continuation-line-p)
2460 (while (py-backslash-continuation-line-p)
2461 (forward-line -1))
2462 ;; else zip out of nested brackets/braces/parens
2463 (while (setq open-bracket-pos (py-nesting-level))
2464 (goto-char open-bracket-pos)))))
2465 (beginning-of-line))
2466
2467;; go to point right beyond final line of current statement; usually
2468;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002469;; statement we need to skip over the continuation lines. Tricky:
2470;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002471(defun py-goto-beyond-final-line ()
2472 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002473 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002474 (while (and (py-continuation-line-p)
2475 (not (eobp)))
2476 ;; skip over the backslash flavor
2477 (while (and (py-backslash-continuation-line-p)
2478 (not (eobp)))
2479 (forward-line 1))
2480 ;; if in nest, zip to the end of the nest
2481 (setq state (py-parse-state))
2482 (if (and (not (zerop (car state)))
2483 (not (eobp)))
2484 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002485 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002486 (forward-line 1))))))
2487
2488;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002489;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002490(defun py-statement-opens-block-p ()
2491 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002492 (let ((start (point))
2493 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2494 (searching t)
2495 (answer nil)
2496 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497 (goto-char start)
2498 (while searching
2499 ;; look for a colon with nothing after it except whitespace, and
2500 ;; maybe a comment
2501 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2502 finish t)
2503 (if (eq (point) finish) ; note: no `else' clause; just
2504 ; keep searching if we're not at
2505 ; the end yet
2506 ;; sure looks like it opens a block -- but it might
2507 ;; be in a comment
2508 (progn
2509 (setq searching nil) ; search is done either way
2510 (setq state (parse-partial-sexp start
2511 (match-beginning 0)))
2512 (setq answer (not (nth 4 state)))))
2513 ;; search failed: couldn't find another interesting colon
2514 (setq searching nil)))
2515 answer)))
2516
Barry Warsawf831d811996-07-31 20:42:59 +00002517(defun py-statement-closes-block-p ()
2518 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002519 ;; starts with `return', `raise', `break', `continue', and `pass'.
2520 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002521 (let ((here (point)))
2522 (back-to-indentation)
2523 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002524 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002525 (goto-char here))))
2526
Barry Warsaw7ae77681994-12-12 20:38:05 +00002527;; go to point right beyond final line of block begun by the current
2528;; line. This is the same as where py-goto-beyond-final-line goes
2529;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002530;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531(defun py-goto-beyond-block ()
2532 (if (py-statement-opens-block-p)
2533 (py-mark-block nil 'just-move)
2534 (py-goto-beyond-final-line)))
2535
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002536;; go to start of first statement (not blank or comment or
2537;; continuation line) at or preceding point. returns t if there is
2538;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002539(defun py-goto-statement-at-or-above ()
2540 (py-goto-initial-line)
2541 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002542 ;; skip back over blank & comment lines
2543 ;; note: will skip a blank or comment line that happens to be
2544 ;; a continuation line too
2545 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2546 (progn (py-goto-initial-line) t)
2547 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002548 t))
2549
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002550;; go to start of first statement (not blank or comment or
2551;; continuation line) following the statement containing point returns
2552;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002553(defun py-goto-statement-below ()
2554 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002555 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002556 (py-goto-beyond-final-line)
2557 (while (and
2558 (looking-at py-blank-or-comment-re)
2559 (not (eobp)))
2560 (forward-line 1))
2561 (if (eobp)
2562 (progn (goto-char start) nil)
2563 t)))
2564
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002565;; go to start of statement, at or preceding point, starting with
2566;; keyword KEY. Skips blank lines and non-indenting comments upward
2567;; first. If that statement starts with KEY, done, else go back to
2568;; first enclosing block starting with KEY. If successful, leaves
2569;; point at the start of the KEY line & returns t. Else leaves point
2570;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002571(defun py-go-up-tree-to-keyword (key)
2572 ;; skip blanks and non-indenting #
2573 (py-goto-initial-line)
2574 (while (and
2575 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2576 (zerop (forward-line -1))) ; go back
2577 nil)
2578 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002579 (let* ((re (concat "[ \t]*" key "\\b"))
2580 (case-fold-search nil) ; let* so looking-at sees this
2581 (found (looking-at re))
2582 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002583 (while (not (or found dead))
2584 (condition-case nil ; in case no enclosing block
2585 (py-goto-block-up 'no-mark)
2586 (error (setq dead t)))
2587 (or dead (setq found (looking-at re))))
2588 (beginning-of-line)
2589 found))
2590
2591;; return string in buffer from start of indentation to end of line;
2592;; prefix "..." if leading whitespace was skipped
2593(defun py-suck-up-leading-text ()
2594 (save-excursion
2595 (back-to-indentation)
2596 (concat
2597 (if (bolp) "" "...")
2598 (buffer-substring (point) (progn (end-of-line) (point))))))
2599
2600;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2601;; as a Lisp symbol; return nil if none
2602(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002603 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002604 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2605 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2606 nil)))
2607
Barry Warsawb3e81d51996-09-04 15:12:42 +00002608(defun py-current-defun ()
2609 ;; tell add-log.el how to find the current function/method/variable
2610 (save-excursion
2611 (if (re-search-backward py-defun-start-re nil t)
2612 (or (match-string 3)
2613 (let ((method (match-string 2)))
2614 (if (and (not (zerop (length (match-string 1))))
2615 (re-search-backward py-class-start-re nil t))
2616 (concat (match-string 1) "." method)
2617 method)))
2618 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002619
2620
Barry Warsawfec75d61995-07-05 23:26:15 +00002621(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002622 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002623
Barry Warsaw850437a1995-03-08 21:50:28 +00002624(defun py-version ()
2625 "Echo the current version of `python-mode' in the minibuffer."
2626 (interactive)
2627 (message "Using `python-mode' version %s" py-version)
2628 (py-keep-region-active))
2629
2630;; only works under Emacs 19
2631;(eval-when-compile
2632; (require 'reporter))
2633
2634(defun py-submit-bug-report (enhancement-p)
2635 "Submit via mail a bug report on `python-mode'.
2636With \\[universal-argument] just submit an enhancement request."
2637 (interactive
2638 (list (not (y-or-n-p
2639 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002640 (let ((reporter-prompt-for-summary-p (if enhancement-p
2641 "(Very) brief summary: "
2642 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002643 (require 'reporter)
2644 (reporter-submit-bug-report
2645 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002646 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002647 ;; varlist
2648 (if enhancement-p nil
2649 '(py-python-command
2650 py-indent-offset
2651 py-block-comment-prefix
2652 py-scroll-process-buffer
2653 py-temp-directory
2654 py-beep-if-tab-change))
2655 nil ;pre-hooks
2656 nil ;post-hooks
2657 "Dear Barry,") ;salutation
2658 (if enhancement-p nil
2659 (set-mark (point))
2660 (insert
2661"Please replace this text with a sufficiently large code sample\n\
2662and an exact recipe so that I can reproduce your problem. Failure\n\
2663to do so may mean a greater delay in fixing your bug.\n\n")
2664 (exchange-point-and-mark)
2665 (py-keep-region-active))))
2666
2667
Barry Warsaw47384781997-11-26 05:27:45 +00002668(defun py-kill-emacs-hook ()
2669 (mapcar #'(lambda (filename)
2670 (py-safe (delete-file filename)))
2671 py-file-queue))
2672
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002673;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002674(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002675
2676
2677
2678(provide 'python-mode)
2679;;; python-mode.el ends here