blob: 4c7cf50eb0b5723bcf0f1d97efe2a0cea50cedd8 [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
28;; At some point this mode will undergo a rewrite to bring it more in
Barry Warsaw755c6711996-08-01 20:02:55 +000029;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
30;; 18 support. But all in all, the mode works exceedingly well, and
31;; I've simply been tweaking it as I go along. Ain't it wonderful
32;; that Python has a much more sane syntax than C? (or <shudder> C++?!
Barry Warsawc72c11c1997-08-09 06:42:08 +000033;; :-). I can say that; I maintain CC Mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000034
35;; The following statements, placed in your .emacs file or
36;; site-init.el, will cause this file to be autoloaded, and
37;; python-mode invoked, when visiting .py files (assuming this file is
38;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000040;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000041;; (setq auto-mode-alist
42;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000043;;
44;; If you want font-lock support for Python source code (a.k.a. syntax
45;; coloring, highlighting), add this to your .emacs file:
46;;
47;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsawc08a9491996-07-31 22:27:58 +000048;;
49;; But you better be sure you're version of Emacs supports
50;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
51;; 19's do.
Barry Warsaw7ae77681994-12-12 20:38:05 +000052
Barry Warsaw3fcaf611996-08-01 20:11:51 +000053;; Here's a brief list of recent additions/improvements/changes:
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000054;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000055;; - Wrapping and indentation within triple quote strings now works.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000056;; - `Standard' bug reporting mechanism (use C-c C-b)
57;; - py-mark-block was moved to C-c C-m
58;; - C-c C-v shows you the python-mode version
Barry Warsaw3fcaf611996-08-01 20:11:51 +000059;; - a basic python-font-lock-keywords has been added for (X)Emacs 19
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000060;; - proper interaction with pending-del and del-sel modes.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000061;; - Better support for outdenting: py-electric-colon (:) and
62;; py-indent-line (TAB) improvements; one level of outdentation
Barry Warsaw7cb505c1996-10-23 20:44:59 +000063;; added after a return, raise, break, pass, or continue statement.
64;; Defeated by prefixing command with C-u.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000065;; - New py-electric-colon (:) command for improved outdenting Also
66;; py-indent-line (TAB) should handle outdented lines better
Barry Warsaw03970731996-07-03 23:12:52 +000067;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000068;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
69;; M-f and M-b respectively.
Barry Warsaw3fcaf611996-08-01 20:11:51 +000070;; - integration with imenu by Perry A. Stoll <stoll@atr-sw.atr.co.jp>
71;; - py-indent-offset now defaults to 4
72;; - new variable py-honor-comment-indentation
73;; - comment-region bound to C-c #
74;; - py-delete-char obeys numeric arguments
75;; - Small modification to rule for "indenting comment lines", such
76;; lines must now also be indented less than or equal to the
77;; indentation of the previous statement.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000078
Barry Warsaw7b0f5681995-03-08 21:33:04 +000079;; Here's a brief to do list:
80;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000081;; - Better integration with gud-mode for debugging.
82;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000083;; - possibly force indent-tabs-mode == nil, and add a
84;; write-file-hooks that runs untabify on the whole buffer (to work
85;; around potential tab/space mismatch problems). In practice this
86;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +000087;; - have py-execute-region on indented code act as if the region is
88;; left justified. Avoids syntax errors.
Barry Warsaw01af4011996-09-04 14:57:22 +000089;; - Add a py-goto-error or some such that would scan an exception in
90;; the py-shell buffer, and pop you to that line in the file.
Barry Warsaw7ae77681994-12-12 20:38:05 +000091
Barry Warsaw7b0f5681995-03-08 21:33:04 +000092;; If you can think of more things you'd like to see, drop me a line.
93;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
94;;
Barry Warsaw3fcaf611996-08-01 20:11:51 +000095;; Note that I only test things on XEmacs 19 and to some degree on
96;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
97;; send me your patches. Byte compiler complaints can probably be
98;; safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000099
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000100;;; Code:
101
Barry Warsawc72c11c1997-08-09 06:42:08 +0000102(require 'custom)
103
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000104
105;; user definable variables
106;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(defgroup python nil
109 "Support for the Python programming language, <http://www.python.org/>"
110 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000111
Barry Warsawc72c11c1997-08-09 06:42:08 +0000112(defcustom py-python-command "python"
113 "*Shell command used to start Python interpreter."
114 :type 'string
115 :group 'python)
116
117(defcustom py-indent-offset 4
118 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000119Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000120when you're editing someone else's Python code."
121 :type 'integer
122 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000123
Barry Warsawc72c11c1997-08-09 06:42:08 +0000124(defcustom py-align-multiline-strings-p t
125 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000126When this flag is non-nil, continuation lines are lined up under the
127preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000128lines are aligned to column zero."
129 :type '(choice (const :tag "Align under preceding line" t)
130 (const :tag "Align to column zero" nil))
131 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000132
Barry Warsawc72c11c1997-08-09 06:42:08 +0000133(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000134 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135This should follow the convention for non-indenting comment lines so
136that the indentation commands won't get confused (i.e., the string
137should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000138`...' is arbitrary)."
139 :type 'string
140 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000141
Barry Warsawc72c11c1997-08-09 06:42:08 +0000142(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000143 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000144
Barry Warsaw6d627751996-03-06 18:41:38 +0000145When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000146if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000147
148When t, lines that begin with a single `#' are a hint to subsequent
149line indentation. If the previous line is such a comment line (as
150opposed to one that starts with `py-block-comment-prefix'), then it's
151indentation is used as a hint for this line's indentation. Lines that
152begin with `py-block-comment-prefix' are ignored for indentation
153purposes.
154
155When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000156indentation hints, unless the comment character is in column zero."
157 :type '(choice
158 (const :tag "Skip all comment lines (fast)" nil)
159 (const :tag "Single # `sets' indentation for next line" t)
160 (const :tag "Single # `sets' indentation except at column zero" other)
161 )
162 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000163
Barry Warsawc72c11c1997-08-09 06:42:08 +0000164(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000165 "*Scroll Python process buffer as output arrives.
166If nil, the Python process buffer acts, with respect to scrolling, like
167Shell-mode buffers normally act. This is surprisingly complicated and
168so won't be explained here; in fact, you can't get the whole story
169without studying the Emacs C code.
170
171If non-nil, the behavior is different in two respects (which are
172slightly inaccurate in the interest of brevity):
173
174 - If the buffer is in a window, and you left point at its end, the
175 window will scroll as new output arrives, and point will move to the
176 buffer's end, even if the window is not the selected window (that
177 being the one the cursor is in). The usual behavior for shell-mode
178 windows is not to scroll, and to leave point where it was, if the
179 buffer is in a window other than the selected window.
180
181 - If the buffer is not visible in any window, and you left point at
182 its end, the buffer will be popped into a window as soon as more
183 output arrives. This is handy if you have a long-running
184 computation and don't want to tie up screen area waiting for the
185 output. The usual behavior for a shell-mode buffer is to stay
186 invisible until you explicitly visit it.
187
188Note the `and if you left point at its end' clauses in both of the
189above: you can `turn off' the special behaviors while output is in
190progress, by visiting the Python buffer and moving point to anywhere
191besides the end. Then the buffer won't scroll, point will remain where
192you leave it, and if you hide the buffer it will stay hidden until you
193visit it again. You can enable and disable the special behaviors as
194often as you like, while output is in progress, by (respectively) moving
195point to, or away from, the end of the buffer.
196
197Warning: If you expect a large amount of output, you'll probably be
198happier setting this option to nil.
199
200Obscure: `End of buffer' above should really say `at or beyond the
201process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000202told <grin>."
203 :type 'boolean
204 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000205
Barry Warsaw516b6201997-08-09 06:43:20 +0000206(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000207 (let ((ok '(lambda (x)
208 (and x
209 (setq x (expand-file-name x)) ; always true
210 (file-directory-p x)
211 (file-writable-p x)
212 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000213 (or (funcall ok (getenv "TMPDIR"))
214 (funcall ok "/usr/tmp")
215 (funcall ok "/tmp")
216 (funcall ok ".")
217 (error
218 "Couldn't find a usable temp directory -- set py-temp-directory")))
219 "*Directory used for temp files created by a *Python* process.
220By default, the first directory from this list that exists and that you
221can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000222/usr/tmp, /tmp, or the current directory."
223 :type 'string
224 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000225
Barry Warsaw516b6201997-08-09 06:43:20 +0000226(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000227 "*Ring the bell if tab-width is changed.
228If a comment of the form
229
230 \t# vi:set tabsize=<number>:
231
232is found before the first code line when the file is entered, and the
233current value of (the general Emacs variable) `tab-width' does not
234equal <number>, `tab-width' is set to <number>, a message saying so is
235displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000236the Emacs bell is also rung as a warning."
237 :type 'boolean
238 :group 'python)
239
240
241;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
242;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
243
244;; As of 30-Jan-1997, Emacs 19.34 works but XEmacs 19.15b90 and
245;; previous does not. It is suspected that Emacsen before 19.34 are
246;; also broken.
247(defvar py-parse-partial-sexp-works-p
248 (let ((buf (get-buffer-create " ---*---pps---*---"))
249 state status)
250 (save-excursion
251 (set-buffer buf)
252 (erase-buffer)
253 (insert "(line1\n line2)\nline3")
254 (lisp-mode)
255 (goto-char (point-min))
256 (setq state (parse-partial-sexp (point) (save-excursion
257 (forward-line 1)
258 (point))))
259 (parse-partial-sexp (point) (point-max) 0 nil state)
260 (setq status (not (= (point) (point-max))))
261 (kill-buffer buf)
262 status))
263 "Does `parse-partial-sexp' work in this Emacs?")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000264
Barry Warsawfb07f401997-02-24 03:37:22 +0000265(defvar python-font-lock-keywords
Barry Warsaw2e049b21996-09-04 15:21:55 +0000266 (let* ((keywords '("and" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000267 "continue" "def" "del" "elif"
268 "else:" "except" "except:" "exec"
269 "finally:" "for" "from" "global"
270 "if" "import" "in" "is"
271 "lambda" "not" "or" "pass"
272 "print" "raise" "return" "try:"
273 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000274 ))
275 (kwregex (mapconcat 'identity keywords "\\|")))
276 (list
277 ;; keywords not at beginning of line
278 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
279 ;; keywords at beginning of line. i don't think regexps are
280 ;; powerful enough to handle these two cases in one regexp.
281 ;; prove me wrong!
282 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
283 ;; classes
284 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
285 1 font-lock-type-face)
286 ;; functions
287 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
288 1 font-lock-function-name-face)
289 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000290 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000291(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
292
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000293
Barry Warsaw81437461996-08-01 19:48:02 +0000294(defvar imenu-example--python-show-method-args-p nil
295 "*Controls echoing of arguments of functions & methods in the imenu buffer.
296When non-nil, arguments are printed.")
297
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000298(make-variable-buffer-local 'py-indent-offset)
299
Barry Warsaw7ae77681994-12-12 20:38:05 +0000300;; have to bind py-file-queue before installing the kill-emacs hook
301(defvar py-file-queue nil
302 "Queue of Python temp files awaiting execution.
303Currently-active file is at the head of the list.")
304
Barry Warsawc72c11c1997-08-09 06:42:08 +0000305(defvar py-delete-function 'backward-delete-char-untabify
306 "*Function called by `py-delete-char' when deleting characters.")
307
308(defvar py-backspace-function 'backward-delete-char-untabify
309 "*Function called by `py-backspace-command' when deleting characters.")
310
311
312;; Constants
313
314;; Regexp matching a Python string literal
315(defconst py-stringlit-re
316 (concat
317 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
318 "\\|" ; or
319 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
320
321;; Regexp matching Python lines that are continued via backslash.
322;; This is tricky because a trailing backslash does not mean
323;; continuation if it's in a comment
324(defconst py-continued-re
325 (concat
326 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
327 "\\\\$"))
328
329;; Regexp matching blank or comment lines.
330(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
331
332;; Regexp matching clauses to be outdented one level.
333(defconst py-outdent-re
334 (concat "\\(" (mapconcat 'identity
335 '("else:"
336 "except\\(\\s +.*\\)?:"
337 "finally:"
338 "elif\\s +.*:")
339 "\\|")
340 "\\)"))
341
342
343;; Regexp matching lines to not outdent after.
344(defconst py-no-outdent-re
345 (concat "\\(" (mapconcat 'identity
346 '("try:"
347 "except\\(\\s +.*\\)?:"
348 "while\\s +.*:"
349 "for\\s +.*:"
350 "if\\s +.*:"
351 "elif\\s +.*:"
352 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
353 )
354 "\\|")
355 "\\)"))
356
357;; Regexp matching a function, method or variable assignment. If you
358;; change this, you probably have to change `py-current-defun' as
359;; well. This is only used by `py-current-defun' to find the name for
360;; add-log.el.
361(defvar py-defun-start-re
362 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
363
364;; Regexp for finding a class name. If you change this, you probably
365;; have to change `py-current-defun' as well. This is only used by
366;; `py-current-defun' to find the name for add-log.el.
367(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
368
369
370
371;; Utilities
372
373(defmacro py-safe (&rest body)
374 ;; safely execute BODY, return nil if an error occurred
375 (` (condition-case nil
376 (progn (,@ body))
377 (error nil))))
378
379(defsubst py-keep-region-active ()
380 ;; Do whatever is necessary to keep the region active in XEmacs.
381 ;; Ignore byte-compiler warnings you might see. Also note that
382 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
383 ;; to take explicit action.
384 (and (boundp 'zmacs-region-stays)
385 (setq zmacs-region-stays t)))
386
387
388;; Major mode boilerplate
389
Barry Warsaw7ae77681994-12-12 20:38:05 +0000390;; define a mode-specific abbrev table for those who use such things
391(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000392 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000393(define-abbrev-table 'python-mode-abbrev-table nil)
394
Barry Warsaw7ae77681994-12-12 20:38:05 +0000395(defvar python-mode-hook nil
396 "*Hook called by `python-mode'.")
397
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000398;; in previous version of python-mode.el, the hook was incorrectly
399;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000400(and (fboundp 'make-obsolete-variable)
401 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
402
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000403(defvar py-mode-map ()
404 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000405(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000406 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000407 (setq py-mode-map (make-sparse-keymap))
408
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000409 ;; shadow global bindings for newline-and-indent w/ the py- version.
410 ;; BAW - this is extremely bad form, but I'm not going to change it
411 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000412 (mapcar (function (lambda (key)
413 (define-key
414 py-mode-map key 'py-newline-and-indent)))
415 (where-is-internal 'newline-and-indent))
416
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000417 ;; BAW - you could do it this way, but its not considered proper
418 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000419 (mapcar (function
420 (lambda (x)
421 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000422 '((":" . py-electric-colon)
423 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000424 ("\C-c|" . py-execute-region)
425 ("\C-c!" . py-shell)
426 ("\177" . py-delete-char)
427 ("\n" . py-newline-and-indent)
428 ("\C-c:" . py-guess-indent-offset)
429 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000430 ("\C-c\C-l" . py-shift-region-left)
431 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000432 ("\C-c<" . py-shift-region-left)
433 ("\C-c>" . py-shift-region-right)
434 ("\C-c\C-n" . py-next-statement)
435 ("\C-c\C-p" . py-previous-statement)
436 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000437 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000438 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000439 ("\C-c?" . py-describe-mode)
440 ("\C-c\C-hm" . py-describe-mode)
441 ("\e\C-a" . beginning-of-python-def-or-class)
442 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000443 ( "\e\C-h" . mark-python-def-or-class)))
444 ;; should do all keybindings this way
445 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
446 (define-key py-mode-map "\C-c\C-v" 'py-version)
447 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000448
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000449(defvar py-mode-syntax-table nil
450 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000451(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000452 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000453 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000454 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
455 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
456 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
457 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
458 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
459 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
460 ;; Add operator symbols misassigned in the std table
461 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
462 (modify-syntax-entry ?\% "." py-mode-syntax-table)
463 (modify-syntax-entry ?\& "." py-mode-syntax-table)
464 (modify-syntax-entry ?\* "." py-mode-syntax-table)
465 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
466 (modify-syntax-entry ?\- "." py-mode-syntax-table)
467 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
468 (modify-syntax-entry ?\< "." py-mode-syntax-table)
469 (modify-syntax-entry ?\= "." py-mode-syntax-table)
470 (modify-syntax-entry ?\> "." py-mode-syntax-table)
471 (modify-syntax-entry ?\| "." py-mode-syntax-table)
472 ;; For historical reasons, underscore is word class instead of
473 ;; symbol class. GNU conventions say it should be symbol class, but
474 ;; there's a natural conflict between what major mode authors want
475 ;; and what users expect from `forward-word' and `backward-word'.
476 ;; Guido and I have hashed this out and have decided to keep
477 ;; underscore in word class. If you're tempted to change it, try
478 ;; binding M-f and M-b to py-forward-into-nomenclature and
479 ;; py-backward-into-nomenclature instead.
480 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
481 ;; Both single quote and double quote are string delimiters
482 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
483 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
484 ;; backquote is open and close paren
485 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
486 ;; comment delimiters
487 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
488 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
489 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000490
Barry Warsawb3e81d51996-09-04 15:12:42 +0000491
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000492
Barry Warsaw42f707f1996-07-29 21:05:05 +0000493;; Menu definitions, only relevent if you have the easymenu.el package
494;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000495(defvar py-menu nil
496 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000497This menu will get created automatically if you have the `easymenu'
498package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000499
Barry Warsawc72c11c1997-08-09 06:42:08 +0000500(and (py-safe (require 'easymenu) t)
501 (easy-menu-define
502 py-menu py-mode-map "Python Mode menu"
503 '("Python"
504 ["Comment Out Region" py-comment-region (mark)]
505 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
506 "-"
507 ["Mark current block" py-mark-block t]
508 ["Mark current def" mark-python-def-or-class t]
509 ["Mark current class" (mark-python-def-or-class t) t]
510 "-"
511 ["Shift region left" py-shift-region-left (mark)]
512 ["Shift region right" py-shift-region-right (mark)]
513 "-"
514 ["Execute buffer" py-execute-buffer t]
515 ["Execute region" py-execute-region (mark)]
516 ["Start interpreter..." py-shell t]
517 "-"
518 ["Go to start of block" py-goto-block-up t]
519 ["Go to start of class" (beginning-of-python-def-or-class t) t]
520 ["Move to end of class" (end-of-python-def-or-class t) t]
521 ["Move to start of def" beginning-of-python-def-or-class t]
522 ["Move to end of def" end-of-python-def-or-class t]
523 "-"
524 ["Describe mode" py-describe-mode t]
525 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000526
Barry Warsaw81437461996-08-01 19:48:02 +0000527
528
529;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
530(defvar imenu-example--python-class-regexp
531 (concat ; <<classes>>
532 "\\(" ;
533 "^[ \t]*" ; newline and maybe whitespace
534 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
535 ; possibly multiple superclasses
536 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
537 "[ \t]*:" ; and the final :
538 "\\)" ; >>classes<<
539 )
540 "Regexp for Python classes for use with the imenu package."
541 )
542
543(defvar imenu-example--python-method-regexp
544 (concat ; <<methods and functions>>
545 "\\(" ;
546 "^[ \t]*" ; new line and maybe whitespace
547 "\\(def[ \t]+" ; function definitions start with def
548 "\\([a-zA-Z0-9_]+\\)" ; name is here
549 ; function arguments...
550 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
551 "\\)" ; end of def
552 "[ \t]*:" ; and then the :
553 "\\)" ; >>methods and functions<<
554 )
555 "Regexp for Python methods/functions for use with the imenu package."
556 )
557
558(defvar imenu-example--python-method-no-arg-parens '(2 8)
559 "Indicies into groups of the Python regexp for use with imenu.
560
561Using these values will result in smaller imenu lists, as arguments to
562functions are not listed.
563
564See the variable `imenu-example--python-show-method-args-p' for more
565information.")
566
567(defvar imenu-example--python-method-arg-parens '(2 7)
568 "Indicies into groups of the Python regexp for use with imenu.
569Using these values will result in large imenu lists, as arguments to
570functions are listed.
571
572See the variable `imenu-example--python-show-method-args-p' for more
573information.")
574
575;; Note that in this format, this variable can still be used with the
576;; imenu--generic-function. Otherwise, there is no real reason to have
577;; it.
578(defvar imenu-example--generic-python-expression
579 (cons
580 (concat
581 imenu-example--python-class-regexp
582 "\\|" ; or...
583 imenu-example--python-method-regexp
584 )
585 imenu-example--python-method-no-arg-parens)
586 "Generic Python expression which may be used directly with imenu.
587Used by setting the variable `imenu-generic-expression' to this value.
588Also, see the function \\[imenu-example--create-python-index] for a
589better alternative for finding the index.")
590
591;; These next two variables are used when searching for the python
592;; class/definitions. Just saving some time in accessing the
593;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000594(defvar imenu-example--python-generic-regexp nil)
595(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000596
597
598;;;###autoload
599(eval-when-compile
600 ;; Imenu isn't used in XEmacs, so just ignore load errors
601 (condition-case ()
602 (progn
603 (require 'cl)
604 (require 'imenu))
605 (error nil)))
606
607(defun imenu-example--create-python-index ()
608 "Python interface function for imenu package.
609Finds all python classes and functions/methods. Calls function
610\\[imenu-example--create-python-index-engine]. See that function for
611the details of how this works."
612 (setq imenu-example--python-generic-regexp
613 (car imenu-example--generic-python-expression))
614 (setq imenu-example--python-generic-parens
615 (if imenu-example--python-show-method-args-p
616 imenu-example--python-method-arg-parens
617 imenu-example--python-method-no-arg-parens))
618 (goto-char (point-min))
619 (imenu-example--create-python-index-engine nil))
620
621(defun imenu-example--create-python-index-engine (&optional start-indent)
622 "Function for finding imenu definitions in Python.
623
624Finds all definitions (classes, methods, or functions) in a Python
625file for the imenu package.
626
627Returns a possibly nested alist of the form
628
629 (INDEX-NAME . INDEX-POSITION)
630
631The second element of the alist may be an alist, producing a nested
632list as in
633
634 (INDEX-NAME . INDEX-ALIST)
635
636This function should not be called directly, as it calls itself
637recursively and requires some setup. Rather this is the engine for
638the function \\[imenu-example--create-python-index].
639
640It works recursively by looking for all definitions at the current
641indention level. When it finds one, it adds it to the alist. If it
642finds a definition at a greater indentation level, it removes the
643previous definition from the alist. In it's place it adds all
644definitions found at the next indentation level. When it finds a
645definition that is less indented then the current level, it retuns the
646alist it has created thus far.
647
648The optional argument START-INDENT indicates the starting indentation
649at which to continue looking for Python classes, methods, or
650functions. If this is not supplied, the function uses the indentation
651of the first definition found."
652 (let ((index-alist '())
653 (sub-method-alist '())
654 looking-p
655 def-name prev-name
656 cur-indent def-pos
657 (class-paren (first imenu-example--python-generic-parens))
658 (def-paren (second imenu-example--python-generic-parens)))
659 (setq looking-p
660 (re-search-forward imenu-example--python-generic-regexp
661 (point-max) t))
662 (while looking-p
663 (save-excursion
664 ;; used to set def-name to this value but generic-extract-name is
665 ;; new to imenu-1.14. this way it still works with imenu-1.11
666 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
667 (let ((cur-paren (if (match-beginning class-paren)
668 class-paren def-paren)))
669 (setq def-name
670 (buffer-substring (match-beginning cur-paren)
671 (match-end cur-paren))))
672 (beginning-of-line)
673 (setq cur-indent (current-indentation)))
674
675 ;; HACK: want to go to the next correct definition location. we
676 ;; explicitly list them here. would be better to have them in a
677 ;; list.
678 (setq def-pos
679 (or (match-beginning class-paren)
680 (match-beginning def-paren)))
681
682 ;; if we don't have a starting indent level, take this one
683 (or start-indent
684 (setq start-indent cur-indent))
685
686 ;; if we don't have class name yet, take this one
687 (or prev-name
688 (setq prev-name def-name))
689
690 ;; what level is the next definition on? must be same, deeper
691 ;; or shallower indentation
692 (cond
693 ;; at the same indent level, add it to the list...
694 ((= start-indent cur-indent)
695
696 ;; if we don't have push, use the following...
697 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
698 (push (cons def-name def-pos) index-alist))
699
700 ;; deeper indented expression, recur...
701 ((< start-indent cur-indent)
702
703 ;; the point is currently on the expression we're supposed to
704 ;; start on, so go back to the last expression. The recursive
705 ;; call will find this place again and add it to the correct
706 ;; list
707 (re-search-backward imenu-example--python-generic-regexp
708 (point-min) 'move)
709 (setq sub-method-alist (imenu-example--create-python-index-engine
710 cur-indent))
711
712 (if sub-method-alist
713 ;; we put the last element on the index-alist on the start
714 ;; of the submethod alist so the user can still get to it.
715 (let ((save-elmt (pop index-alist)))
716 (push (cons (imenu-create-submenu-name prev-name)
717 (cons save-elmt sub-method-alist))
718 index-alist))))
719
720 ;; found less indented expression, we're done.
721 (t
722 (setq looking-p nil)
723 (re-search-backward imenu-example--python-generic-regexp
724 (point-min) t)))
725 (setq prev-name def-name)
726 (and looking-p
727 (setq looking-p
728 (re-search-forward imenu-example--python-generic-regexp
729 (point-max) 'move))))
730 (nreverse index-alist)))
731
Barry Warsaw42f707f1996-07-29 21:05:05 +0000732
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000733;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000734(defun python-mode ()
735 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000736To submit a problem report, enter `\\[py-submit-bug-report]' from a
737`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
738documentation. To see what version of `python-mode' you are running,
739enter `\\[py-version]'.
740
741This mode knows about Python indentation, tokens, comments and
742continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000743
744COMMANDS
745\\{py-mode-map}
746VARIABLES
747
Barry Warsaw42f707f1996-07-29 21:05:05 +0000748py-indent-offset\t\tindentation increment
749py-block-comment-prefix\t\tcomment string used by comment-region
750py-python-command\t\tshell command to invoke Python interpreter
751py-scroll-process-buffer\t\talways scroll Python process buffer
752py-temp-directory\t\tdirectory used for temp files (if needed)
753py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000754 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000755 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000756 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000757 (make-local-variable 'font-lock-defaults)
758 (make-local-variable 'paragraph-separate)
759 (make-local-variable 'paragraph-start)
760 (make-local-variable 'require-final-newline)
761 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000762 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000763 (make-local-variable 'comment-start-skip)
764 (make-local-variable 'comment-column)
765 (make-local-variable 'indent-region-function)
766 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000767 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000768 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000769 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000770 (setq major-mode 'python-mode
771 mode-name "Python"
772 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000773 paragraph-separate "^[ \t]*$"
774 paragraph-start "^[ \t]*$"
775 require-final-newline t
776 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000777 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000778 comment-start-skip "# *"
779 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000780 indent-region-function 'py-indent-region
781 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000782 ;; tell add-log.el how to find the current function/method/variable
783 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000784 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000785 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000786 ;; add the menu
787 (if py-menu
788 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000789 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000790 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000791 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000792 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000793 ;;
794 ;; not sure where the magic comment has to be; to save time
795 ;; searching for a rarity, we give up if it's not found prior to the
796 ;; first executable statement.
797 ;;
798 ;; BAW - on first glance, this seems like complete hackery. Why was
799 ;; this necessary, and is it still necessary?
800 (let ((case-fold-search nil)
801 (start (point))
802 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000803 (if (re-search-forward
804 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
805 (prog2 (py-next-statement 1) (point) (goto-char 1))
806 t)
807 (progn
808 (setq new-tab-width
809 (string-to-int
810 (buffer-substring (match-beginning 1) (match-end 1))))
811 (if (= tab-width new-tab-width)
812 nil
813 (setq tab-width new-tab-width)
814 (message "Caution: tab-width changed to %d" new-tab-width)
815 (if py-beep-if-tab-change (beep)))))
816 (goto-char start))
817
Barry Warsaw755c6711996-08-01 20:02:55 +0000818 ;; install imenu
819 (setq imenu-create-index-function
820 (function imenu-example--create-python-index))
821 (if (fboundp 'imenu-add-to-menubar)
822 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
823
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000824 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000825 (if python-mode-hook
826 (run-hooks 'python-mode-hook)
827 (run-hooks 'py-mode-hook)))
828
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000829
Barry Warsawb91b7431995-03-14 15:55:20 +0000830;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000831(defun py-outdent-p ()
832 ;; returns non-nil if the current line should outdent one level
833 (save-excursion
834 (and (progn (back-to-indentation)
835 (looking-at py-outdent-re))
836 (progn (backward-to-indentation 1)
837 (while (or (looking-at py-blank-or-comment-re)
838 (bobp))
839 (backward-to-indentation 1))
840 (not (looking-at py-no-outdent-re)))
841 )))
842
Barry Warsawb91b7431995-03-14 15:55:20 +0000843(defun py-electric-colon (arg)
844 "Insert a colon.
845In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000846argument is provided, that many colons are inserted non-electrically.
847Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000848 (interactive "P")
849 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000850 ;; are we in a string or comment?
851 (if (save-excursion
852 (let ((pps (parse-partial-sexp (save-excursion
853 (beginning-of-python-def-or-class)
854 (point))
855 (point))))
856 (not (or (nth 3 pps) (nth 4 pps)))))
857 (save-excursion
858 (let ((here (point))
859 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000860 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000861 (if (and (not arg)
862 (py-outdent-p)
863 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000864 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000865 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000866 )
867 (setq outdent py-indent-offset))
868 ;; Don't indent, only outdent. This assumes that any lines that
869 ;; are already outdented relative to py-compute-indentation were
870 ;; put there on purpose. Its highly annoying to have `:' indent
871 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
872 ;; there a better way to determine this???
873 (if (< (current-indentation) indent) nil
874 (goto-char here)
875 (beginning-of-line)
876 (delete-horizontal-space)
877 (indent-to (- indent outdent))
878 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000879
880
Barry Warsaw7ae77681994-12-12 20:38:05 +0000881;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000882;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000883(defun py-shell ()
884 "Start an interactive Python interpreter in another window.
885This is like Shell mode, except that Python is running in the window
886instead of a shell. See the `Interactive Shell' and `Shell Mode'
887sections of the Emacs manual for details, especially for the key
888bindings active in the `*Python*' buffer.
889
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000890See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000891behavior in the process window.
892
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000893Warning: Don't use an interactive Python if you change sys.ps1 or
894sys.ps2 from their default values, or if you're running code that
895prints `>>> ' or `... ' at the start of a line. `python-mode' can't
896distinguish your output from Python's output, and assumes that `>>> '
897at the start of a line is a prompt from Python. Similarly, the Emacs
898Shell mode code assumes that both `>>> ' and `... ' at the start of a
899line are Python prompts. Bad things can happen if you fool either
900mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901
902Warning: If you do any editing *in* the process buffer *while* the
903buffer is accepting output from Python, do NOT attempt to `undo' the
904changes. Some of the output (nowhere near the parts you changed!) may
905be lost if you do. This appears to be an Emacs bug, an unfortunate
906interaction between undo and process filters; the same problem exists in
907non-Python process buffers using the default (Emacs-supplied) process
908filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000909 ;; BAW - should undo be disabled in the python process buffer, if
910 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000911 (interactive)
Barry Warsawe6648961997-07-10 15:58:36 +0000912 (require 'comint)
913 (switch-to-buffer-other-window (make-comint "Python" py-python-command))
914 (make-local-variable 'comint-prompt-regexp)
915 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
916 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
917 (set-syntax-table py-mode-syntax-table)
918 (local-set-key [tab] 'self-insert-command))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000919
920(defun py-execute-region (start end)
921 "Send the region between START and END to a Python interpreter.
922If there is a *Python* process it is used.
923
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000924Hint: If you want to execute part of a Python file several times
925\(e.g., perhaps you're developing a function and want to flesh it out
926a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
927the region of interest, and send the code to a *Python* process via
928`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000929
930Following are subtleties to note when using a *Python* process:
931
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000932If a *Python* process is used, the region is copied into a temporary
933file (in directory `py-temp-directory'), and an `execfile' command is
934sent to Python naming that file. If you send regions faster than
935Python can execute them, `python-mode' will save them into distinct
936temp files, and execute the next one in the queue the next time it
937sees a `>>> ' prompt from Python. Each time this happens, the process
938buffer is popped into a window (if it's not already in some window) so
939you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000941 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000942
943is inserted at the end.
944
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945Caution: No more than 26 regions can be pending at any given time.
946This limit is (indirectly) inherited from libc's mktemp(3).
947`python-mode' does not try to protect you from exceeding the limit.
948It's extremely unlikely that you'll get anywhere close to the limit in
949practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000950
951See the `\\[py-shell]' docs for additional warnings."
952 (interactive "r")
953 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000954 (let ((pyproc (get-process "Python"))
955 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000956 (if (null pyproc)
957 (shell-command-on-region start end py-python-command)
958 ;; else feed it thru a temp file
959 (setq fname (py-make-temp-name))
960 (write-region start end fname nil 'no-msg)
961 (setq py-file-queue (append py-file-queue (list fname)))
962 (if (cdr py-file-queue)
963 (message "File %s queued for execution" fname)
964 ;; else
965 (py-execute-file pyproc fname)))))
966
967(defun py-execute-file (pyproc fname)
968 (py-append-to-process-buffer
969 pyproc
970 (format "## working on region in file %s ...\n" fname))
971 (process-send-string pyproc (format "execfile('%s')\n" fname)))
972
973(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000974 (let ((curbuf (current-buffer))
975 (pbuf (process-buffer pyproc))
976 (pmark (process-mark pyproc))
977 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978
979 ;; make sure we switch to a different buffer at least once. if we
980 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981 ;; window, and point is before the end, and lots of output is
982 ;; coming at a fast pace, then (a) simple cursor-movement commands
983 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
984 ;; to have a visible effect (the window just doesn't get updated,
985 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
986 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000988 ;; #b makes no sense to me at all. #a almost makes sense: unless
989 ;; we actually change buffers, set_buffer_internal in buffer.c
990 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
991 ;; seems to make the Emacs command loop reluctant to update the
992 ;; display. Perhaps the default process filter in process.c's
993 ;; read_process_output has update_mode_lines++ for a similar
994 ;; reason? beats me ...
995
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000996 (unwind-protect
997 ;; make sure current buffer is restored
998 ;; BAW - we want to check to see if this still applies
999 (progn
1000 ;; mysterious ugly hack
1001 (if (eq curbuf pbuf)
1002 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001003
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001004 (set-buffer pbuf)
1005 (let* ((start (point))
1006 (goback (< start pmark))
1007 (goend (and (not goback) (= start (point-max))))
1008 (buffer-read-only nil))
1009 (goto-char pmark)
1010 (insert string)
1011 (move-marker pmark (point))
1012 (setq file-finished
1013 (and py-file-queue
1014 (equal ">>> "
1015 (buffer-substring
1016 (prog2 (beginning-of-line) (point)
1017 (goto-char pmark))
1018 (point)))))
1019 (if goback (goto-char start)
1020 ;; else
1021 (if py-scroll-process-buffer
1022 (let* ((pop-up-windows t)
1023 (pwin (display-buffer pbuf)))
1024 (set-window-point pwin (point)))))
1025 (set-buffer curbuf)
1026 (if file-finished
1027 (progn
1028 (py-delete-file-silently (car py-file-queue))
1029 (setq py-file-queue (cdr py-file-queue))
1030 (if py-file-queue
1031 (py-execute-file pyproc (car py-file-queue)))))
1032 (and goend
1033 (progn (set-buffer pbuf)
1034 (goto-char (point-max))))
1035 ))
1036 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001037
1038(defun py-execute-buffer ()
1039 "Send the contents of the buffer to a Python interpreter.
1040If there is a *Python* process buffer it is used. If a clipping
1041restriction is in effect, only the accessible portion of the buffer is
1042sent. A trailing newline will be supplied if needed.
1043
1044See the `\\[py-execute-region]' docs for an account of some subtleties."
1045 (interactive)
1046 (py-execute-region (point-min) (point-max)))
1047
1048
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001049
1050;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001051(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001053
Barry Warsaw7ae77681994-12-12 20:38:05 +00001054If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001055Deletion is performed by calling the function in `py-delete-function'
1056with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001057
1058Else if point is at the leftmost non-blank character of a line that is
1059neither a continuation line nor a non-indenting comment line, or if
1060point is at the end of a blank line, reduces the indentation to match
1061that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001062opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001063of where you are. With numeric count, outdents that many blocks (but
1064not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001065
1066Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001067needed so that only a single column position is deleted. Numeric
1068argument delets that many characters."
1069 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (if (or (/= (current-indentation) (current-column))
1071 (bolp)
1072 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001073 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001074 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001075 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 ;; else indent the same as the colon line that opened the block
1077
1078 ;; force non-blank so py-goto-block-up doesn't ignore it
1079 (insert-char ?* 1)
1080 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001081 (let ((base-indent 0) ; indentation of base line
1082 (base-text "") ; and text of base line
1083 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001084 (save-excursion
1085 (while (< 0 count)
1086 (condition-case nil ; in case no enclosing block
1087 (progn
1088 (py-goto-block-up 'no-mark)
1089 (setq base-indent (current-indentation)
1090 base-text (py-suck-up-leading-text)
1091 base-found-p t))
1092 (error nil))
1093 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094 (delete-char 1) ; toss the dummy character
1095 (delete-horizontal-space)
1096 (indent-to base-indent)
1097 (if base-found-p
1098 (message "Closes block: %s" base-text)))))
1099
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001100;; required for pending-del and delsel modes
1101(put 'py-delete-char 'delete-selection 'supersede)
1102(put 'py-delete-char 'pending-delete 'supersede)
1103
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001104(defun py-indent-line (&optional arg)
1105 "Fix the indentation of the current line according to Python rules.
1106With \\[universal-argument], ignore outdenting rules for block
1107closing statements (e.g. return, raise, break, continue, pass)
1108
1109This function is normally bound to `indent-line-function' so
1110\\[indent-for-tab-command] will call it."
1111 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001112 (let* ((ci (current-indentation))
1113 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001114 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001115 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001116 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001117 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001118 (if (/= ci need)
1119 (save-excursion
1120 (beginning-of-line)
1121 (delete-horizontal-space)
1122 (indent-to need)))
1123 (if move-to-indentation-p (back-to-indentation))))
1124
1125(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001126 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001127This is just `strives to' because correct indentation can't be computed
1128from scratch for Python code. In general, deletes the whitespace before
1129point, inserts a newline, and takes an educated guess as to how you want
1130the new line indented."
1131 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001132 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001133 (if (< ci (current-column)) ; if point beyond indentation
1134 (newline-and-indent)
1135 ;; else try to act like newline-and-indent "normally" acts
1136 (beginning-of-line)
1137 (insert-char ?\n 1)
1138 (move-to-column ci))))
1139
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001140(defun py-compute-indentation (honor-block-close-p)
1141 ;; implements all the rules for indentation computation. when
1142 ;; honor-block-close-p is non-nil, statements such as return, raise,
1143 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001144 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001145 (let ((pps (parse-partial-sexp (save-excursion
1146 (beginning-of-python-def-or-class)
1147 (point))
1148 (point))))
1149 (beginning-of-line)
1150 (cond
1151 ;; are we inside a string or comment?
1152 ((or (nth 3 pps) (nth 4 pps))
1153 (save-excursion
1154 (if (not py-align-multiline-strings-p) 0
1155 ;; skip back over blank & non-indenting comment lines
1156 ;; note: will skip a blank or non-indenting comment line
1157 ;; that happens to be a continuation line too
1158 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1159 (back-to-indentation)
1160 (current-column))))
1161 ;; are we on a continuation line?
1162 ((py-continuation-line-p)
1163 (let ((startpos (point))
1164 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001165 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001166 (if open-bracket-pos
1167 (progn
1168 ;; align with first item in list; else a normal
1169 ;; indent beyond the line with the open bracket
1170 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1171 ;; is the first list item on the same line?
1172 (skip-chars-forward " \t")
1173 (if (null (memq (following-char) '(?\n ?# ?\\)))
1174 ; yes, so line up with it
1175 (current-column)
1176 ;; first list item on another line, or doesn't exist yet
1177 (forward-line 1)
1178 (while (and (< (point) startpos)
1179 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1180 (forward-line 1))
1181 (if (< (point) startpos)
1182 ;; again mimic the first list item
1183 (current-indentation)
1184 ;; else they're about to enter the first item
1185 (goto-char open-bracket-pos)
1186 (+ (current-indentation) py-indent-offset))))
1187
1188 ;; else on backslash continuation line
1189 (forward-line -1)
1190 (if (py-continuation-line-p) ; on at least 3rd line in block
1191 (current-indentation) ; so just continue the pattern
1192 ;; else started on 2nd line in block, so indent more.
1193 ;; if base line is an assignment with a start on a RHS,
1194 ;; indent to 2 beyond the leftmost "="; else skip first
1195 ;; chunk of non-whitespace characters on base line, + 1 more
1196 ;; column
1197 (end-of-line)
1198 (setq endpos (point) searching t)
1199 (back-to-indentation)
1200 (setq startpos (point))
1201 ;; look at all "=" from left to right, stopping at first
1202 ;; one not nested in a list or string
1203 (while searching
1204 (skip-chars-forward "^=" endpos)
1205 (if (= (point) endpos)
1206 (setq searching nil)
1207 (forward-char 1)
1208 (setq state (parse-partial-sexp startpos (point)))
1209 (if (and (zerop (car state)) ; not in a bracket
1210 (null (nth 3 state))) ; & not in a string
1211 (progn
1212 (setq searching nil) ; done searching in any case
1213 (setq found
1214 (not (or
1215 (eq (following-char) ?=)
1216 (memq (char-after (- (point) 2))
1217 '(?< ?> ?!)))))))))
1218 (if (or (not found) ; not an assignment
1219 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1220 (progn
1221 (goto-char startpos)
1222 (skip-chars-forward "^ \t\n")))
1223 (1+ (current-column))))))
1224
1225 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001226 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001227
Barry Warsawa7891711996-08-01 15:53:09 +00001228 ;; Dfn: "Indenting comment line". A line containing only a
1229 ;; comment, but which is treated like a statement for
1230 ;; indentation calculation purposes. Such lines are only
1231 ;; treated specially by the mode; they are not treated
1232 ;; specially by the Python interpreter.
1233
1234 ;; The rules for indenting comment lines are a line where:
1235 ;; - the first non-whitespace character is `#', and
1236 ;; - the character following the `#' is whitespace, and
1237 ;; - the line is outdented with respect to (i.e. to the left
1238 ;; of) the indentation of the preceding non-blank line.
1239
1240 ;; The first non-blank line following an indenting comment
1241 ;; line is given the same amount of indentation as the
1242 ;; indenting comment line.
1243
1244 ;; All other comment-only lines are ignored for indentation
1245 ;; purposes.
1246
1247 ;; Are we looking at a comment-only line which is *not* an
1248 ;; indenting comment line? If so, we assume that its been
1249 ;; placed at the desired indentation, so leave it alone.
1250 ;; Indenting comment lines are aligned as statements down
1251 ;; below.
1252 ((and (looking-at "[ \t]*#[^ \t\n]")
1253 ;; NOTE: this test will not be performed in older Emacsen
1254 (fboundp 'forward-comment)
1255 (<= (current-indentation)
1256 (save-excursion
1257 (forward-comment (- (point-max)))
1258 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001259 (current-indentation))
1260
1261 ;; else indentation based on that of the statement that
1262 ;; precedes us; use the first line of that statement to
1263 ;; establish the base, in case the user forced a non-std
1264 ;; indentation for the continuation lines (if any)
1265 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001266 ;; skip back over blank & non-indenting comment lines note:
1267 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001268 ;; happens to be a continuation line too. use fast Emacs 19
1269 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001270 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001271 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001272 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001273 (let (done)
1274 (while (not done)
1275 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1276 nil 'move)
1277 (setq done (or (eq py-honor-comment-indentation t)
1278 (bobp)
1279 (/= (following-char) ?#)
1280 (not (zerop (current-column)))))
1281 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001282 ;; if we landed inside a string, go to the beginning of that
1283 ;; string. this handles triple quoted, multi-line spanning
1284 ;; strings.
1285 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001286 (+ (current-indentation)
1287 (if (py-statement-opens-block-p)
1288 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001289 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001290 (- py-indent-offset)
1291 0)))
1292 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001293
1294(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001295 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001296By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001297`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001298Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001299`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001300their own buffer-local copy), both those currently existing and those
1301created later in the Emacs session.
1302
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001303Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001304There's no excuse for such foolishness, but sometimes you have to deal
1305with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001306`py-indent-offset' to what it thinks it was when they created the
1307mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001308
1309Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001310looking for a line that opens a block of code. `py-indent-offset' is
1311set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001312statement following it. If the search doesn't succeed going forward,
1313it's tried again going backward."
1314 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001315 (let (new-value
1316 (start (point))
1317 restart
1318 (found nil)
1319 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001320 (py-goto-initial-line)
1321 (while (not (or found (eobp)))
1322 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1323 (progn
1324 (setq restart (point))
1325 (py-goto-initial-line)
1326 (if (py-statement-opens-block-p)
1327 (setq found t)
1328 (goto-char restart)))))
1329 (if found
1330 ()
1331 (goto-char start)
1332 (py-goto-initial-line)
1333 (while (not (or found (bobp)))
1334 (setq found
1335 (and
1336 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1337 (or (py-goto-initial-line) t) ; always true -- side effect
1338 (py-statement-opens-block-p)))))
1339 (setq colon-indent (current-indentation)
1340 found (and found (zerop (py-next-statement 1)))
1341 new-value (- (current-indentation) colon-indent))
1342 (goto-char start)
1343 (if found
1344 (progn
1345 (funcall (if global 'kill-local-variable 'make-local-variable)
1346 'py-indent-offset)
1347 (setq py-indent-offset new-value)
1348 (message "%s value of py-indent-offset set to %d"
1349 (if global "Global" "Local")
1350 py-indent-offset))
1351 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1352
1353(defun py-shift-region (start end count)
1354 (save-excursion
1355 (goto-char end) (beginning-of-line) (setq end (point))
1356 (goto-char start) (beginning-of-line) (setq start (point))
1357 (indent-rigidly start end count)))
1358
1359(defun py-shift-region-left (start end &optional count)
1360 "Shift region of Python code to the left.
1361The lines from the line containing the start of the current region up
1362to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001364
1365If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001366many columns. With no active region, outdent only the current line.
1367You cannot outdent the region if any line is already at column zero."
1368 (interactive
1369 (let ((p (point))
1370 (m (mark))
1371 (arg current-prefix-arg))
1372 (if m
1373 (list (min p m) (max p m) arg)
1374 (list p (save-excursion (forward-line 1) (point)) arg))))
1375 ;; if any line is at column zero, don't shift the region
1376 (save-excursion
1377 (goto-char start)
1378 (while (< (point) end)
1379 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001380 (if (and (zerop (current-column))
1381 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001382 (error "Region is at left edge."))
1383 (forward-line 1)))
1384 (py-shift-region start end (- (prefix-numeric-value
1385 (or count py-indent-offset))))
1386 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001387
1388(defun py-shift-region-right (start end &optional count)
1389 "Shift region of Python code to the right.
1390The lines from the line containing the start of the current region up
1391to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393
1394If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001395many columns. With no active region, indent only the current line."
1396 (interactive
1397 (let ((p (point))
1398 (m (mark))
1399 (arg current-prefix-arg))
1400 (if m
1401 (list (min p m) (max p m) arg)
1402 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001403 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001404 (or count py-indent-offset)))
1405 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406
1407(defun py-indent-region (start end &optional indent-offset)
1408 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001409
Barry Warsaw7ae77681994-12-12 20:38:05 +00001410The lines from the line containing the start of the current region up
1411to (but not including) the line containing the end of the region are
1412reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001413character in the first column, the first line is left alone and the
1414rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001415region is reindented with respect to the (closest code or indenting
1416comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001417
1418This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001419control structures are introduced or removed, or to reformat code
1420using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001421
1422If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001423the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001424used.
1425
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001426Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001427is called! This function does not compute proper indentation from
1428scratch (that's impossible in Python), it merely adjusts the existing
1429indentation to be correct in context.
1430
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001431Warning: This function really has no idea what to do with
1432non-indenting comment lines, and shifts them as if they were indenting
1433comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001434
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001435Special cases: whitespace is deleted from blank lines; continuation
1436lines are shifted by the same amount their initial line was shifted,
1437in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001438initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001439 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001440 (save-excursion
1441 (goto-char end) (beginning-of-line) (setq end (point-marker))
1442 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001443 (let ((py-indent-offset (prefix-numeric-value
1444 (or indent-offset py-indent-offset)))
1445 (indents '(-1)) ; stack of active indent levels
1446 (target-column 0) ; column to which to indent
1447 (base-shifted-by 0) ; amount last base line was shifted
1448 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001449 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001450 0))
1451 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001452 (while (< (point) end)
1453 (setq ci (current-indentation))
1454 ;; figure out appropriate target column
1455 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001456 ((or (eq (following-char) ?#) ; comment in column 1
1457 (looking-at "[ \t]*$")) ; entirely blank
1458 (setq target-column 0))
1459 ((py-continuation-line-p) ; shift relative to base line
1460 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461 (t ; new base line
1462 (if (> ci (car indents)) ; going deeper; push it
1463 (setq indents (cons ci indents))
1464 ;; else we should have seen this indent before
1465 (setq indents (memq ci indents)) ; pop deeper indents
1466 (if (null indents)
1467 (error "Bad indentation in region, at line %d"
1468 (save-restriction
1469 (widen)
1470 (1+ (count-lines 1 (point)))))))
1471 (setq target-column (+ indent-base
1472 (* py-indent-offset
1473 (- (length indents) 2))))
1474 (setq base-shifted-by (- target-column ci))))
1475 ;; shift as needed
1476 (if (/= ci target-column)
1477 (progn
1478 (delete-horizontal-space)
1479 (indent-to target-column)))
1480 (forward-line 1))))
1481 (set-marker end nil))
1482
Barry Warsawa7891711996-08-01 15:53:09 +00001483(defun py-comment-region (beg end &optional arg)
1484 "Like `comment-region' but uses double hash (`#') comment starter."
1485 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001486 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001487 (comment-region beg end arg)))
1488
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001489
1490;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491(defun py-previous-statement (count)
1492 "Go to the start of previous Python statement.
1493If the statement at point is the i'th Python statement, goes to the
1494start of statement i-COUNT. If there is no such statement, goes to the
1495first statement. Returns count of statements left to move.
1496`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001497 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001498 (if (< count 0) (py-next-statement (- count))
1499 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001500 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001501 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001502 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001503 (> count 0)
1504 (zerop (forward-line -1))
1505 (py-goto-statement-at-or-above))
1506 (setq count (1- count)))
1507 (if (> count 0) (goto-char start)))
1508 count))
1509
1510(defun py-next-statement (count)
1511 "Go to the start of next Python statement.
1512If the statement at point is the i'th Python statement, goes to the
1513start of statement i+COUNT. If there is no such statement, goes to the
1514last statement. Returns count of statements left to move. `Statements'
1515do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001516 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001517 (if (< count 0) (py-previous-statement (- count))
1518 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001519 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001520 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001522 (> count 0)
1523 (py-goto-statement-below))
1524 (setq count (1- count)))
1525 (if (> count 0) (goto-char start)))
1526 count))
1527
1528(defun py-goto-block-up (&optional nomark)
1529 "Move up to start of current block.
1530Go to the statement that starts the smallest enclosing block; roughly
1531speaking, this will be the closest preceding statement that ends with a
1532colon and is indented less than the statement you started on. If
1533successful, also sets the mark to the starting point.
1534
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001535`\\[py-mark-block]' can be used afterward to mark the whole code
1536block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001537
1538If called from a program, the mark will not be set if optional argument
1539NOMARK is not nil."
1540 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541 (let ((start (point))
1542 (found nil)
1543 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544 (py-goto-initial-line)
1545 ;; if on blank or non-indenting comment line, use the preceding stmt
1546 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1547 (progn
1548 (py-goto-statement-at-or-above)
1549 (setq found (py-statement-opens-block-p))))
1550 ;; search back for colon line indented less
1551 (setq initial-indent (current-indentation))
1552 (if (zerop initial-indent)
1553 ;; force fast exit
1554 (goto-char (point-min)))
1555 (while (not (or found (bobp)))
1556 (setq found
1557 (and
1558 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1559 (or (py-goto-initial-line) t) ; always true -- side effect
1560 (< (current-indentation) initial-indent)
1561 (py-statement-opens-block-p))))
1562 (if found
1563 (progn
1564 (or nomark (push-mark start))
1565 (back-to-indentation))
1566 (goto-char start)
1567 (error "Enclosing block not found"))))
1568
1569(defun beginning-of-python-def-or-class (&optional class)
1570 "Move point to start of def (or class, with prefix arg).
1571
1572Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001573arg, looks for a `class' instead. The docs assume the `def' case;
1574just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001575
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001576If point is in a def statement already, and after the `d', simply
1577moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579Else (point is not in a def statement, or at or before the `d' of a
1580def statement), searches for the closest preceding def statement, and
1581leaves point at its start. If no such statement can be found, leaves
1582point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001583
1584Returns t iff a def statement is found by these rules.
1585
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001586Note that doing this command repeatedly will take you closer to the
1587start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001589If you want to mark the current def/class, see
1590`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001591 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001592 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1593 (start-of-line (progn (beginning-of-line) (point)))
1594 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001595 (if (or (/= start-of-stmt start-of-line)
1596 (not at-or-before-p))
1597 (end-of-line)) ; OK to match on this line
1598 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001599 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001600
1601(defun end-of-python-def-or-class (&optional class)
1602 "Move point beyond end of def (or class, with prefix arg) body.
1603
1604By default, looks for an appropriate `def'. If you supply a prefix arg,
1605looks for a `class' instead. The docs assume the `def' case; just
1606substitute `class' for `def' for the other case.
1607
1608If point is in a def statement already, this is the def we use.
1609
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001610Else if the def found by `\\[beginning-of-python-def-or-class]'
1611contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001612
1613Else we search forward for the closest following def, and use that.
1614
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001615If a def can be found by these rules, point is moved to the start of
1616the line immediately following the def block, and the position of the
1617start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001618
1619Else point is moved to the end of the buffer, and nil is returned.
1620
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001621Note that doing this command repeatedly will take you closer to the
1622end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001623
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001624If you want to mark the current def/class, see
1625`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001626 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001627 (let ((start (progn (py-goto-initial-line) (point)))
1628 (which (if class "class" "def"))
1629 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001630 ;; move point to start of appropriate def/class
1631 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1632 (setq state 'at-beginning)
1633 ;; else see if beginning-of-python-def-or-class hits container
1634 (if (and (beginning-of-python-def-or-class class)
1635 (progn (py-goto-beyond-block)
1636 (> (point) start)))
1637 (setq state 'at-end)
1638 ;; else search forward
1639 (goto-char start)
1640 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1641 (progn (setq state 'at-beginning)
1642 (beginning-of-line)))))
1643 (cond
1644 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1645 ((eq state 'at-end) t)
1646 ((eq state 'not-found) nil)
1647 (t (error "internal error in end-of-python-def-or-class")))))
1648
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001649
1650;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001651(defun py-mark-block (&optional extend just-move)
1652 "Mark following block of lines. With prefix arg, mark structure.
1653Easier to use than explain. It sets the region to an `interesting'
1654block of succeeding lines. If point is on a blank line, it goes down to
1655the next non-blank line. That will be the start of the region. The end
1656of the region depends on the kind of line at the start:
1657
1658 - If a comment, the region will include all succeeding comment lines up
1659 to (but not including) the next non-comment line (if any).
1660
1661 - Else if a prefix arg is given, and the line begins one of these
1662 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001663
1664 if elif else try except finally for while def class
1665
Barry Warsaw7ae77681994-12-12 20:38:05 +00001666 the region will be set to the body of the structure, including
1667 following blocks that `belong' to it, but excluding trailing blank
1668 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669 and all (if any) of the following `except' and `finally' blocks
1670 that belong to the `try' structure will be in the region. Ditto
1671 for if/elif/else, for/else and while/else structures, and (a bit
1672 degenerate, since they're always one-block structures) def and
1673 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674
1675 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001676 block (see list above), and the block is not a `one-liner' (i.e.,
1677 the statement ends with a colon, not with code), the region will
1678 include all succeeding lines up to (but not including) the next
1679 code statement (if any) that's indented no more than the starting
1680 line, except that trailing blank and comment lines are excluded.
1681 E.g., if the starting line begins a multi-statement `def'
1682 structure, the region will be set to the full function definition,
1683 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001684
1685 - Else the region will include all succeeding lines up to (but not
1686 including) the next blank line, or code or indenting-comment line
1687 indented strictly less than the starting line. Trailing indenting
1688 comment lines are included in this case, but not trailing blank
1689 lines.
1690
1691A msg identifying the location of the mark is displayed in the echo
1692area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1693
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001694If called from a program, optional argument EXTEND plays the role of
1695the prefix arg, and if optional argument JUST-MOVE is not nil, just
1696moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697 (interactive "P") ; raw prefix arg
1698 (py-goto-initial-line)
1699 ;; skip over blank lines
1700 (while (and
1701 (looking-at "[ \t]*$") ; while blank line
1702 (not (eobp))) ; & somewhere to go
1703 (forward-line 1))
1704 (if (eobp)
1705 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001706 (let ((initial-pos (point))
1707 (initial-indent (current-indentation))
1708 last-pos ; position of last stmt in region
1709 (followers
1710 '((if elif else) (elif elif else) (else)
1711 (try except finally) (except except) (finally)
1712 (for else) (while else)
1713 (def) (class) ) )
1714 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001715
1716 (cond
1717 ;; if comment line, suck up the following comment lines
1718 ((looking-at "[ \t]*#")
1719 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1720 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1721 (setq last-pos (point)))
1722
1723 ;; else if line is a block line and EXTEND given, suck up
1724 ;; the whole structure
1725 ((and extend
1726 (setq first-symbol (py-suck-up-first-keyword) )
1727 (assq first-symbol followers))
1728 (while (and
1729 (or (py-goto-beyond-block) t) ; side effect
1730 (forward-line -1) ; side effect
1731 (setq last-pos (point)) ; side effect
1732 (py-goto-statement-below)
1733 (= (current-indentation) initial-indent)
1734 (setq next-symbol (py-suck-up-first-keyword))
1735 (memq next-symbol (cdr (assq first-symbol followers))))
1736 (setq first-symbol next-symbol)))
1737
1738 ;; else if line *opens* a block, search for next stmt indented <=
1739 ((py-statement-opens-block-p)
1740 (while (and
1741 (setq last-pos (point)) ; always true -- side effect
1742 (py-goto-statement-below)
1743 (> (current-indentation) initial-indent))
1744 nil))
1745
1746 ;; else plain code line; stop at next blank line, or stmt or
1747 ;; indenting comment line indented <
1748 (t
1749 (while (and
1750 (setq last-pos (point)) ; always true -- side effect
1751 (or (py-goto-beyond-final-line) t)
1752 (not (looking-at "[ \t]*$")) ; stop at blank line
1753 (or
1754 (>= (current-indentation) initial-indent)
1755 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1756 nil)))
1757
1758 ;; skip to end of last stmt
1759 (goto-char last-pos)
1760 (py-goto-beyond-final-line)
1761
1762 ;; set mark & display
1763 (if just-move
1764 () ; just return
1765 (push-mark (point) 'no-msg)
1766 (forward-line -1)
1767 (message "Mark set after: %s" (py-suck-up-leading-text))
1768 (goto-char initial-pos))))
1769
1770(defun mark-python-def-or-class (&optional class)
1771 "Set region to body of def (or class, with prefix arg) enclosing point.
1772Pushes the current mark, then point, on the mark ring (all language
1773modes do this, but although it's handy it's never documented ...).
1774
1775In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001776hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1777`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778
1779And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780Turned out that was more confusing than useful: the `goto start' and
1781`goto end' commands are usually used to search through a file, and
1782people expect them to act a lot like `search backward' and `search
1783forward' string-search commands. But because Python `def' and `class'
1784can nest to arbitrary levels, finding the smallest def containing
1785point cannot be done via a simple backward search: the def containing
1786point may not be the closest preceding def, or even the closest
1787preceding def that's indented less. The fancy algorithm required is
1788appropriate for the usual uses of this `mark' command, but not for the
1789`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001790
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001791So the def marked by this command may not be the one either of the
1792`goto' commands find: If point is on a blank or non-indenting comment
1793line, moves back to start of the closest preceding code statement or
1794indenting comment line. If this is a `def' statement, that's the def
1795we use. Else searches for the smallest enclosing `def' block and uses
1796that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001798When an enclosing def is found: The mark is left immediately beyond
1799the last line of the def block. Point is left at the start of the
1800def, except that: if the def is preceded by a number of comment lines
1801followed by (at most) one optional blank line, point is left at the
1802start of the comments; else if the def is preceded by a blank line,
1803point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001804
1805The intent is to mark the containing def/class and its associated
1806documentation, to make moving and duplicating functions and classes
1807pleasant."
1808 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001809 (let ((start (point))
1810 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811 (push-mark start)
1812 (if (not (py-go-up-tree-to-keyword which))
1813 (progn (goto-char start)
1814 (error "Enclosing %s not found" which))
1815 ;; else enclosing def/class found
1816 (setq start (point))
1817 (py-goto-beyond-block)
1818 (push-mark (point))
1819 (goto-char start)
1820 (if (zerop (forward-line -1)) ; if there is a preceding line
1821 (progn
1822 (if (looking-at "[ \t]*$") ; it's blank
1823 (setq start (point)) ; so reset start point
1824 (goto-char start)) ; else try again
1825 (if (zerop (forward-line -1))
1826 (if (looking-at "[ \t]*#") ; a comment
1827 ;; look back for non-comment line
1828 ;; tricky: note that the regexp matches a blank
1829 ;; line, cuz \n is in the 2nd character class
1830 (and
1831 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1832 (forward-line 1))
1833 ;; no comment, so go back
1834 (goto-char start))))))))
1835
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001836;; ripped from cc-mode
1837(defun py-forward-into-nomenclature (&optional arg)
1838 "Move forward to end of a nomenclature section or word.
1839With arg, to it arg times.
1840
1841A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1842 (interactive "p")
1843 (let ((case-fold-search nil))
1844 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001845 (re-search-forward
1846 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1847 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001848 (while (and (< arg 0)
1849 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001850 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001851 (point-min) 0))
1852 (forward-char 1)
1853 (setq arg (1+ arg)))))
1854 (py-keep-region-active))
1855
1856(defun py-backward-into-nomenclature (&optional arg)
1857 "Move backward to beginning of a nomenclature section or word.
1858With optional ARG, move that many times. If ARG is negative, move
1859forward.
1860
1861A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1862 (interactive "p")
1863 (py-forward-into-nomenclature (- arg))
1864 (py-keep-region-active))
1865
1866
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001867
1868;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001869
1870;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1872;; out of the right places, along with the keys they're on & current
1873;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874(defun py-dump-help-string (str)
1875 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001876 (let ((locals (buffer-local-variables))
1877 funckind funcname func funcdoc
1878 (start 0) mstart end
1879 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001880 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1881 (setq mstart (match-beginning 0) end (match-end 0)
1882 funckind (substring str (match-beginning 1) (match-end 1))
1883 funcname (substring str (match-beginning 2) (match-end 2))
1884 func (intern funcname))
1885 (princ (substitute-command-keys (substring str start mstart)))
1886 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001887 ((equal funckind "c") ; command
1888 (setq funcdoc (documentation func)
1889 keys (concat
1890 "Key(s): "
1891 (mapconcat 'key-description
1892 (where-is-internal func py-mode-map)
1893 ", "))))
1894 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001895 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896 keys (if (assq func locals)
1897 (concat
1898 "Local/Global values: "
1899 (prin1-to-string (symbol-value func))
1900 " / "
1901 (prin1-to-string (default-value func)))
1902 (concat
1903 "Value: "
1904 (prin1-to-string (symbol-value func))))))
1905 (t ; unexpected
1906 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001907 (princ (format "\n-> %s:\t%s\t%s\n\n"
1908 (if (equal funckind "c") "Command" "Variable")
1909 funcname keys))
1910 (princ funcdoc)
1911 (terpri)
1912 (setq start end))
1913 (princ (substitute-command-keys (substring str start))))
1914 (print-help-return-message)))
1915
1916(defun py-describe-mode ()
1917 "Dump long form of Python-mode docs."
1918 (interactive)
1919 (py-dump-help-string "Major mode for editing Python files.
1920Knows about Python indentation, tokens, comments and continuation lines.
1921Paragraphs are separated by blank lines only.
1922
1923Major sections below begin with the string `@'; specific function and
1924variable docs begin with `->'.
1925
1926@EXECUTING PYTHON CODE
1927
1928\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1929\\[py-execute-region]\tsends the current region
1930\\[py-shell]\tstarts a Python interpreter window; this will be used by
1931\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1932%c:py-execute-buffer
1933%c:py-execute-region
1934%c:py-shell
1935
1936@VARIABLES
1937
1938py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001939py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940
1941py-python-command\tshell command to invoke Python interpreter
1942py-scroll-process-buffer\talways scroll Python process buffer
1943py-temp-directory\tdirectory used for temp files (if needed)
1944
1945py-beep-if-tab-change\tring the bell if tab-width is changed
1946%v:py-indent-offset
1947%v:py-block-comment-prefix
1948%v:py-python-command
1949%v:py-scroll-process-buffer
1950%v:py-temp-directory
1951%v:py-beep-if-tab-change
1952
1953@KINDS OF LINES
1954
1955Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001956preceding line ends with a backslash that's not part of a comment, or
1957the paren/bracket/brace nesting level at the start of the line is
1958non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001959
1960An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961possibly blanks or tabs), a `comment line' (leftmost non-blank
1962character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001963
1964Comment Lines
1965
1966Although all comment lines are treated alike by Python, Python mode
1967recognizes two kinds that act differently with respect to indentation.
1968
1969An `indenting comment line' is a comment line with a blank, tab or
1970nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001971treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001972indenting comment line will be indented like the comment line. All
1973other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974following the initial `#') are `non-indenting comment lines', and
1975their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001976
1977Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001978whenever possible. Non-indenting comment lines are useful in cases
1979like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001980
1981\ta = b # a very wordy single-line comment that ends up being
1982\t #... continued onto another line
1983
1984\tif a == b:
1985##\t\tprint 'panic!' # old code we've `commented out'
1986\t\treturn a
1987
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001988Since the `#...' and `##' comment lines have a non-whitespace
1989character following the initial `#', Python mode ignores them when
1990computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991
1992Continuation Lines and Statements
1993
1994The Python-mode commands generally work on statements instead of on
1995individual lines, where a `statement' is a comment or blank line, or a
1996code line and all of its following continuation lines (if any)
1997considered as a single logical unit. The commands in this mode
1998generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999statement containing point, even if point happens to be in the middle
2000of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001
2002
2003@INDENTATION
2004
2005Primarily for entering new code:
2006\t\\[indent-for-tab-command]\t indent line appropriately
2007\t\\[py-newline-and-indent]\t insert newline, then indent
2008\t\\[py-delete-char]\t reduce indentation, or delete single character
2009
2010Primarily for reindenting existing code:
2011\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2012\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2013
2014\t\\[py-indent-region]\t reindent region to match its context
2015\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2016\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2017
2018Unlike most programming languages, Python uses indentation, and only
2019indentation, to specify block structure. Hence the indentation supplied
2020automatically by Python-mode is just an educated guess: only you know
2021the block structure you intend, so only you can supply correct
2022indentation.
2023
2024The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2025the indentation of preceding statements. E.g., assuming
2026py-indent-offset is 4, after you enter
2027\tif a > 0: \\[py-newline-and-indent]
2028the cursor will be moved to the position of the `_' (_ is not a
2029character in the file, it's just used here to indicate the location of
2030the cursor):
2031\tif a > 0:
2032\t _
2033If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2034to
2035\tif a > 0:
2036\t c = d
2037\t _
2038Python-mode cannot know whether that's what you intended, or whether
2039\tif a > 0:
2040\t c = d
2041\t_
2042was your intent. In general, Python-mode either reproduces the
2043indentation of the (closest code or indenting-comment) preceding
2044statement, or adds an extra py-indent-offset blanks if the preceding
2045statement has `:' as its last significant (non-whitespace and non-
2046comment) character. If the suggested indentation is too much, use
2047\\[py-delete-char] to reduce it.
2048
2049Continuation lines are given extra indentation. If you don't like the
2050suggested indentation, change it to something you do like, and Python-
2051mode will strive to indent later lines of the statement in the same way.
2052
2053If a line is a continuation line by virtue of being in an unclosed
2054paren/bracket/brace structure (`list', for short), the suggested
2055indentation depends on whether the current line contains the first item
2056in the list. If it does, it's indented py-indent-offset columns beyond
2057the indentation of the line containing the open bracket. If you don't
2058like that, change it by hand. The remaining items in the list will mimic
2059whatever indentation you give to the first item.
2060
2061If a line is a continuation line because the line preceding it ends with
2062a backslash, the third and following lines of the statement inherit their
2063indentation from the line preceding them. The indentation of the second
2064line in the statement depends on the form of the first (base) line: if
2065the base line is an assignment statement with anything more interesting
2066than the backslash following the leftmost assigning `=', the second line
2067is indented two columns beyond that `='. Else it's indented to two
2068columns beyond the leftmost solid chunk of non-whitespace characters on
2069the base line.
2070
2071Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2072repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2073structure you intend.
2074%c:indent-for-tab-command
2075%c:py-newline-and-indent
2076%c:py-delete-char
2077
2078
2079The next function may be handy when editing code you didn't write:
2080%c:py-guess-indent-offset
2081
2082
2083The remaining `indent' functions apply to a region of Python code. They
2084assume the block structure (equals indentation, in Python) of the region
2085is correct, and alter the indentation in various ways while preserving
2086the block structure:
2087%c:py-indent-region
2088%c:py-shift-region-left
2089%c:py-shift-region-right
2090
2091@MARKING & MANIPULATING REGIONS OF CODE
2092
2093\\[py-mark-block]\t mark block of lines
2094\\[mark-python-def-or-class]\t mark smallest enclosing def
2095\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002096\\[comment-region]\t comment out region of code
2097\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098%c:py-mark-block
2099%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002100%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002101
2102@MOVING POINT
2103
2104\\[py-previous-statement]\t move to statement preceding point
2105\\[py-next-statement]\t move to statement following point
2106\\[py-goto-block-up]\t move up to start of current block
2107\\[beginning-of-python-def-or-class]\t move to start of def
2108\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2109\\[end-of-python-def-or-class]\t move to end of def
2110\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2111
2112The first two move to one statement beyond the statement that contains
2113point. A numeric prefix argument tells them to move that many
2114statements instead. Blank lines, comment lines, and continuation lines
2115do not count as `statements' for these commands. So, e.g., you can go
2116to the first code statement in a file by entering
2117\t\\[beginning-of-buffer]\t to move to the top of the file
2118\t\\[py-next-statement]\t to skip over initial comments and blank lines
2119Or do `\\[py-previous-statement]' with a huge prefix argument.
2120%c:py-previous-statement
2121%c:py-next-statement
2122%c:py-goto-block-up
2123%c:beginning-of-python-def-or-class
2124%c:end-of-python-def-or-class
2125
2126@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2127
2128`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2129
2130`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2131overall class and def structure of a module.
2132
2133`\\[back-to-indentation]' moves point to a line's first non-blank character.
2134
2135`\\[indent-relative]' is handy for creating odd indentation.
2136
2137@OTHER EMACS HINTS
2138
2139If you don't like the default value of a variable, change its value to
2140whatever you do like by putting a `setq' line in your .emacs file.
2141E.g., to set the indentation increment to 4, put this line in your
2142.emacs:
2143\t(setq py-indent-offset 4)
2144To see the value of a variable, do `\\[describe-variable]' and enter the variable
2145name at the prompt.
2146
2147When entering a key sequence like `C-c C-n', it is not necessary to
2148release the CONTROL key after doing the `C-c' part -- it suffices to
2149press the CONTROL key, press and release `c' (while still holding down
2150CONTROL), press and release `n' (while still holding down CONTROL), &
2151then release CONTROL.
2152
2153Entering Python mode calls with no arguments the value of the variable
2154`python-mode-hook', if that value exists and is not nil; for backward
2155compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2156the Elisp manual for details.
2157
2158Obscure: When python-mode is first loaded, it looks for all bindings
2159to newline-and-indent in the global keymap, and shadows them with
2160local bindings to py-newline-and-indent."))
2161
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002162
2163;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002164(defvar py-parse-state-re
2165 (concat
2166 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2167 "\\|"
2168 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002169
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170;; returns the parse state at point (see parse-partial-sexp docs)
2171(defun py-parse-state ()
2172 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002173 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002174 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002175 (while (not done)
2176 ;; back up to the first preceding line (if any; else start of
2177 ;; buffer) that begins with a popular Python keyword, or a
2178 ;; non- whitespace and non-comment character. These are good
2179 ;; places to start parsing to see whether where we started is
2180 ;; at a non-zero nesting level. It may be slow for people who
2181 ;; write huge code blocks or huge lists ... tough beans.
2182 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002183 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002184 (beginning-of-line)
2185 (save-excursion
2186 (setq pps (parse-partial-sexp (point) here)))
2187 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002188 (setq done (or (zerop ci)
2189 (not (nth 3 pps))
2190 (bobp)))
2191 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002192 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002193
2194;; if point is at a non-zero nesting level, returns the number of the
2195;; character that opens the smallest enclosing unclosed list; else
2196;; returns nil.
2197(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002198 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002199 (if (zerop (car status))
2200 nil ; not in a nest
2201 (car (cdr status))))) ; char# of open bracket
2202
2203;; t iff preceding line ends with backslash that's not in a comment
2204(defun py-backslash-continuation-line-p ()
2205 (save-excursion
2206 (beginning-of-line)
2207 (and
2208 ;; use a cheap test first to avoid the regexp if possible
2209 ;; use 'eq' because char-after may return nil
2210 (eq (char-after (- (point) 2)) ?\\ )
2211 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002213 (looking-at py-continued-re))))
2214
2215;; t iff current line is a continuation line
2216(defun py-continuation-line-p ()
2217 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002218 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002219 (or (py-backslash-continuation-line-p)
2220 (py-nesting-level))))
2221
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002222;; go to initial line of current statement; usually this is the line
2223;; we're on, but if we're on the 2nd or following lines of a
2224;; continuation block, we need to go up to the first line of the
2225;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002227;; Tricky: We want to avoid quadratic-time behavior for long continued
2228;; blocks, whether of the backslash or open-bracket varieties, or a
2229;; mix of the two. The following manages to do that in the usual
2230;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002231(defun py-goto-initial-line ()
2232 (let ( open-bracket-pos )
2233 (while (py-continuation-line-p)
2234 (beginning-of-line)
2235 (if (py-backslash-continuation-line-p)
2236 (while (py-backslash-continuation-line-p)
2237 (forward-line -1))
2238 ;; else zip out of nested brackets/braces/parens
2239 (while (setq open-bracket-pos (py-nesting-level))
2240 (goto-char open-bracket-pos)))))
2241 (beginning-of-line))
2242
2243;; go to point right beyond final line of current statement; usually
2244;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002245;; statement we need to skip over the continuation lines. Tricky:
2246;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002247(defun py-goto-beyond-final-line ()
2248 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002249 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002250 (while (and (py-continuation-line-p)
2251 (not (eobp)))
2252 ;; skip over the backslash flavor
2253 (while (and (py-backslash-continuation-line-p)
2254 (not (eobp)))
2255 (forward-line 1))
2256 ;; if in nest, zip to the end of the nest
2257 (setq state (py-parse-state))
2258 (if (and (not (zerop (car state)))
2259 (not (eobp)))
2260 (progn
Barry Warsawf7705781997-01-30 19:49:39 +00002261 (parse-partial-sexp (point) (point-max)
2262 (if py-parse-partial-sexp-works-p
2263 0 (- 0 (car state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002264 nil state)
2265 (forward-line 1))))))
2266
2267;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002268;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002269(defun py-statement-opens-block-p ()
2270 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002271 (let ((start (point))
2272 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2273 (searching t)
2274 (answer nil)
2275 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002276 (goto-char start)
2277 (while searching
2278 ;; look for a colon with nothing after it except whitespace, and
2279 ;; maybe a comment
2280 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2281 finish t)
2282 (if (eq (point) finish) ; note: no `else' clause; just
2283 ; keep searching if we're not at
2284 ; the end yet
2285 ;; sure looks like it opens a block -- but it might
2286 ;; be in a comment
2287 (progn
2288 (setq searching nil) ; search is done either way
2289 (setq state (parse-partial-sexp start
2290 (match-beginning 0)))
2291 (setq answer (not (nth 4 state)))))
2292 ;; search failed: couldn't find another interesting colon
2293 (setq searching nil)))
2294 answer)))
2295
Barry Warsawf831d811996-07-31 20:42:59 +00002296(defun py-statement-closes-block-p ()
2297 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002298 ;; starts with `return', `raise', `break', `continue', and `pass'.
2299 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002300 (let ((here (point)))
2301 (back-to-indentation)
2302 (prog1
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002303 (looking-at "\\(return\\|raise\\|break\\|continue\\|pass\\)\\>")
Barry Warsawf831d811996-07-31 20:42:59 +00002304 (goto-char here))))
2305
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306;; go to point right beyond final line of block begun by the current
2307;; line. This is the same as where py-goto-beyond-final-line goes
2308;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002309;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002310(defun py-goto-beyond-block ()
2311 (if (py-statement-opens-block-p)
2312 (py-mark-block nil 'just-move)
2313 (py-goto-beyond-final-line)))
2314
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002315;; go to start of first statement (not blank or comment or
2316;; continuation line) at or preceding point. returns t if there is
2317;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002318(defun py-goto-statement-at-or-above ()
2319 (py-goto-initial-line)
2320 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002321 ;; skip back over blank & comment lines
2322 ;; note: will skip a blank or comment line that happens to be
2323 ;; a continuation line too
2324 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2325 (progn (py-goto-initial-line) t)
2326 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002327 t))
2328
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002329;; go to start of first statement (not blank or comment or
2330;; continuation line) following the statement containing point returns
2331;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002332(defun py-goto-statement-below ()
2333 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002334 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002335 (py-goto-beyond-final-line)
2336 (while (and
2337 (looking-at py-blank-or-comment-re)
2338 (not (eobp)))
2339 (forward-line 1))
2340 (if (eobp)
2341 (progn (goto-char start) nil)
2342 t)))
2343
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002344;; go to start of statement, at or preceding point, starting with
2345;; keyword KEY. Skips blank lines and non-indenting comments upward
2346;; first. If that statement starts with KEY, done, else go back to
2347;; first enclosing block starting with KEY. If successful, leaves
2348;; point at the start of the KEY line & returns t. Else leaves point
2349;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002350(defun py-go-up-tree-to-keyword (key)
2351 ;; skip blanks and non-indenting #
2352 (py-goto-initial-line)
2353 (while (and
2354 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2355 (zerop (forward-line -1))) ; go back
2356 nil)
2357 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002358 (let* ((re (concat "[ \t]*" key "\\b"))
2359 (case-fold-search nil) ; let* so looking-at sees this
2360 (found (looking-at re))
2361 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002362 (while (not (or found dead))
2363 (condition-case nil ; in case no enclosing block
2364 (py-goto-block-up 'no-mark)
2365 (error (setq dead t)))
2366 (or dead (setq found (looking-at re))))
2367 (beginning-of-line)
2368 found))
2369
2370;; return string in buffer from start of indentation to end of line;
2371;; prefix "..." if leading whitespace was skipped
2372(defun py-suck-up-leading-text ()
2373 (save-excursion
2374 (back-to-indentation)
2375 (concat
2376 (if (bolp) "" "...")
2377 (buffer-substring (point) (progn (end-of-line) (point))))))
2378
2379;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2380;; as a Lisp symbol; return nil if none
2381(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002382 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002383 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2384 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2385 nil)))
2386
2387(defun py-make-temp-name ()
2388 (make-temp-name
2389 (concat (file-name-as-directory py-temp-directory) "python")))
2390
2391(defun py-delete-file-silently (fname)
2392 (condition-case nil
2393 (delete-file fname)
2394 (error nil)))
2395
2396(defun py-kill-emacs-hook ()
2397 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002398 (py-safe (while py-file-queue
2399 (py-delete-file-silently (car py-file-queue))
2400 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002401
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002402;; make PROCESS's buffer visible, append STRING to it, and force
2403;; display; also make shell-mode believe the user typed this string,
2404;; so that kill-output-from-shell and show-output-from-shell work
2405;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002406(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002407 (let ((cbuf (current-buffer))
2408 (pbuf (process-buffer process))
2409 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002410 (set-buffer pbuf)
2411 (goto-char (point-max))
2412 (move-marker (process-mark process) (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002413 (funcall (process-filter process) process string)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002414 (set-buffer cbuf))
2415 (sit-for 0))
2416
Barry Warsaw3622e0d1996-10-29 15:32:57 +00002417;; older Emacsen don't have this function
2418(if (not (fboundp 'match-string))
2419 (defun match-string (n)
2420 (let ((beg (match-beginning n))
2421 (end (match-end n)))
2422 (if (and beg end)
2423 (buffer-substring beg end)
2424 nil))))
2425
Barry Warsawb3e81d51996-09-04 15:12:42 +00002426(defun py-current-defun ()
2427 ;; tell add-log.el how to find the current function/method/variable
2428 (save-excursion
2429 (if (re-search-backward py-defun-start-re nil t)
2430 (or (match-string 3)
2431 (let ((method (match-string 2)))
2432 (if (and (not (zerop (length (match-string 1))))
2433 (re-search-backward py-class-start-re nil t))
2434 (concat (match-string 1) "." method)
2435 method)))
2436 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002437
2438
Barry Warsawfec75d61995-07-05 23:26:15 +00002439(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002440 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002441
Barry Warsaw850437a1995-03-08 21:50:28 +00002442(defun py-version ()
2443 "Echo the current version of `python-mode' in the minibuffer."
2444 (interactive)
2445 (message "Using `python-mode' version %s" py-version)
2446 (py-keep-region-active))
2447
2448;; only works under Emacs 19
2449;(eval-when-compile
2450; (require 'reporter))
2451
2452(defun py-submit-bug-report (enhancement-p)
2453 "Submit via mail a bug report on `python-mode'.
2454With \\[universal-argument] just submit an enhancement request."
2455 (interactive
2456 (list (not (y-or-n-p
2457 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002458 (let ((reporter-prompt-for-summary-p (if enhancement-p
2459 "(Very) brief summary: "
2460 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002461 (require 'reporter)
2462 (reporter-submit-bug-report
2463 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002464 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002465 ;; varlist
2466 (if enhancement-p nil
2467 '(py-python-command
2468 py-indent-offset
2469 py-block-comment-prefix
2470 py-scroll-process-buffer
2471 py-temp-directory
2472 py-beep-if-tab-change))
2473 nil ;pre-hooks
2474 nil ;post-hooks
2475 "Dear Barry,") ;salutation
2476 (if enhancement-p nil
2477 (set-mark (point))
2478 (insert
2479"Please replace this text with a sufficiently large code sample\n\
2480and an exact recipe so that I can reproduce your problem. Failure\n\
2481to do so may mean a greater delay in fixing your bug.\n\n")
2482 (exchange-point-and-mark)
2483 (py-keep-region-active))))
2484
2485
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002486;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002487(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002488
2489
2490
2491(provide 'python-mode)
2492;;; python-mode.el ends here