blob: dcb14eec97bf67f83fd0ebaaf45dcf4058dee345 [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
7;; Maintainer: python-mode@python.org
Barry Warsawcfec3591995-03-10 15:58:16 +00008;; Created: Feb 1992
Barry Warsaw7d6b7d31997-08-08 16:19:03 +00009;; Version: 3.0
Barry Warsaw4669d7e1996-03-22 16:13:24 +000010;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000011
Barry Warsawc72c11c1997-08-09 06:42:08 +000012(defconst py-version "3.0"
13 "`python-mode' version number.")
14
Barry Warsawcfec3591995-03-10 15:58:16 +000015;; This software is provided as-is, without express or implied
16;; warranty. Permission to use, copy, modify, distribute or sell this
17;; software, without fee, for any purpose and by any individual or
18;; organization, is hereby granted, provided that the above copyright
19;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000020
21;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000022
Barry Warsaw7b0f5681995-03-08 21:33:04 +000023;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000024;; by Tim Peters after an original idea by Michael A. Guravage. Tim
25;; subsequently left the net; in 1995, Barry Warsaw inherited the
26;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000027
Barry Warsawaffc0ca1997-11-03 16:59:38 +000028;; Note: this version of python-mode.el is no longer compatible with
29;; Emacs 18. For a gabazillion reasons, I highly recommend upgrading
30;; to X/Emacs 19 or X/Emacs 20. For older versions of the 19 series,
31;; you may need to acquire the Custom library.
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,
35;; but it is compatible with the EOL 19 series and current 20 series
36;; Emacsen. By default, in XEmacs when you visit a .py file, it is
37;; put in Python mode. In Emacs, you need to add the following to
38;; your .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)
82
Barry Warsaw7b0f5681995-03-08 21:33:04 +000083
84;; user definable variables
85;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000086
Barry Warsawc72c11c1997-08-09 06:42:08 +000087(defgroup python nil
88 "Support for the Python programming language, <http://www.python.org/>"
89 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +000090
Barry Warsawc72c11c1997-08-09 06:42:08 +000091(defcustom py-python-command "python"
92 "*Shell command used to start Python interpreter."
93 :type 'string
94 :group 'python)
95
96(defcustom py-indent-offset 4
97 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +000098Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +000099when you're editing someone else's Python code."
100 :type 'integer
101 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000102
Barry Warsawc72c11c1997-08-09 06:42:08 +0000103(defcustom py-align-multiline-strings-p t
104 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000105When this flag is non-nil, continuation lines are lined up under the
106preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000107lines are aligned to column zero."
108 :type '(choice (const :tag "Align under preceding line" t)
109 (const :tag "Align to column zero" nil))
110 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000111
Barry Warsawc72c11c1997-08-09 06:42:08 +0000112(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000113 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000114This should follow the convention for non-indenting comment lines so
115that the indentation commands won't get confused (i.e., the string
116should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000117`...' is arbitrary)."
118 :type 'string
119 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000120
Barry Warsawc72c11c1997-08-09 06:42:08 +0000121(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000122 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000123
Barry Warsaw6d627751996-03-06 18:41:38 +0000124When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000125if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000126
127When t, lines that begin with a single `#' are a hint to subsequent
128line indentation. If the previous line is such a comment line (as
129opposed to one that starts with `py-block-comment-prefix'), then it's
130indentation is used as a hint for this line's indentation. Lines that
131begin with `py-block-comment-prefix' are ignored for indentation
132purposes.
133
134When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000135indentation hints, unless the comment character is in column zero."
136 :type '(choice
137 (const :tag "Skip all comment lines (fast)" nil)
138 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000139 (const :tag "Single # `sets' indentation except at column zero"
140 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000141 )
142 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000143
Barry Warsawc72c11c1997-08-09 06:42:08 +0000144(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000145 "*Scroll Python process buffer as output arrives.
146If nil, the Python process buffer acts, with respect to scrolling, like
147Shell-mode buffers normally act. This is surprisingly complicated and
148so won't be explained here; in fact, you can't get the whole story
149without studying the Emacs C code.
150
151If non-nil, the behavior is different in two respects (which are
152slightly inaccurate in the interest of brevity):
153
154 - If the buffer is in a window, and you left point at its end, the
155 window will scroll as new output arrives, and point will move to the
156 buffer's end, even if the window is not the selected window (that
157 being the one the cursor is in). The usual behavior for shell-mode
158 windows is not to scroll, and to leave point where it was, if the
159 buffer is in a window other than the selected window.
160
161 - If the buffer is not visible in any window, and you left point at
162 its end, the buffer will be popped into a window as soon as more
163 output arrives. This is handy if you have a long-running
164 computation and don't want to tie up screen area waiting for the
165 output. The usual behavior for a shell-mode buffer is to stay
166 invisible until you explicitly visit it.
167
168Note the `and if you left point at its end' clauses in both of the
169above: you can `turn off' the special behaviors while output is in
170progress, by visiting the Python buffer and moving point to anywhere
171besides the end. Then the buffer won't scroll, point will remain where
172you leave it, and if you hide the buffer it will stay hidden until you
173visit it again. You can enable and disable the special behaviors as
174often as you like, while output is in progress, by (respectively) moving
175point to, or away from, the end of the buffer.
176
177Warning: If you expect a large amount of output, you'll probably be
178happier setting this option to nil.
179
180Obscure: `End of buffer' above should really say `at or beyond the
181process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000182told <grin>."
183 :type 'boolean
184 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000185
Barry Warsaw516b6201997-08-09 06:43:20 +0000186(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000187 (let ((ok '(lambda (x)
188 (and x
189 (setq x (expand-file-name x)) ; always true
190 (file-directory-p x)
191 (file-writable-p x)
192 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000193 (or (funcall ok (getenv "TMPDIR"))
194 (funcall ok "/usr/tmp")
195 (funcall ok "/tmp")
196 (funcall ok ".")
197 (error
198 "Couldn't find a usable temp directory -- set py-temp-directory")))
199 "*Directory used for temp files created by a *Python* process.
200By default, the first directory from this list that exists and that you
201can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000202/usr/tmp, /tmp, or the current directory."
203 :type 'string
204 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000205
Barry Warsaw516b6201997-08-09 06:43:20 +0000206(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000207 "*Ring the bell if tab-width is changed.
208If a comment of the form
209
210 \t# vi:set tabsize=<number>:
211
212is found before the first code line when the file is entered, and the
213current value of (the general Emacs variable) `tab-width' does not
214equal <number>, `tab-width' is set to <number>, a message saying so is
215displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000216the Emacs bell is also rung as a warning."
217 :type 'boolean
218 :group 'python)
219
220
221;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
222;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
223
Barry Warsawc12c62e1997-09-04 04:18:07 +0000224(defconst py-emacs-features ()
225 "A list of features extant in the Emacs you are using.
226There are many flavors of Emacs out there, each with different
227features supporting those needed by CC Mode. Here's the current
228supported list, along with the values for this variable:
229
230 XEmacs 19: ()
231 XEmacs 20: ()
232 Emacs 19: ()
233")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000234
Barry Warsawfb07f401997-02-24 03:37:22 +0000235(defvar python-font-lock-keywords
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000236 (let* ((keywords '("and" "assert" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000237 "continue" "def" "del" "elif"
238 "else:" "except" "except:" "exec"
239 "finally:" "for" "from" "global"
240 "if" "import" "in" "is"
241 "lambda" "not" "or" "pass"
242 "print" "raise" "return" "try:"
243 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000244 ))
245 (kwregex (mapconcat 'identity keywords "\\|")))
246 (list
247 ;; keywords not at beginning of line
248 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
249 ;; keywords at beginning of line. i don't think regexps are
250 ;; powerful enough to handle these two cases in one regexp.
251 ;; prove me wrong!
252 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
253 ;; classes
254 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
255 1 font-lock-type-face)
256 ;; functions
257 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
258 1 font-lock-function-name-face)
259 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000260 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000261(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
262
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000263
Barry Warsaw81437461996-08-01 19:48:02 +0000264(defvar imenu-example--python-show-method-args-p nil
265 "*Controls echoing of arguments of functions & methods in the imenu buffer.
266When non-nil, arguments are printed.")
267
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000268(make-variable-buffer-local 'py-indent-offset)
269
Barry Warsaw7ae77681994-12-12 20:38:05 +0000270;; have to bind py-file-queue before installing the kill-emacs hook
271(defvar py-file-queue nil
272 "Queue of Python temp files awaiting execution.
273Currently-active file is at the head of the list.")
274
Barry Warsawc72c11c1997-08-09 06:42:08 +0000275(defvar py-delete-function 'backward-delete-char-untabify
276 "*Function called by `py-delete-char' when deleting characters.")
277
278(defvar py-backspace-function 'backward-delete-char-untabify
279 "*Function called by `py-backspace-command' when deleting characters.")
280
281
282;; Constants
283
284;; Regexp matching a Python string literal
285(defconst py-stringlit-re
286 (concat
287 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
288 "\\|" ; or
289 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
290
291;; Regexp matching Python lines that are continued via backslash.
292;; This is tricky because a trailing backslash does not mean
293;; continuation if it's in a comment
294(defconst py-continued-re
295 (concat
296 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
297 "\\\\$"))
298
299;; Regexp matching blank or comment lines.
300(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
301
302;; Regexp matching clauses to be outdented one level.
303(defconst py-outdent-re
304 (concat "\\(" (mapconcat 'identity
305 '("else:"
306 "except\\(\\s +.*\\)?:"
307 "finally:"
308 "elif\\s +.*:")
309 "\\|")
310 "\\)"))
311
312
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000313;; Regexp matching keywords which typically close a block
314(defconst py-block-closing-keywords-re
315 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
316
Barry Warsawc72c11c1997-08-09 06:42:08 +0000317;; Regexp matching lines to not outdent after.
318(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000319 (concat
320 "\\("
321 (mapconcat 'identity
322 (list "try:"
323 "except\\(\\s +.*\\)?:"
324 "while\\s +.*:"
325 "for\\s +.*:"
326 "if\\s +.*:"
327 "elif\\s +.*:"
328 (concat py-block-closing-keywords-re "[ \t\n]")
329 )
330 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000331 "\\)"))
332
333;; Regexp matching a function, method or variable assignment. If you
334;; change this, you probably have to change `py-current-defun' as
335;; well. This is only used by `py-current-defun' to find the name for
336;; add-log.el.
337(defvar py-defun-start-re
338 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
339
340;; Regexp for finding a class name. If you change this, you probably
341;; have to change `py-current-defun' as well. This is only used by
342;; `py-current-defun' to find the name for add-log.el.
343(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
344
345
346
347;; Utilities
348
349(defmacro py-safe (&rest body)
350 ;; safely execute BODY, return nil if an error occurred
351 (` (condition-case nil
352 (progn (,@ body))
353 (error nil))))
354
355(defsubst py-keep-region-active ()
356 ;; Do whatever is necessary to keep the region active in XEmacs.
357 ;; Ignore byte-compiler warnings you might see. Also note that
358 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
359 ;; to take explicit action.
360 (and (boundp 'zmacs-region-stays)
361 (setq zmacs-region-stays t)))
362
363
364;; Major mode boilerplate
365
Barry Warsaw7ae77681994-12-12 20:38:05 +0000366;; define a mode-specific abbrev table for those who use such things
367(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000368 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000369(define-abbrev-table 'python-mode-abbrev-table nil)
370
Barry Warsaw7ae77681994-12-12 20:38:05 +0000371(defvar python-mode-hook nil
372 "*Hook called by `python-mode'.")
373
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000374;; in previous version of python-mode.el, the hook was incorrectly
375;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000376(and (fboundp 'make-obsolete-variable)
377 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
378
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000379(defvar py-mode-map ()
380 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000381(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000382 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000383 (setq py-mode-map (make-sparse-keymap))
384
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000385 ;; shadow global bindings for newline-and-indent w/ the py- version.
386 ;; BAW - this is extremely bad form, but I'm not going to change it
387 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000388 (mapcar (function (lambda (key)
389 (define-key
390 py-mode-map key 'py-newline-and-indent)))
391 (where-is-internal 'newline-and-indent))
392
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393 ;; BAW - you could do it this way, but its not considered proper
394 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000395 (mapcar (function
396 (lambda (x)
397 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000398 '((":" . py-electric-colon)
399 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000400 ("\C-c|" . py-execute-region)
401 ("\C-c!" . py-shell)
402 ("\177" . py-delete-char)
403 ("\n" . py-newline-and-indent)
404 ("\C-c:" . py-guess-indent-offset)
405 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000406 ("\C-c\C-l" . py-shift-region-left)
407 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000408 ("\C-c<" . py-shift-region-left)
409 ("\C-c>" . py-shift-region-right)
410 ("\C-c\C-n" . py-next-statement)
411 ("\C-c\C-p" . py-previous-statement)
412 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000413 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000414 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000415 ("\C-c?" . py-describe-mode)
416 ("\C-c\C-hm" . py-describe-mode)
417 ("\e\C-a" . beginning-of-python-def-or-class)
418 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000419 ( "\e\C-h" . mark-python-def-or-class)))
420 ;; should do all keybindings this way
421 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
422 (define-key py-mode-map "\C-c\C-v" 'py-version)
423 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000424
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000425(defvar py-mode-syntax-table nil
426 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000427(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000428 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000429 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000430 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
431 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
432 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
433 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
434 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
435 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
436 ;; Add operator symbols misassigned in the std table
437 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
438 (modify-syntax-entry ?\% "." py-mode-syntax-table)
439 (modify-syntax-entry ?\& "." py-mode-syntax-table)
440 (modify-syntax-entry ?\* "." py-mode-syntax-table)
441 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
442 (modify-syntax-entry ?\- "." py-mode-syntax-table)
443 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
444 (modify-syntax-entry ?\< "." py-mode-syntax-table)
445 (modify-syntax-entry ?\= "." py-mode-syntax-table)
446 (modify-syntax-entry ?\> "." py-mode-syntax-table)
447 (modify-syntax-entry ?\| "." py-mode-syntax-table)
448 ;; For historical reasons, underscore is word class instead of
449 ;; symbol class. GNU conventions say it should be symbol class, but
450 ;; there's a natural conflict between what major mode authors want
451 ;; and what users expect from `forward-word' and `backward-word'.
452 ;; Guido and I have hashed this out and have decided to keep
453 ;; underscore in word class. If you're tempted to change it, try
454 ;; binding M-f and M-b to py-forward-into-nomenclature and
455 ;; py-backward-into-nomenclature instead.
456 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
457 ;; Both single quote and double quote are string delimiters
458 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
459 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
460 ;; backquote is open and close paren
461 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
462 ;; comment delimiters
463 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
464 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
465 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000466
Barry Warsawb3e81d51996-09-04 15:12:42 +0000467
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000468
Barry Warsaw42f707f1996-07-29 21:05:05 +0000469;; Menu definitions, only relevent if you have the easymenu.el package
470;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000471(defvar py-menu nil
472 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000473This menu will get created automatically if you have the `easymenu'
474package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000475
Barry Warsawc72c11c1997-08-09 06:42:08 +0000476(and (py-safe (require 'easymenu) t)
477 (easy-menu-define
478 py-menu py-mode-map "Python Mode menu"
479 '("Python"
480 ["Comment Out Region" py-comment-region (mark)]
481 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
482 "-"
483 ["Mark current block" py-mark-block t]
484 ["Mark current def" mark-python-def-or-class t]
485 ["Mark current class" (mark-python-def-or-class t) t]
486 "-"
487 ["Shift region left" py-shift-region-left (mark)]
488 ["Shift region right" py-shift-region-right (mark)]
489 "-"
490 ["Execute buffer" py-execute-buffer t]
491 ["Execute region" py-execute-region (mark)]
492 ["Start interpreter..." py-shell t]
493 "-"
494 ["Go to start of block" py-goto-block-up t]
495 ["Go to start of class" (beginning-of-python-def-or-class t) t]
496 ["Move to end of class" (end-of-python-def-or-class t) t]
497 ["Move to start of def" beginning-of-python-def-or-class t]
498 ["Move to end of def" end-of-python-def-or-class t]
499 "-"
500 ["Describe mode" py-describe-mode t]
501 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000502
Barry Warsaw81437461996-08-01 19:48:02 +0000503
504
505;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
506(defvar imenu-example--python-class-regexp
507 (concat ; <<classes>>
508 "\\(" ;
509 "^[ \t]*" ; newline and maybe whitespace
510 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
511 ; possibly multiple superclasses
512 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
513 "[ \t]*:" ; and the final :
514 "\\)" ; >>classes<<
515 )
516 "Regexp for Python classes for use with the imenu package."
517 )
518
519(defvar imenu-example--python-method-regexp
520 (concat ; <<methods and functions>>
521 "\\(" ;
522 "^[ \t]*" ; new line and maybe whitespace
523 "\\(def[ \t]+" ; function definitions start with def
524 "\\([a-zA-Z0-9_]+\\)" ; name is here
525 ; function arguments...
526 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
527 "\\)" ; end of def
528 "[ \t]*:" ; and then the :
529 "\\)" ; >>methods and functions<<
530 )
531 "Regexp for Python methods/functions for use with the imenu package."
532 )
533
534(defvar imenu-example--python-method-no-arg-parens '(2 8)
535 "Indicies into groups of the Python regexp for use with imenu.
536
537Using these values will result in smaller imenu lists, as arguments to
538functions are not listed.
539
540See the variable `imenu-example--python-show-method-args-p' for more
541information.")
542
543(defvar imenu-example--python-method-arg-parens '(2 7)
544 "Indicies into groups of the Python regexp for use with imenu.
545Using these values will result in large imenu lists, as arguments to
546functions are listed.
547
548See the variable `imenu-example--python-show-method-args-p' for more
549information.")
550
551;; Note that in this format, this variable can still be used with the
552;; imenu--generic-function. Otherwise, there is no real reason to have
553;; it.
554(defvar imenu-example--generic-python-expression
555 (cons
556 (concat
557 imenu-example--python-class-regexp
558 "\\|" ; or...
559 imenu-example--python-method-regexp
560 )
561 imenu-example--python-method-no-arg-parens)
562 "Generic Python expression which may be used directly with imenu.
563Used by setting the variable `imenu-generic-expression' to this value.
564Also, see the function \\[imenu-example--create-python-index] for a
565better alternative for finding the index.")
566
567;; These next two variables are used when searching for the python
568;; class/definitions. Just saving some time in accessing the
569;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000570(defvar imenu-example--python-generic-regexp nil)
571(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000572
573
574;;;###autoload
575(eval-when-compile
576 ;; Imenu isn't used in XEmacs, so just ignore load errors
577 (condition-case ()
578 (progn
579 (require 'cl)
580 (require 'imenu))
581 (error nil)))
582
583(defun imenu-example--create-python-index ()
584 "Python interface function for imenu package.
585Finds all python classes and functions/methods. Calls function
586\\[imenu-example--create-python-index-engine]. See that function for
587the details of how this works."
588 (setq imenu-example--python-generic-regexp
589 (car imenu-example--generic-python-expression))
590 (setq imenu-example--python-generic-parens
591 (if imenu-example--python-show-method-args-p
592 imenu-example--python-method-arg-parens
593 imenu-example--python-method-no-arg-parens))
594 (goto-char (point-min))
595 (imenu-example--create-python-index-engine nil))
596
597(defun imenu-example--create-python-index-engine (&optional start-indent)
598 "Function for finding imenu definitions in Python.
599
600Finds all definitions (classes, methods, or functions) in a Python
601file for the imenu package.
602
603Returns a possibly nested alist of the form
604
605 (INDEX-NAME . INDEX-POSITION)
606
607The second element of the alist may be an alist, producing a nested
608list as in
609
610 (INDEX-NAME . INDEX-ALIST)
611
612This function should not be called directly, as it calls itself
613recursively and requires some setup. Rather this is the engine for
614the function \\[imenu-example--create-python-index].
615
616It works recursively by looking for all definitions at the current
617indention level. When it finds one, it adds it to the alist. If it
618finds a definition at a greater indentation level, it removes the
619previous definition from the alist. In it's place it adds all
620definitions found at the next indentation level. When it finds a
621definition that is less indented then the current level, it retuns the
622alist it has created thus far.
623
624The optional argument START-INDENT indicates the starting indentation
625at which to continue looking for Python classes, methods, or
626functions. If this is not supplied, the function uses the indentation
627of the first definition found."
628 (let ((index-alist '())
629 (sub-method-alist '())
630 looking-p
631 def-name prev-name
632 cur-indent def-pos
633 (class-paren (first imenu-example--python-generic-parens))
634 (def-paren (second imenu-example--python-generic-parens)))
635 (setq looking-p
636 (re-search-forward imenu-example--python-generic-regexp
637 (point-max) t))
638 (while looking-p
639 (save-excursion
640 ;; used to set def-name to this value but generic-extract-name is
641 ;; new to imenu-1.14. this way it still works with imenu-1.11
642 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
643 (let ((cur-paren (if (match-beginning class-paren)
644 class-paren def-paren)))
645 (setq def-name
646 (buffer-substring (match-beginning cur-paren)
647 (match-end cur-paren))))
648 (beginning-of-line)
649 (setq cur-indent (current-indentation)))
650
651 ;; HACK: want to go to the next correct definition location. we
652 ;; explicitly list them here. would be better to have them in a
653 ;; list.
654 (setq def-pos
655 (or (match-beginning class-paren)
656 (match-beginning def-paren)))
657
658 ;; if we don't have a starting indent level, take this one
659 (or start-indent
660 (setq start-indent cur-indent))
661
662 ;; if we don't have class name yet, take this one
663 (or prev-name
664 (setq prev-name def-name))
665
666 ;; what level is the next definition on? must be same, deeper
667 ;; or shallower indentation
668 (cond
669 ;; at the same indent level, add it to the list...
670 ((= start-indent cur-indent)
671
672 ;; if we don't have push, use the following...
673 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
674 (push (cons def-name def-pos) index-alist))
675
676 ;; deeper indented expression, recur...
677 ((< start-indent cur-indent)
678
679 ;; the point is currently on the expression we're supposed to
680 ;; start on, so go back to the last expression. The recursive
681 ;; call will find this place again and add it to the correct
682 ;; list
683 (re-search-backward imenu-example--python-generic-regexp
684 (point-min) 'move)
685 (setq sub-method-alist (imenu-example--create-python-index-engine
686 cur-indent))
687
688 (if sub-method-alist
689 ;; we put the last element on the index-alist on the start
690 ;; of the submethod alist so the user can still get to it.
691 (let ((save-elmt (pop index-alist)))
692 (push (cons (imenu-create-submenu-name prev-name)
693 (cons save-elmt sub-method-alist))
694 index-alist))))
695
696 ;; found less indented expression, we're done.
697 (t
698 (setq looking-p nil)
699 (re-search-backward imenu-example--python-generic-regexp
700 (point-min) t)))
701 (setq prev-name def-name)
702 (and looking-p
703 (setq looking-p
704 (re-search-forward imenu-example--python-generic-regexp
705 (point-max) 'move))))
706 (nreverse index-alist)))
707
Barry Warsaw42f707f1996-07-29 21:05:05 +0000708
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000709;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000710(defun python-mode ()
711 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000712To submit a problem report, enter `\\[py-submit-bug-report]' from a
713`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
714documentation. To see what version of `python-mode' you are running,
715enter `\\[py-version]'.
716
717This mode knows about Python indentation, tokens, comments and
718continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000719
720COMMANDS
721\\{py-mode-map}
722VARIABLES
723
Barry Warsaw42f707f1996-07-29 21:05:05 +0000724py-indent-offset\t\tindentation increment
725py-block-comment-prefix\t\tcomment string used by comment-region
726py-python-command\t\tshell command to invoke Python interpreter
727py-scroll-process-buffer\t\talways scroll Python process buffer
728py-temp-directory\t\tdirectory used for temp files (if needed)
729py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000730 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000731 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000732 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000733 (make-local-variable 'font-lock-defaults)
734 (make-local-variable 'paragraph-separate)
735 (make-local-variable 'paragraph-start)
736 (make-local-variable 'require-final-newline)
737 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000738 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000739 (make-local-variable 'comment-start-skip)
740 (make-local-variable 'comment-column)
741 (make-local-variable 'indent-region-function)
742 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000743 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000744 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000745 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000746 (setq major-mode 'python-mode
747 mode-name "Python"
748 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000749 paragraph-separate "^[ \t]*$"
750 paragraph-start "^[ \t]*$"
751 require-final-newline t
752 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000753 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000754 comment-start-skip "# *"
755 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000756 indent-region-function 'py-indent-region
757 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000758 ;; tell add-log.el how to find the current function/method/variable
759 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000760 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000761 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000762 ;; add the menu
763 (if py-menu
764 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000765 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000766 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000767 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000768 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000769 ;;
770 ;; not sure where the magic comment has to be; to save time
771 ;; searching for a rarity, we give up if it's not found prior to the
772 ;; first executable statement.
773 ;;
774 ;; BAW - on first glance, this seems like complete hackery. Why was
775 ;; this necessary, and is it still necessary?
776 (let ((case-fold-search nil)
777 (start (point))
778 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000779 (if (re-search-forward
780 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
781 (prog2 (py-next-statement 1) (point) (goto-char 1))
782 t)
783 (progn
784 (setq new-tab-width
785 (string-to-int
786 (buffer-substring (match-beginning 1) (match-end 1))))
787 (if (= tab-width new-tab-width)
788 nil
789 (setq tab-width new-tab-width)
790 (message "Caution: tab-width changed to %d" new-tab-width)
791 (if py-beep-if-tab-change (beep)))))
792 (goto-char start))
793
Barry Warsaw755c6711996-08-01 20:02:55 +0000794 ;; install imenu
795 (setq imenu-create-index-function
796 (function imenu-example--create-python-index))
797 (if (fboundp 'imenu-add-to-menubar)
798 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
799
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000800 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000801 (if python-mode-hook
802 (run-hooks 'python-mode-hook)
803 (run-hooks 'py-mode-hook)))
804
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000805
Barry Warsawb91b7431995-03-14 15:55:20 +0000806;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000807(defun py-outdent-p ()
808 ;; returns non-nil if the current line should outdent one level
809 (save-excursion
810 (and (progn (back-to-indentation)
811 (looking-at py-outdent-re))
812 (progn (backward-to-indentation 1)
813 (while (or (looking-at py-blank-or-comment-re)
814 (bobp))
815 (backward-to-indentation 1))
816 (not (looking-at py-no-outdent-re)))
817 )))
818
Barry Warsawb91b7431995-03-14 15:55:20 +0000819(defun py-electric-colon (arg)
820 "Insert a colon.
821In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000822argument is provided, that many colons are inserted non-electrically.
823Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000824 (interactive "P")
825 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000826 ;; are we in a string or comment?
827 (if (save-excursion
828 (let ((pps (parse-partial-sexp (save-excursion
829 (beginning-of-python-def-or-class)
830 (point))
831 (point))))
832 (not (or (nth 3 pps) (nth 4 pps)))))
833 (save-excursion
834 (let ((here (point))
835 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000836 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000837 (if (and (not arg)
838 (py-outdent-p)
839 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000840 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000841 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000842 )
843 (setq outdent py-indent-offset))
844 ;; Don't indent, only outdent. This assumes that any lines that
845 ;; are already outdented relative to py-compute-indentation were
846 ;; put there on purpose. Its highly annoying to have `:' indent
847 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
848 ;; there a better way to determine this???
849 (if (< (current-indentation) indent) nil
850 (goto-char here)
851 (beginning-of-line)
852 (delete-horizontal-space)
853 (indent-to (- indent outdent))
854 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000855
856
Barry Warsaw7ae77681994-12-12 20:38:05 +0000857;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000858;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000859(defun py-shell ()
860 "Start an interactive Python interpreter in another window.
861This is like Shell mode, except that Python is running in the window
862instead of a shell. See the `Interactive Shell' and `Shell Mode'
863sections of the Emacs manual for details, especially for the key
864bindings active in the `*Python*' buffer.
865
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000866See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000867behavior in the process window.
868
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000869Warning: Don't use an interactive Python if you change sys.ps1 or
870sys.ps2 from their default values, or if you're running code that
871prints `>>> ' or `... ' at the start of a line. `python-mode' can't
872distinguish your output from Python's output, and assumes that `>>> '
873at the start of a line is a prompt from Python. Similarly, the Emacs
874Shell mode code assumes that both `>>> ' and `... ' at the start of a
875line are Python prompts. Bad things can happen if you fool either
876mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000877
878Warning: If you do any editing *in* the process buffer *while* the
879buffer is accepting output from Python, do NOT attempt to `undo' the
880changes. Some of the output (nowhere near the parts you changed!) may
881be lost if you do. This appears to be an Emacs bug, an unfortunate
882interaction between undo and process filters; the same problem exists in
883non-Python process buffers using the default (Emacs-supplied) process
884filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000885 ;; BAW - should undo be disabled in the python process buffer, if
886 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887 (interactive)
Barry Warsawe6648961997-07-10 15:58:36 +0000888 (require 'comint)
889 (switch-to-buffer-other-window (make-comint "Python" py-python-command))
890 (make-local-variable 'comint-prompt-regexp)
891 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000892 (set-process-filter (get-buffer-process (current-buffer)) nil)
Barry Warsawe6648961997-07-10 15:58:36 +0000893 (set-syntax-table py-mode-syntax-table)
894 (local-set-key [tab] 'self-insert-command))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000895
896(defun py-execute-region (start end)
897 "Send the region between START and END to a Python interpreter.
898If there is a *Python* process it is used.
899
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000900Hint: If you want to execute part of a Python file several times
901\(e.g., perhaps you're developing a function and want to flesh it out
902a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
903the region of interest, and send the code to a *Python* process via
904`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000905
906Following are subtleties to note when using a *Python* process:
907
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000908If a *Python* process is used, the region is copied into a temporary
909file (in directory `py-temp-directory'), and an `execfile' command is
910sent to Python naming that file. If you send regions faster than
911Python can execute them, `python-mode' will save them into distinct
912temp files, and execute the next one in the queue the next time it
913sees a `>>> ' prompt from Python. Each time this happens, the process
914buffer is popped into a window (if it's not already in some window) so
915you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918
919is inserted at the end.
920
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000921Caution: No more than 26 regions can be pending at any given time.
922This limit is (indirectly) inherited from libc's mktemp(3).
923`python-mode' does not try to protect you from exceeding the limit.
924It's extremely unlikely that you'll get anywhere close to the limit in
925practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000926
927See the `\\[py-shell]' docs for additional warnings."
928 (interactive "r")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000929 (or (< start end)
930 (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000931 (let ((pyproc (get-process "Python"))
932 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000933 (if (null pyproc)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000934 (let ((outbuf "*Python Output*"))
935 (shell-command-on-region start end py-python-command outbuf)
936 (save-excursion
937 (set-buffer outbuf)
938 ;; TBD: ???
939 (goto-char (point-max))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940 ;; else feed it thru a temp file
941 (setq fname (py-make-temp-name))
942 (write-region start end fname nil 'no-msg)
943 (setq py-file-queue (append py-file-queue (list fname)))
944 (if (cdr py-file-queue)
945 (message "File %s queued for execution" fname)
946 ;; else
947 (py-execute-file pyproc fname)))))
948
949(defun py-execute-file (pyproc fname)
950 (py-append-to-process-buffer
951 pyproc
952 (format "## working on region in file %s ...\n" fname))
953 (process-send-string pyproc (format "execfile('%s')\n" fname)))
954
955(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000956 (let ((curbuf (current-buffer))
957 (pbuf (process-buffer pyproc))
958 (pmark (process-mark pyproc))
959 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
961 ;; make sure we switch to a different buffer at least once. if we
962 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000963 ;; window, and point is before the end, and lots of output is
964 ;; coming at a fast pace, then (a) simple cursor-movement commands
965 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
966 ;; to have a visible effect (the window just doesn't get updated,
967 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
968 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000969 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000970 ;; #b makes no sense to me at all. #a almost makes sense: unless
971 ;; we actually change buffers, set_buffer_internal in buffer.c
972 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
973 ;; seems to make the Emacs command loop reluctant to update the
974 ;; display. Perhaps the default process filter in process.c's
975 ;; read_process_output has update_mode_lines++ for a similar
976 ;; reason? beats me ...
977
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000978 (unwind-protect
979 ;; make sure current buffer is restored
980 ;; BAW - we want to check to see if this still applies
981 (progn
982 ;; mysterious ugly hack
983 (if (eq curbuf pbuf)
984 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000985
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000986 (set-buffer pbuf)
987 (let* ((start (point))
988 (goback (< start pmark))
989 (goend (and (not goback) (= start (point-max))))
990 (buffer-read-only nil))
991 (goto-char pmark)
992 (insert string)
993 (move-marker pmark (point))
994 (setq file-finished
995 (and py-file-queue
996 (equal ">>> "
997 (buffer-substring
998 (prog2 (beginning-of-line) (point)
999 (goto-char pmark))
1000 (point)))))
1001 (if goback (goto-char start)
1002 ;; else
1003 (if py-scroll-process-buffer
1004 (let* ((pop-up-windows t)
1005 (pwin (display-buffer pbuf)))
1006 (set-window-point pwin (point)))))
1007 (set-buffer curbuf)
1008 (if file-finished
1009 (progn
1010 (py-delete-file-silently (car py-file-queue))
1011 (setq py-file-queue (cdr py-file-queue))
1012 (if py-file-queue
1013 (py-execute-file pyproc (car py-file-queue)))))
1014 (and goend
1015 (progn (set-buffer pbuf)
1016 (goto-char (point-max))))
1017 ))
1018 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001019
1020(defun py-execute-buffer ()
1021 "Send the contents of the buffer to a Python interpreter.
1022If there is a *Python* process buffer it is used. If a clipping
1023restriction is in effect, only the accessible portion of the buffer is
1024sent. A trailing newline will be supplied if needed.
1025
1026See the `\\[py-execute-region]' docs for an account of some subtleties."
1027 (interactive)
1028 (py-execute-region (point-min) (point-max)))
1029
1030
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001031
1032;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001033(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001034 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001035
Barry Warsaw7ae77681994-12-12 20:38:05 +00001036If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001037Deletion is performed by calling the function in `py-delete-function'
1038with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001039
1040Else if point is at the leftmost non-blank character of a line that is
1041neither a continuation line nor a non-indenting comment line, or if
1042point is at the end of a blank line, reduces the indentation to match
1043that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001044opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001045of where you are. With numeric count, outdents that many blocks (but
1046not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001047
1048Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001049needed so that only a single column position is deleted. Numeric
1050argument delets that many characters."
1051 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052 (if (or (/= (current-indentation) (current-column))
1053 (bolp)
1054 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001055 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001056 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001057 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001058 ;; else indent the same as the colon line that opened the block
1059
1060 ;; force non-blank so py-goto-block-up doesn't ignore it
1061 (insert-char ?* 1)
1062 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001063 (let ((base-indent 0) ; indentation of base line
1064 (base-text "") ; and text of base line
1065 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001066 (save-excursion
1067 (while (< 0 count)
1068 (condition-case nil ; in case no enclosing block
1069 (progn
1070 (py-goto-block-up 'no-mark)
1071 (setq base-indent (current-indentation)
1072 base-text (py-suck-up-leading-text)
1073 base-found-p t))
1074 (error nil))
1075 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (delete-char 1) ; toss the dummy character
1077 (delete-horizontal-space)
1078 (indent-to base-indent)
1079 (if base-found-p
1080 (message "Closes block: %s" base-text)))))
1081
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001082;; required for pending-del and delsel modes
1083(put 'py-delete-char 'delete-selection 'supersede)
1084(put 'py-delete-char 'pending-delete 'supersede)
1085
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001086(defun py-indent-line (&optional arg)
1087 "Fix the indentation of the current line according to Python rules.
1088With \\[universal-argument], ignore outdenting rules for block
1089closing statements (e.g. return, raise, break, continue, pass)
1090
1091This function is normally bound to `indent-line-function' so
1092\\[indent-for-tab-command] will call it."
1093 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094 (let* ((ci (current-indentation))
1095 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001096 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001097 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001098 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001099 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 (if (/= ci need)
1101 (save-excursion
1102 (beginning-of-line)
1103 (delete-horizontal-space)
1104 (indent-to need)))
1105 (if move-to-indentation-p (back-to-indentation))))
1106
1107(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001108 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001109This is just `strives to' because correct indentation can't be computed
1110from scratch for Python code. In general, deletes the whitespace before
1111point, inserts a newline, and takes an educated guess as to how you want
1112the new line indented."
1113 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001114 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115 (if (< ci (current-column)) ; if point beyond indentation
1116 (newline-and-indent)
1117 ;; else try to act like newline-and-indent "normally" acts
1118 (beginning-of-line)
1119 (insert-char ?\n 1)
1120 (move-to-column ci))))
1121
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001122(defun py-compute-indentation (honor-block-close-p)
1123 ;; implements all the rules for indentation computation. when
1124 ;; honor-block-close-p is non-nil, statements such as return, raise,
1125 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001126 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001127 (let ((pps (parse-partial-sexp (save-excursion
1128 (beginning-of-python-def-or-class)
1129 (point))
1130 (point))))
1131 (beginning-of-line)
1132 (cond
1133 ;; are we inside a string or comment?
1134 ((or (nth 3 pps) (nth 4 pps))
1135 (save-excursion
1136 (if (not py-align-multiline-strings-p) 0
1137 ;; skip back over blank & non-indenting comment lines
1138 ;; note: will skip a blank or non-indenting comment line
1139 ;; that happens to be a continuation line too
1140 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1141 (back-to-indentation)
1142 (current-column))))
1143 ;; are we on a continuation line?
1144 ((py-continuation-line-p)
1145 (let ((startpos (point))
1146 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001147 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001148 (if open-bracket-pos
1149 (progn
1150 ;; align with first item in list; else a normal
1151 ;; indent beyond the line with the open bracket
1152 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1153 ;; is the first list item on the same line?
1154 (skip-chars-forward " \t")
1155 (if (null (memq (following-char) '(?\n ?# ?\\)))
1156 ; yes, so line up with it
1157 (current-column)
1158 ;; first list item on another line, or doesn't exist yet
1159 (forward-line 1)
1160 (while (and (< (point) startpos)
1161 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1162 (forward-line 1))
1163 (if (< (point) startpos)
1164 ;; again mimic the first list item
1165 (current-indentation)
1166 ;; else they're about to enter the first item
1167 (goto-char open-bracket-pos)
1168 (+ (current-indentation) py-indent-offset))))
1169
1170 ;; else on backslash continuation line
1171 (forward-line -1)
1172 (if (py-continuation-line-p) ; on at least 3rd line in block
1173 (current-indentation) ; so just continue the pattern
1174 ;; else started on 2nd line in block, so indent more.
1175 ;; if base line is an assignment with a start on a RHS,
1176 ;; indent to 2 beyond the leftmost "="; else skip first
1177 ;; chunk of non-whitespace characters on base line, + 1 more
1178 ;; column
1179 (end-of-line)
1180 (setq endpos (point) searching t)
1181 (back-to-indentation)
1182 (setq startpos (point))
1183 ;; look at all "=" from left to right, stopping at first
1184 ;; one not nested in a list or string
1185 (while searching
1186 (skip-chars-forward "^=" endpos)
1187 (if (= (point) endpos)
1188 (setq searching nil)
1189 (forward-char 1)
1190 (setq state (parse-partial-sexp startpos (point)))
1191 (if (and (zerop (car state)) ; not in a bracket
1192 (null (nth 3 state))) ; & not in a string
1193 (progn
1194 (setq searching nil) ; done searching in any case
1195 (setq found
1196 (not (or
1197 (eq (following-char) ?=)
1198 (memq (char-after (- (point) 2))
1199 '(?< ?> ?!)))))))))
1200 (if (or (not found) ; not an assignment
1201 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1202 (progn
1203 (goto-char startpos)
1204 (skip-chars-forward "^ \t\n")))
1205 (1+ (current-column))))))
1206
1207 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001208 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001209
Barry Warsawa7891711996-08-01 15:53:09 +00001210 ;; Dfn: "Indenting comment line". A line containing only a
1211 ;; comment, but which is treated like a statement for
1212 ;; indentation calculation purposes. Such lines are only
1213 ;; treated specially by the mode; they are not treated
1214 ;; specially by the Python interpreter.
1215
1216 ;; The rules for indenting comment lines are a line where:
1217 ;; - the first non-whitespace character is `#', and
1218 ;; - the character following the `#' is whitespace, and
1219 ;; - the line is outdented with respect to (i.e. to the left
1220 ;; of) the indentation of the preceding non-blank line.
1221
1222 ;; The first non-blank line following an indenting comment
1223 ;; line is given the same amount of indentation as the
1224 ;; indenting comment line.
1225
1226 ;; All other comment-only lines are ignored for indentation
1227 ;; purposes.
1228
1229 ;; Are we looking at a comment-only line which is *not* an
1230 ;; indenting comment line? If so, we assume that its been
1231 ;; placed at the desired indentation, so leave it alone.
1232 ;; Indenting comment lines are aligned as statements down
1233 ;; below.
1234 ((and (looking-at "[ \t]*#[^ \t\n]")
1235 ;; NOTE: this test will not be performed in older Emacsen
1236 (fboundp 'forward-comment)
1237 (<= (current-indentation)
1238 (save-excursion
1239 (forward-comment (- (point-max)))
1240 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001241 (current-indentation))
1242
1243 ;; else indentation based on that of the statement that
1244 ;; precedes us; use the first line of that statement to
1245 ;; establish the base, in case the user forced a non-std
1246 ;; indentation for the continuation lines (if any)
1247 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001248 ;; skip back over blank & non-indenting comment lines note:
1249 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001250 ;; happens to be a continuation line too. use fast Emacs 19
1251 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001252 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001253 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001254 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001255 (let (done)
1256 (while (not done)
1257 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1258 nil 'move)
1259 (setq done (or (eq py-honor-comment-indentation t)
1260 (bobp)
1261 (/= (following-char) ?#)
1262 (not (zerop (current-column)))))
1263 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001264 ;; if we landed inside a string, go to the beginning of that
1265 ;; string. this handles triple quoted, multi-line spanning
1266 ;; strings.
1267 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001268 (+ (current-indentation)
1269 (if (py-statement-opens-block-p)
1270 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001271 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001272 (- py-indent-offset)
1273 0)))
1274 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001275
1276(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001277 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001278By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001279`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001281`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001282their own buffer-local copy), both those currently existing and those
1283created later in the Emacs session.
1284
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001285Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001286There's no excuse for such foolishness, but sometimes you have to deal
1287with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001288`py-indent-offset' to what it thinks it was when they created the
1289mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290
1291Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001292looking for a line that opens a block of code. `py-indent-offset' is
1293set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001294statement following it. If the search doesn't succeed going forward,
1295it's tried again going backward."
1296 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001297 (let (new-value
1298 (start (point))
1299 restart
1300 (found nil)
1301 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001302 (py-goto-initial-line)
1303 (while (not (or found (eobp)))
1304 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1305 (progn
1306 (setq restart (point))
1307 (py-goto-initial-line)
1308 (if (py-statement-opens-block-p)
1309 (setq found t)
1310 (goto-char restart)))))
1311 (if found
1312 ()
1313 (goto-char start)
1314 (py-goto-initial-line)
1315 (while (not (or found (bobp)))
1316 (setq found
1317 (and
1318 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1319 (or (py-goto-initial-line) t) ; always true -- side effect
1320 (py-statement-opens-block-p)))))
1321 (setq colon-indent (current-indentation)
1322 found (and found (zerop (py-next-statement 1)))
1323 new-value (- (current-indentation) colon-indent))
1324 (goto-char start)
1325 (if found
1326 (progn
1327 (funcall (if global 'kill-local-variable 'make-local-variable)
1328 'py-indent-offset)
1329 (setq py-indent-offset new-value)
1330 (message "%s value of py-indent-offset set to %d"
1331 (if global "Global" "Local")
1332 py-indent-offset))
1333 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1334
1335(defun py-shift-region (start end count)
1336 (save-excursion
1337 (goto-char end) (beginning-of-line) (setq end (point))
1338 (goto-char start) (beginning-of-line) (setq start (point))
1339 (indent-rigidly start end count)))
1340
1341(defun py-shift-region-left (start end &optional count)
1342 "Shift region of Python code to the left.
1343The lines from the line containing the start of the current region up
1344to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001345shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001346
1347If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001348many columns. With no active region, outdent only the current line.
1349You cannot outdent the region if any line is already at column zero."
1350 (interactive
1351 (let ((p (point))
1352 (m (mark))
1353 (arg current-prefix-arg))
1354 (if m
1355 (list (min p m) (max p m) arg)
1356 (list p (save-excursion (forward-line 1) (point)) arg))))
1357 ;; if any line is at column zero, don't shift the region
1358 (save-excursion
1359 (goto-char start)
1360 (while (< (point) end)
1361 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001362 (if (and (zerop (current-column))
1363 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001364 (error "Region is at left edge."))
1365 (forward-line 1)))
1366 (py-shift-region start end (- (prefix-numeric-value
1367 (or count py-indent-offset))))
1368 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001369
1370(defun py-shift-region-right (start end &optional count)
1371 "Shift region of Python code to the right.
1372The lines from the line containing the start of the current region up
1373to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001374shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001375
1376If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001377many columns. With no active region, indent only the current line."
1378 (interactive
1379 (let ((p (point))
1380 (m (mark))
1381 (arg current-prefix-arg))
1382 (if m
1383 (list (min p m) (max p m) arg)
1384 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001385 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001386 (or count py-indent-offset)))
1387 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001388
1389(defun py-indent-region (start end &optional indent-offset)
1390 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001391
Barry Warsaw7ae77681994-12-12 20:38:05 +00001392The lines from the line containing the start of the current region up
1393to (but not including) the line containing the end of the region are
1394reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001395character in the first column, the first line is left alone and the
1396rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001397region is reindented with respect to the (closest code or indenting
1398comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001399
1400This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001401control structures are introduced or removed, or to reformat code
1402using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001403
1404If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001405the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406used.
1407
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001408Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001409is called! This function does not compute proper indentation from
1410scratch (that's impossible in Python), it merely adjusts the existing
1411indentation to be correct in context.
1412
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001413Warning: This function really has no idea what to do with
1414non-indenting comment lines, and shifts them as if they were indenting
1415comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001416
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001417Special cases: whitespace is deleted from blank lines; continuation
1418lines are shifted by the same amount their initial line was shifted,
1419in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001420initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001421 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422 (save-excursion
1423 (goto-char end) (beginning-of-line) (setq end (point-marker))
1424 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001425 (let ((py-indent-offset (prefix-numeric-value
1426 (or indent-offset py-indent-offset)))
1427 (indents '(-1)) ; stack of active indent levels
1428 (target-column 0) ; column to which to indent
1429 (base-shifted-by 0) ; amount last base line was shifted
1430 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001431 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001432 0))
1433 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001434 (while (< (point) end)
1435 (setq ci (current-indentation))
1436 ;; figure out appropriate target column
1437 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001438 ((or (eq (following-char) ?#) ; comment in column 1
1439 (looking-at "[ \t]*$")) ; entirely blank
1440 (setq target-column 0))
1441 ((py-continuation-line-p) ; shift relative to base line
1442 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001443 (t ; new base line
1444 (if (> ci (car indents)) ; going deeper; push it
1445 (setq indents (cons ci indents))
1446 ;; else we should have seen this indent before
1447 (setq indents (memq ci indents)) ; pop deeper indents
1448 (if (null indents)
1449 (error "Bad indentation in region, at line %d"
1450 (save-restriction
1451 (widen)
1452 (1+ (count-lines 1 (point)))))))
1453 (setq target-column (+ indent-base
1454 (* py-indent-offset
1455 (- (length indents) 2))))
1456 (setq base-shifted-by (- target-column ci))))
1457 ;; shift as needed
1458 (if (/= ci target-column)
1459 (progn
1460 (delete-horizontal-space)
1461 (indent-to target-column)))
1462 (forward-line 1))))
1463 (set-marker end nil))
1464
Barry Warsawa7891711996-08-01 15:53:09 +00001465(defun py-comment-region (beg end &optional arg)
1466 "Like `comment-region' but uses double hash (`#') comment starter."
1467 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001468 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001469 (comment-region beg end arg)))
1470
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001471
1472;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001473(defun py-previous-statement (count)
1474 "Go to the start of previous Python statement.
1475If the statement at point is the i'th Python statement, goes to the
1476start of statement i-COUNT. If there is no such statement, goes to the
1477first statement. Returns count of statements left to move.
1478`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480 (if (< count 0) (py-next-statement (- count))
1481 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001482 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001483 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001484 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001485 (> count 0)
1486 (zerop (forward-line -1))
1487 (py-goto-statement-at-or-above))
1488 (setq count (1- count)))
1489 (if (> count 0) (goto-char start)))
1490 count))
1491
1492(defun py-next-statement (count)
1493 "Go to the start of next Python statement.
1494If the statement at point is the i'th Python statement, goes to the
1495start of statement i+COUNT. If there is no such statement, goes to the
1496last statement. Returns count of statements left to move. `Statements'
1497do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001498 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001499 (if (< count 0) (py-previous-statement (- count))
1500 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001501 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001502 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001503 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001504 (> count 0)
1505 (py-goto-statement-below))
1506 (setq count (1- count)))
1507 (if (> count 0) (goto-char start)))
1508 count))
1509
1510(defun py-goto-block-up (&optional nomark)
1511 "Move up to start of current block.
1512Go to the statement that starts the smallest enclosing block; roughly
1513speaking, this will be the closest preceding statement that ends with a
1514colon and is indented less than the statement you started on. If
1515successful, also sets the mark to the starting point.
1516
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517`\\[py-mark-block]' can be used afterward to mark the whole code
1518block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001519
1520If called from a program, the mark will not be set if optional argument
1521NOMARK is not nil."
1522 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001523 (let ((start (point))
1524 (found nil)
1525 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001526 (py-goto-initial-line)
1527 ;; if on blank or non-indenting comment line, use the preceding stmt
1528 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1529 (progn
1530 (py-goto-statement-at-or-above)
1531 (setq found (py-statement-opens-block-p))))
1532 ;; search back for colon line indented less
1533 (setq initial-indent (current-indentation))
1534 (if (zerop initial-indent)
1535 ;; force fast exit
1536 (goto-char (point-min)))
1537 (while (not (or found (bobp)))
1538 (setq found
1539 (and
1540 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1541 (or (py-goto-initial-line) t) ; always true -- side effect
1542 (< (current-indentation) initial-indent)
1543 (py-statement-opens-block-p))))
1544 (if found
1545 (progn
1546 (or nomark (push-mark start))
1547 (back-to-indentation))
1548 (goto-char start)
1549 (error "Enclosing block not found"))))
1550
1551(defun beginning-of-python-def-or-class (&optional class)
1552 "Move point to start of def (or class, with prefix arg).
1553
1554Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001555arg, looks for a `class' instead. The docs assume the `def' case;
1556just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001557
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001558If point is in a def statement already, and after the `d', simply
1559moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001560
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001561Else (point is not in a def statement, or at or before the `d' of a
1562def statement), searches for the closest preceding def statement, and
1563leaves point at its start. If no such statement can be found, leaves
1564point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001565
1566Returns t iff a def statement is found by these rules.
1567
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568Note that doing this command repeatedly will take you closer to the
1569start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001570
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001571If you want to mark the current def/class, see
1572`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001574 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1575 (start-of-line (progn (beginning-of-line) (point)))
1576 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577 (if (or (/= start-of-stmt start-of-line)
1578 (not at-or-before-p))
1579 (end-of-line)) ; OK to match on this line
1580 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001581 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001582
1583(defun end-of-python-def-or-class (&optional class)
1584 "Move point beyond end of def (or class, with prefix arg) body.
1585
1586By default, looks for an appropriate `def'. If you supply a prefix arg,
1587looks for a `class' instead. The docs assume the `def' case; just
1588substitute `class' for `def' for the other case.
1589
1590If point is in a def statement already, this is the def we use.
1591
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001592Else if the def found by `\\[beginning-of-python-def-or-class]'
1593contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001594
1595Else we search forward for the closest following def, and use that.
1596
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001597If a def can be found by these rules, point is moved to the start of
1598the line immediately following the def block, and the position of the
1599start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600
1601Else point is moved to the end of the buffer, and nil is returned.
1602
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001603Note that doing this command repeatedly will take you closer to the
1604end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001605
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001606If you want to mark the current def/class, see
1607`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001608 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001609 (let ((start (progn (py-goto-initial-line) (point)))
1610 (which (if class "class" "def"))
1611 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001612 ;; move point to start of appropriate def/class
1613 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1614 (setq state 'at-beginning)
1615 ;; else see if beginning-of-python-def-or-class hits container
1616 (if (and (beginning-of-python-def-or-class class)
1617 (progn (py-goto-beyond-block)
1618 (> (point) start)))
1619 (setq state 'at-end)
1620 ;; else search forward
1621 (goto-char start)
1622 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1623 (progn (setq state 'at-beginning)
1624 (beginning-of-line)))))
1625 (cond
1626 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1627 ((eq state 'at-end) t)
1628 ((eq state 'not-found) nil)
1629 (t (error "internal error in end-of-python-def-or-class")))))
1630
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001631
1632;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001633(defun py-mark-block (&optional extend just-move)
1634 "Mark following block of lines. With prefix arg, mark structure.
1635Easier to use than explain. It sets the region to an `interesting'
1636block of succeeding lines. If point is on a blank line, it goes down to
1637the next non-blank line. That will be the start of the region. The end
1638of the region depends on the kind of line at the start:
1639
1640 - If a comment, the region will include all succeeding comment lines up
1641 to (but not including) the next non-comment line (if any).
1642
1643 - Else if a prefix arg is given, and the line begins one of these
1644 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001645
1646 if elif else try except finally for while def class
1647
Barry Warsaw7ae77681994-12-12 20:38:05 +00001648 the region will be set to the body of the structure, including
1649 following blocks that `belong' to it, but excluding trailing blank
1650 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001651 and all (if any) of the following `except' and `finally' blocks
1652 that belong to the `try' structure will be in the region. Ditto
1653 for if/elif/else, for/else and while/else structures, and (a bit
1654 degenerate, since they're always one-block structures) def and
1655 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656
1657 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001658 block (see list above), and the block is not a `one-liner' (i.e.,
1659 the statement ends with a colon, not with code), the region will
1660 include all succeeding lines up to (but not including) the next
1661 code statement (if any) that's indented no more than the starting
1662 line, except that trailing blank and comment lines are excluded.
1663 E.g., if the starting line begins a multi-statement `def'
1664 structure, the region will be set to the full function definition,
1665 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001666
1667 - Else the region will include all succeeding lines up to (but not
1668 including) the next blank line, or code or indenting-comment line
1669 indented strictly less than the starting line. Trailing indenting
1670 comment lines are included in this case, but not trailing blank
1671 lines.
1672
1673A msg identifying the location of the mark is displayed in the echo
1674area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1675
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001676If called from a program, optional argument EXTEND plays the role of
1677the prefix arg, and if optional argument JUST-MOVE is not nil, just
1678moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679 (interactive "P") ; raw prefix arg
1680 (py-goto-initial-line)
1681 ;; skip over blank lines
1682 (while (and
1683 (looking-at "[ \t]*$") ; while blank line
1684 (not (eobp))) ; & somewhere to go
1685 (forward-line 1))
1686 (if (eobp)
1687 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001688 (let ((initial-pos (point))
1689 (initial-indent (current-indentation))
1690 last-pos ; position of last stmt in region
1691 (followers
1692 '((if elif else) (elif elif else) (else)
1693 (try except finally) (except except) (finally)
1694 (for else) (while else)
1695 (def) (class) ) )
1696 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697
1698 (cond
1699 ;; if comment line, suck up the following comment lines
1700 ((looking-at "[ \t]*#")
1701 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1702 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1703 (setq last-pos (point)))
1704
1705 ;; else if line is a block line and EXTEND given, suck up
1706 ;; the whole structure
1707 ((and extend
1708 (setq first-symbol (py-suck-up-first-keyword) )
1709 (assq first-symbol followers))
1710 (while (and
1711 (or (py-goto-beyond-block) t) ; side effect
1712 (forward-line -1) ; side effect
1713 (setq last-pos (point)) ; side effect
1714 (py-goto-statement-below)
1715 (= (current-indentation) initial-indent)
1716 (setq next-symbol (py-suck-up-first-keyword))
1717 (memq next-symbol (cdr (assq first-symbol followers))))
1718 (setq first-symbol next-symbol)))
1719
1720 ;; else if line *opens* a block, search for next stmt indented <=
1721 ((py-statement-opens-block-p)
1722 (while (and
1723 (setq last-pos (point)) ; always true -- side effect
1724 (py-goto-statement-below)
1725 (> (current-indentation) initial-indent))
1726 nil))
1727
1728 ;; else plain code line; stop at next blank line, or stmt or
1729 ;; indenting comment line indented <
1730 (t
1731 (while (and
1732 (setq last-pos (point)) ; always true -- side effect
1733 (or (py-goto-beyond-final-line) t)
1734 (not (looking-at "[ \t]*$")) ; stop at blank line
1735 (or
1736 (>= (current-indentation) initial-indent)
1737 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1738 nil)))
1739
1740 ;; skip to end of last stmt
1741 (goto-char last-pos)
1742 (py-goto-beyond-final-line)
1743
1744 ;; set mark & display
1745 (if just-move
1746 () ; just return
1747 (push-mark (point) 'no-msg)
1748 (forward-line -1)
1749 (message "Mark set after: %s" (py-suck-up-leading-text))
1750 (goto-char initial-pos))))
1751
1752(defun mark-python-def-or-class (&optional class)
1753 "Set region to body of def (or class, with prefix arg) enclosing point.
1754Pushes the current mark, then point, on the mark ring (all language
1755modes do this, but although it's handy it's never documented ...).
1756
1757In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001758hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1759`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760
1761And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001762Turned out that was more confusing than useful: the `goto start' and
1763`goto end' commands are usually used to search through a file, and
1764people expect them to act a lot like `search backward' and `search
1765forward' string-search commands. But because Python `def' and `class'
1766can nest to arbitrary levels, finding the smallest def containing
1767point cannot be done via a simple backward search: the def containing
1768point may not be the closest preceding def, or even the closest
1769preceding def that's indented less. The fancy algorithm required is
1770appropriate for the usual uses of this `mark' command, but not for the
1771`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001772
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773So the def marked by this command may not be the one either of the
1774`goto' commands find: If point is on a blank or non-indenting comment
1775line, moves back to start of the closest preceding code statement or
1776indenting comment line. If this is a `def' statement, that's the def
1777we use. Else searches for the smallest enclosing `def' block and uses
1778that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780When an enclosing def is found: The mark is left immediately beyond
1781the last line of the def block. Point is left at the start of the
1782def, except that: if the def is preceded by a number of comment lines
1783followed by (at most) one optional blank line, point is left at the
1784start of the comments; else if the def is preceded by a blank line,
1785point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001786
1787The intent is to mark the containing def/class and its associated
1788documentation, to make moving and duplicating functions and classes
1789pleasant."
1790 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001791 (let ((start (point))
1792 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001793 (push-mark start)
1794 (if (not (py-go-up-tree-to-keyword which))
1795 (progn (goto-char start)
1796 (error "Enclosing %s not found" which))
1797 ;; else enclosing def/class found
1798 (setq start (point))
1799 (py-goto-beyond-block)
1800 (push-mark (point))
1801 (goto-char start)
1802 (if (zerop (forward-line -1)) ; if there is a preceding line
1803 (progn
1804 (if (looking-at "[ \t]*$") ; it's blank
1805 (setq start (point)) ; so reset start point
1806 (goto-char start)) ; else try again
1807 (if (zerop (forward-line -1))
1808 (if (looking-at "[ \t]*#") ; a comment
1809 ;; look back for non-comment line
1810 ;; tricky: note that the regexp matches a blank
1811 ;; line, cuz \n is in the 2nd character class
1812 (and
1813 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1814 (forward-line 1))
1815 ;; no comment, so go back
1816 (goto-char start))))))))
1817
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001818;; ripped from cc-mode
1819(defun py-forward-into-nomenclature (&optional arg)
1820 "Move forward to end of a nomenclature section or word.
1821With arg, to it arg times.
1822
1823A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1824 (interactive "p")
1825 (let ((case-fold-search nil))
1826 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001827 (re-search-forward
1828 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1829 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001830 (while (and (< arg 0)
1831 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001832 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001833 (point-min) 0))
1834 (forward-char 1)
1835 (setq arg (1+ arg)))))
1836 (py-keep-region-active))
1837
1838(defun py-backward-into-nomenclature (&optional arg)
1839 "Move backward to beginning of a nomenclature section or word.
1840With optional ARG, move that many times. If ARG is negative, move
1841forward.
1842
1843A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1844 (interactive "p")
1845 (py-forward-into-nomenclature (- arg))
1846 (py-keep-region-active))
1847
1848
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849
1850;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001851
1852;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1854;; out of the right places, along with the keys they're on & current
1855;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001856(defun py-dump-help-string (str)
1857 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858 (let ((locals (buffer-local-variables))
1859 funckind funcname func funcdoc
1860 (start 0) mstart end
1861 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1863 (setq mstart (match-beginning 0) end (match-end 0)
1864 funckind (substring str (match-beginning 1) (match-end 1))
1865 funcname (substring str (match-beginning 2) (match-end 2))
1866 func (intern funcname))
1867 (princ (substitute-command-keys (substring str start mstart)))
1868 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869 ((equal funckind "c") ; command
1870 (setq funcdoc (documentation func)
1871 keys (concat
1872 "Key(s): "
1873 (mapconcat 'key-description
1874 (where-is-internal func py-mode-map)
1875 ", "))))
1876 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001877 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878 keys (if (assq func locals)
1879 (concat
1880 "Local/Global values: "
1881 (prin1-to-string (symbol-value func))
1882 " / "
1883 (prin1-to-string (default-value func)))
1884 (concat
1885 "Value: "
1886 (prin1-to-string (symbol-value func))))))
1887 (t ; unexpected
1888 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889 (princ (format "\n-> %s:\t%s\t%s\n\n"
1890 (if (equal funckind "c") "Command" "Variable")
1891 funcname keys))
1892 (princ funcdoc)
1893 (terpri)
1894 (setq start end))
1895 (princ (substitute-command-keys (substring str start))))
1896 (print-help-return-message)))
1897
1898(defun py-describe-mode ()
1899 "Dump long form of Python-mode docs."
1900 (interactive)
1901 (py-dump-help-string "Major mode for editing Python files.
1902Knows about Python indentation, tokens, comments and continuation lines.
1903Paragraphs are separated by blank lines only.
1904
1905Major sections below begin with the string `@'; specific function and
1906variable docs begin with `->'.
1907
1908@EXECUTING PYTHON CODE
1909
1910\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1911\\[py-execute-region]\tsends the current region
1912\\[py-shell]\tstarts a Python interpreter window; this will be used by
1913\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1914%c:py-execute-buffer
1915%c:py-execute-region
1916%c:py-shell
1917
1918@VARIABLES
1919
1920py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001921py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922
1923py-python-command\tshell command to invoke Python interpreter
1924py-scroll-process-buffer\talways scroll Python process buffer
1925py-temp-directory\tdirectory used for temp files (if needed)
1926
1927py-beep-if-tab-change\tring the bell if tab-width is changed
1928%v:py-indent-offset
1929%v:py-block-comment-prefix
1930%v:py-python-command
1931%v:py-scroll-process-buffer
1932%v:py-temp-directory
1933%v:py-beep-if-tab-change
1934
1935@KINDS OF LINES
1936
1937Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938preceding line ends with a backslash that's not part of a comment, or
1939the paren/bracket/brace nesting level at the start of the line is
1940non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941
1942An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943possibly blanks or tabs), a `comment line' (leftmost non-blank
1944character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945
1946Comment Lines
1947
1948Although all comment lines are treated alike by Python, Python mode
1949recognizes two kinds that act differently with respect to indentation.
1950
1951An `indenting comment line' is a comment line with a blank, tab or
1952nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001953treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001954indenting comment line will be indented like the comment line. All
1955other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001956following the initial `#') are `non-indenting comment lines', and
1957their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958
1959Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001960whenever possible. Non-indenting comment lines are useful in cases
1961like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001962
1963\ta = b # a very wordy single-line comment that ends up being
1964\t #... continued onto another line
1965
1966\tif a == b:
1967##\t\tprint 'panic!' # old code we've `commented out'
1968\t\treturn a
1969
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001970Since the `#...' and `##' comment lines have a non-whitespace
1971character following the initial `#', Python mode ignores them when
1972computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001973
1974Continuation Lines and Statements
1975
1976The Python-mode commands generally work on statements instead of on
1977individual lines, where a `statement' is a comment or blank line, or a
1978code line and all of its following continuation lines (if any)
1979considered as a single logical unit. The commands in this mode
1980generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001981statement containing point, even if point happens to be in the middle
1982of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001983
1984
1985@INDENTATION
1986
1987Primarily for entering new code:
1988\t\\[indent-for-tab-command]\t indent line appropriately
1989\t\\[py-newline-and-indent]\t insert newline, then indent
1990\t\\[py-delete-char]\t reduce indentation, or delete single character
1991
1992Primarily for reindenting existing code:
1993\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1994\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1995
1996\t\\[py-indent-region]\t reindent region to match its context
1997\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1998\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1999
2000Unlike most programming languages, Python uses indentation, and only
2001indentation, to specify block structure. Hence the indentation supplied
2002automatically by Python-mode is just an educated guess: only you know
2003the block structure you intend, so only you can supply correct
2004indentation.
2005
2006The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2007the indentation of preceding statements. E.g., assuming
2008py-indent-offset is 4, after you enter
2009\tif a > 0: \\[py-newline-and-indent]
2010the cursor will be moved to the position of the `_' (_ is not a
2011character in the file, it's just used here to indicate the location of
2012the cursor):
2013\tif a > 0:
2014\t _
2015If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2016to
2017\tif a > 0:
2018\t c = d
2019\t _
2020Python-mode cannot know whether that's what you intended, or whether
2021\tif a > 0:
2022\t c = d
2023\t_
2024was your intent. In general, Python-mode either reproduces the
2025indentation of the (closest code or indenting-comment) preceding
2026statement, or adds an extra py-indent-offset blanks if the preceding
2027statement has `:' as its last significant (non-whitespace and non-
2028comment) character. If the suggested indentation is too much, use
2029\\[py-delete-char] to reduce it.
2030
2031Continuation lines are given extra indentation. If you don't like the
2032suggested indentation, change it to something you do like, and Python-
2033mode will strive to indent later lines of the statement in the same way.
2034
2035If a line is a continuation line by virtue of being in an unclosed
2036paren/bracket/brace structure (`list', for short), the suggested
2037indentation depends on whether the current line contains the first item
2038in the list. If it does, it's indented py-indent-offset columns beyond
2039the indentation of the line containing the open bracket. If you don't
2040like that, change it by hand. The remaining items in the list will mimic
2041whatever indentation you give to the first item.
2042
2043If a line is a continuation line because the line preceding it ends with
2044a backslash, the third and following lines of the statement inherit their
2045indentation from the line preceding them. The indentation of the second
2046line in the statement depends on the form of the first (base) line: if
2047the base line is an assignment statement with anything more interesting
2048than the backslash following the leftmost assigning `=', the second line
2049is indented two columns beyond that `='. Else it's indented to two
2050columns beyond the leftmost solid chunk of non-whitespace characters on
2051the base line.
2052
2053Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2054repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2055structure you intend.
2056%c:indent-for-tab-command
2057%c:py-newline-and-indent
2058%c:py-delete-char
2059
2060
2061The next function may be handy when editing code you didn't write:
2062%c:py-guess-indent-offset
2063
2064
2065The remaining `indent' functions apply to a region of Python code. They
2066assume the block structure (equals indentation, in Python) of the region
2067is correct, and alter the indentation in various ways while preserving
2068the block structure:
2069%c:py-indent-region
2070%c:py-shift-region-left
2071%c:py-shift-region-right
2072
2073@MARKING & MANIPULATING REGIONS OF CODE
2074
2075\\[py-mark-block]\t mark block of lines
2076\\[mark-python-def-or-class]\t mark smallest enclosing def
2077\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002078\\[comment-region]\t comment out region of code
2079\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002080%c:py-mark-block
2081%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002082%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002083
2084@MOVING POINT
2085
2086\\[py-previous-statement]\t move to statement preceding point
2087\\[py-next-statement]\t move to statement following point
2088\\[py-goto-block-up]\t move up to start of current block
2089\\[beginning-of-python-def-or-class]\t move to start of def
2090\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2091\\[end-of-python-def-or-class]\t move to end of def
2092\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2093
2094The first two move to one statement beyond the statement that contains
2095point. A numeric prefix argument tells them to move that many
2096statements instead. Blank lines, comment lines, and continuation lines
2097do not count as `statements' for these commands. So, e.g., you can go
2098to the first code statement in a file by entering
2099\t\\[beginning-of-buffer]\t to move to the top of the file
2100\t\\[py-next-statement]\t to skip over initial comments and blank lines
2101Or do `\\[py-previous-statement]' with a huge prefix argument.
2102%c:py-previous-statement
2103%c:py-next-statement
2104%c:py-goto-block-up
2105%c:beginning-of-python-def-or-class
2106%c:end-of-python-def-or-class
2107
2108@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2109
2110`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2111
2112`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2113overall class and def structure of a module.
2114
2115`\\[back-to-indentation]' moves point to a line's first non-blank character.
2116
2117`\\[indent-relative]' is handy for creating odd indentation.
2118
2119@OTHER EMACS HINTS
2120
2121If you don't like the default value of a variable, change its value to
2122whatever you do like by putting a `setq' line in your .emacs file.
2123E.g., to set the indentation increment to 4, put this line in your
2124.emacs:
2125\t(setq py-indent-offset 4)
2126To see the value of a variable, do `\\[describe-variable]' and enter the variable
2127name at the prompt.
2128
2129When entering a key sequence like `C-c C-n', it is not necessary to
2130release the CONTROL key after doing the `C-c' part -- it suffices to
2131press the CONTROL key, press and release `c' (while still holding down
2132CONTROL), press and release `n' (while still holding down CONTROL), &
2133then release CONTROL.
2134
2135Entering Python mode calls with no arguments the value of the variable
2136`python-mode-hook', if that value exists and is not nil; for backward
2137compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2138the Elisp manual for details.
2139
2140Obscure: When python-mode is first loaded, it looks for all bindings
2141to newline-and-indent in the global keymap, and shadows them with
2142local bindings to py-newline-and-indent."))
2143
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002144
2145;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002146(defvar py-parse-state-re
2147 (concat
2148 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2149 "\\|"
2150 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002151
Barry Warsaw7ae77681994-12-12 20:38:05 +00002152;; returns the parse state at point (see parse-partial-sexp docs)
2153(defun py-parse-state ()
2154 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002155 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002156 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002157 (while (not done)
2158 ;; back up to the first preceding line (if any; else start of
2159 ;; buffer) that begins with a popular Python keyword, or a
2160 ;; non- whitespace and non-comment character. These are good
2161 ;; places to start parsing to see whether where we started is
2162 ;; at a non-zero nesting level. It may be slow for people who
2163 ;; write huge code blocks or huge lists ... tough beans.
2164 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002165 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002166 (beginning-of-line)
2167 (save-excursion
2168 (setq pps (parse-partial-sexp (point) here)))
2169 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002170 (setq done (or (zerop ci)
2171 (not (nth 3 pps))
2172 (bobp)))
2173 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002174 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002175
2176;; if point is at a non-zero nesting level, returns the number of the
2177;; character that opens the smallest enclosing unclosed list; else
2178;; returns nil.
2179(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002180 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002181 (if (zerop (car status))
2182 nil ; not in a nest
2183 (car (cdr status))))) ; char# of open bracket
2184
2185;; t iff preceding line ends with backslash that's not in a comment
2186(defun py-backslash-continuation-line-p ()
2187 (save-excursion
2188 (beginning-of-line)
2189 (and
2190 ;; use a cheap test first to avoid the regexp if possible
2191 ;; use 'eq' because char-after may return nil
2192 (eq (char-after (- (point) 2)) ?\\ )
2193 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002194 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002195 (looking-at py-continued-re))))
2196
2197;; t iff current line is a continuation line
2198(defun py-continuation-line-p ()
2199 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002200 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002201 (or (py-backslash-continuation-line-p)
2202 (py-nesting-level))))
2203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204;; go to initial line of current statement; usually this is the line
2205;; we're on, but if we're on the 2nd or following lines of a
2206;; continuation block, we need to go up to the first line of the
2207;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002208;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002209;; Tricky: We want to avoid quadratic-time behavior for long continued
2210;; blocks, whether of the backslash or open-bracket varieties, or a
2211;; mix of the two. The following manages to do that in the usual
2212;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002213(defun py-goto-initial-line ()
2214 (let ( open-bracket-pos )
2215 (while (py-continuation-line-p)
2216 (beginning-of-line)
2217 (if (py-backslash-continuation-line-p)
2218 (while (py-backslash-continuation-line-p)
2219 (forward-line -1))
2220 ;; else zip out of nested brackets/braces/parens
2221 (while (setq open-bracket-pos (py-nesting-level))
2222 (goto-char open-bracket-pos)))))
2223 (beginning-of-line))
2224
2225;; go to point right beyond final line of current statement; usually
2226;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002227;; statement we need to skip over the continuation lines. Tricky:
2228;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002229(defun py-goto-beyond-final-line ()
2230 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002231 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002232 (while (and (py-continuation-line-p)
2233 (not (eobp)))
2234 ;; skip over the backslash flavor
2235 (while (and (py-backslash-continuation-line-p)
2236 (not (eobp)))
2237 (forward-line 1))
2238 ;; if in nest, zip to the end of the nest
2239 (setq state (py-parse-state))
2240 (if (and (not (zerop (car state)))
2241 (not (eobp)))
2242 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002243 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002244 (forward-line 1))))))
2245
2246;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002247;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002248(defun py-statement-opens-block-p ()
2249 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002250 (let ((start (point))
2251 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2252 (searching t)
2253 (answer nil)
2254 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002255 (goto-char start)
2256 (while searching
2257 ;; look for a colon with nothing after it except whitespace, and
2258 ;; maybe a comment
2259 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2260 finish t)
2261 (if (eq (point) finish) ; note: no `else' clause; just
2262 ; keep searching if we're not at
2263 ; the end yet
2264 ;; sure looks like it opens a block -- but it might
2265 ;; be in a comment
2266 (progn
2267 (setq searching nil) ; search is done either way
2268 (setq state (parse-partial-sexp start
2269 (match-beginning 0)))
2270 (setq answer (not (nth 4 state)))))
2271 ;; search failed: couldn't find another interesting colon
2272 (setq searching nil)))
2273 answer)))
2274
Barry Warsawf831d811996-07-31 20:42:59 +00002275(defun py-statement-closes-block-p ()
2276 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002277 ;; starts with `return', `raise', `break', `continue', and `pass'.
2278 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002279 (let ((here (point)))
2280 (back-to-indentation)
2281 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002282 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002283 (goto-char here))))
2284
Barry Warsaw7ae77681994-12-12 20:38:05 +00002285;; go to point right beyond final line of block begun by the current
2286;; line. This is the same as where py-goto-beyond-final-line goes
2287;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002288;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002289(defun py-goto-beyond-block ()
2290 (if (py-statement-opens-block-p)
2291 (py-mark-block nil 'just-move)
2292 (py-goto-beyond-final-line)))
2293
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002294;; go to start of first statement (not blank or comment or
2295;; continuation line) at or preceding point. returns t if there is
2296;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002297(defun py-goto-statement-at-or-above ()
2298 (py-goto-initial-line)
2299 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002300 ;; skip back over blank & comment lines
2301 ;; note: will skip a blank or comment line that happens to be
2302 ;; a continuation line too
2303 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2304 (progn (py-goto-initial-line) t)
2305 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306 t))
2307
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002308;; go to start of first statement (not blank or comment or
2309;; continuation line) following the statement containing point returns
2310;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002311(defun py-goto-statement-below ()
2312 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002313 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002314 (py-goto-beyond-final-line)
2315 (while (and
2316 (looking-at py-blank-or-comment-re)
2317 (not (eobp)))
2318 (forward-line 1))
2319 (if (eobp)
2320 (progn (goto-char start) nil)
2321 t)))
2322
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002323;; go to start of statement, at or preceding point, starting with
2324;; keyword KEY. Skips blank lines and non-indenting comments upward
2325;; first. If that statement starts with KEY, done, else go back to
2326;; first enclosing block starting with KEY. If successful, leaves
2327;; point at the start of the KEY line & returns t. Else leaves point
2328;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329(defun py-go-up-tree-to-keyword (key)
2330 ;; skip blanks and non-indenting #
2331 (py-goto-initial-line)
2332 (while (and
2333 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2334 (zerop (forward-line -1))) ; go back
2335 nil)
2336 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002337 (let* ((re (concat "[ \t]*" key "\\b"))
2338 (case-fold-search nil) ; let* so looking-at sees this
2339 (found (looking-at re))
2340 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341 (while (not (or found dead))
2342 (condition-case nil ; in case no enclosing block
2343 (py-goto-block-up 'no-mark)
2344 (error (setq dead t)))
2345 (or dead (setq found (looking-at re))))
2346 (beginning-of-line)
2347 found))
2348
2349;; return string in buffer from start of indentation to end of line;
2350;; prefix "..." if leading whitespace was skipped
2351(defun py-suck-up-leading-text ()
2352 (save-excursion
2353 (back-to-indentation)
2354 (concat
2355 (if (bolp) "" "...")
2356 (buffer-substring (point) (progn (end-of-line) (point))))))
2357
2358;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2359;; as a Lisp symbol; return nil if none
2360(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002361 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002362 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2363 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2364 nil)))
2365
2366(defun py-make-temp-name ()
2367 (make-temp-name
2368 (concat (file-name-as-directory py-temp-directory) "python")))
2369
2370(defun py-delete-file-silently (fname)
2371 (condition-case nil
2372 (delete-file fname)
2373 (error nil)))
2374
2375(defun py-kill-emacs-hook ()
2376 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002377 (py-safe (while py-file-queue
2378 (py-delete-file-silently (car py-file-queue))
2379 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002380
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002381;; make PROCESS's buffer visible, append STRING to it, and force
2382;; display; also make shell-mode believe the user typed this string,
2383;; so that kill-output-from-shell and show-output-from-shell work
2384;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002385(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002386 (let ((cbuf (current-buffer))
2387 (pbuf (process-buffer process))
2388 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002389 (set-buffer pbuf)
2390 (goto-char (point-max))
2391 (move-marker (process-mark process) (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002392 (funcall (process-filter process) process string)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002393 (set-buffer cbuf))
2394 (sit-for 0))
2395
Barry Warsaw3622e0d1996-10-29 15:32:57 +00002396;; older Emacsen don't have this function
2397(if (not (fboundp 'match-string))
2398 (defun match-string (n)
2399 (let ((beg (match-beginning n))
2400 (end (match-end n)))
2401 (if (and beg end)
2402 (buffer-substring beg end)
2403 nil))))
2404
Barry Warsawb3e81d51996-09-04 15:12:42 +00002405(defun py-current-defun ()
2406 ;; tell add-log.el how to find the current function/method/variable
2407 (save-excursion
2408 (if (re-search-backward py-defun-start-re nil t)
2409 (or (match-string 3)
2410 (let ((method (match-string 2)))
2411 (if (and (not (zerop (length (match-string 1))))
2412 (re-search-backward py-class-start-re nil t))
2413 (concat (match-string 1) "." method)
2414 method)))
2415 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002416
2417
Barry Warsawfec75d61995-07-05 23:26:15 +00002418(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002419 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002420
Barry Warsaw850437a1995-03-08 21:50:28 +00002421(defun py-version ()
2422 "Echo the current version of `python-mode' in the minibuffer."
2423 (interactive)
2424 (message "Using `python-mode' version %s" py-version)
2425 (py-keep-region-active))
2426
2427;; only works under Emacs 19
2428;(eval-when-compile
2429; (require 'reporter))
2430
2431(defun py-submit-bug-report (enhancement-p)
2432 "Submit via mail a bug report on `python-mode'.
2433With \\[universal-argument] just submit an enhancement request."
2434 (interactive
2435 (list (not (y-or-n-p
2436 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002437 (let ((reporter-prompt-for-summary-p (if enhancement-p
2438 "(Very) brief summary: "
2439 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002440 (require 'reporter)
2441 (reporter-submit-bug-report
2442 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002443 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002444 ;; varlist
2445 (if enhancement-p nil
2446 '(py-python-command
2447 py-indent-offset
2448 py-block-comment-prefix
2449 py-scroll-process-buffer
2450 py-temp-directory
2451 py-beep-if-tab-change))
2452 nil ;pre-hooks
2453 nil ;post-hooks
2454 "Dear Barry,") ;salutation
2455 (if enhancement-p nil
2456 (set-mark (point))
2457 (insert
2458"Please replace this text with a sufficiently large code sample\n\
2459and an exact recipe so that I can reproduce your problem. Failure\n\
2460to do so may mean a greater delay in fixing your bug.\n\n")
2461 (exchange-point-and-mark)
2462 (py-keep-region-active))))
2463
2464
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002465;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002466(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002467
2468
2469
2470(provide 'python-mode)
2471;;; python-mode.el ends here