blob: f5b804a75a662f2604273b4005047fa2c0f3d7aa [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
Barry Warsawc12c62e1997-09-04 04:18:07 +0000244(defconst py-emacs-features ()
245 "A list of features extant in the Emacs you are using.
246There are many flavors of Emacs out there, each with different
247features supporting those needed by CC Mode. Here's the current
248supported list, along with the values for this variable:
249
250 XEmacs 19: ()
251 XEmacs 20: ()
252 Emacs 19: ()
253")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000254
Barry Warsawfb07f401997-02-24 03:37:22 +0000255(defvar python-font-lock-keywords
Barry Warsaw2e049b21996-09-04 15:21:55 +0000256 (let* ((keywords '("and" "break" "class"
Barry Warsaw44b72201996-07-05 20:11:35 +0000257 "continue" "def" "del" "elif"
258 "else:" "except" "except:" "exec"
259 "finally:" "for" "from" "global"
260 "if" "import" "in" "is"
261 "lambda" "not" "or" "pass"
262 "print" "raise" "return" "try:"
263 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000264 ))
265 (kwregex (mapconcat 'identity keywords "\\|")))
266 (list
267 ;; keywords not at beginning of line
268 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
269 ;; keywords at beginning of line. i don't think regexps are
270 ;; powerful enough to handle these two cases in one regexp.
271 ;; prove me wrong!
272 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
273 ;; classes
274 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
275 1 font-lock-type-face)
276 ;; functions
277 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
278 1 font-lock-function-name-face)
279 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000280 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000281(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
282
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000283
Barry Warsaw81437461996-08-01 19:48:02 +0000284(defvar imenu-example--python-show-method-args-p nil
285 "*Controls echoing of arguments of functions & methods in the imenu buffer.
286When non-nil, arguments are printed.")
287
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000288(make-variable-buffer-local 'py-indent-offset)
289
Barry Warsaw7ae77681994-12-12 20:38:05 +0000290;; have to bind py-file-queue before installing the kill-emacs hook
291(defvar py-file-queue nil
292 "Queue of Python temp files awaiting execution.
293Currently-active file is at the head of the list.")
294
Barry Warsawc72c11c1997-08-09 06:42:08 +0000295(defvar py-delete-function 'backward-delete-char-untabify
296 "*Function called by `py-delete-char' when deleting characters.")
297
298(defvar py-backspace-function 'backward-delete-char-untabify
299 "*Function called by `py-backspace-command' when deleting characters.")
300
301
302;; Constants
303
304;; Regexp matching a Python string literal
305(defconst py-stringlit-re
306 (concat
307 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
308 "\\|" ; or
309 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
310
311;; Regexp matching Python lines that are continued via backslash.
312;; This is tricky because a trailing backslash does not mean
313;; continuation if it's in a comment
314(defconst py-continued-re
315 (concat
316 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
317 "\\\\$"))
318
319;; Regexp matching blank or comment lines.
320(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
321
322;; Regexp matching clauses to be outdented one level.
323(defconst py-outdent-re
324 (concat "\\(" (mapconcat 'identity
325 '("else:"
326 "except\\(\\s +.*\\)?:"
327 "finally:"
328 "elif\\s +.*:")
329 "\\|")
330 "\\)"))
331
332
333;; Regexp matching lines to not outdent after.
334(defconst py-no-outdent-re
335 (concat "\\(" (mapconcat 'identity
336 '("try:"
337 "except\\(\\s +.*\\)?:"
338 "while\\s +.*:"
339 "for\\s +.*:"
340 "if\\s +.*:"
341 "elif\\s +.*:"
342 "\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
343 )
344 "\\|")
345 "\\)"))
346
347;; Regexp matching a function, method or variable assignment. If you
348;; change this, you probably have to change `py-current-defun' as
349;; well. This is only used by `py-current-defun' to find the name for
350;; add-log.el.
351(defvar py-defun-start-re
352 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
353
354;; Regexp for finding a class name. If you change this, you probably
355;; have to change `py-current-defun' as well. This is only used by
356;; `py-current-defun' to find the name for add-log.el.
357(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
358
359
360
361;; Utilities
362
363(defmacro py-safe (&rest body)
364 ;; safely execute BODY, return nil if an error occurred
365 (` (condition-case nil
366 (progn (,@ body))
367 (error nil))))
368
369(defsubst py-keep-region-active ()
370 ;; Do whatever is necessary to keep the region active in XEmacs.
371 ;; Ignore byte-compiler warnings you might see. Also note that
372 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
373 ;; to take explicit action.
374 (and (boundp 'zmacs-region-stays)
375 (setq zmacs-region-stays t)))
376
377
378;; Major mode boilerplate
379
Barry Warsaw7ae77681994-12-12 20:38:05 +0000380;; define a mode-specific abbrev table for those who use such things
381(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000382 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000383(define-abbrev-table 'python-mode-abbrev-table nil)
384
Barry Warsaw7ae77681994-12-12 20:38:05 +0000385(defvar python-mode-hook nil
386 "*Hook called by `python-mode'.")
387
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000388;; in previous version of python-mode.el, the hook was incorrectly
389;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000390(and (fboundp 'make-obsolete-variable)
391 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
392
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000393(defvar py-mode-map ()
394 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000395(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000396 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000397 (setq py-mode-map (make-sparse-keymap))
398
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399 ;; shadow global bindings for newline-and-indent w/ the py- version.
400 ;; BAW - this is extremely bad form, but I'm not going to change it
401 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000402 (mapcar (function (lambda (key)
403 (define-key
404 py-mode-map key 'py-newline-and-indent)))
405 (where-is-internal 'newline-and-indent))
406
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000407 ;; BAW - you could do it this way, but its not considered proper
408 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000409 (mapcar (function
410 (lambda (x)
411 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000412 '((":" . py-electric-colon)
413 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 ("\C-c|" . py-execute-region)
415 ("\C-c!" . py-shell)
416 ("\177" . py-delete-char)
417 ("\n" . py-newline-and-indent)
418 ("\C-c:" . py-guess-indent-offset)
419 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000420 ("\C-c\C-l" . py-shift-region-left)
421 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000422 ("\C-c<" . py-shift-region-left)
423 ("\C-c>" . py-shift-region-right)
424 ("\C-c\C-n" . py-next-statement)
425 ("\C-c\C-p" . py-previous-statement)
426 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000427 ("\C-c\C-m" . py-mark-block)
Barry Warsawa7891711996-08-01 15:53:09 +0000428 ("\C-c#" . py-comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000429 ("\C-c?" . py-describe-mode)
430 ("\C-c\C-hm" . py-describe-mode)
431 ("\e\C-a" . beginning-of-python-def-or-class)
432 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000433 ( "\e\C-h" . mark-python-def-or-class)))
434 ;; should do all keybindings this way
435 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
436 (define-key py-mode-map "\C-c\C-v" 'py-version)
437 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000438
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000439(defvar py-mode-syntax-table nil
440 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000441(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000442 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000443 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000444 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
445 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
446 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
447 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
448 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
449 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
450 ;; Add operator symbols misassigned in the std table
451 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
452 (modify-syntax-entry ?\% "." py-mode-syntax-table)
453 (modify-syntax-entry ?\& "." py-mode-syntax-table)
454 (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 (modify-syntax-entry ?\> "." py-mode-syntax-table)
461 (modify-syntax-entry ?\| "." py-mode-syntax-table)
462 ;; For historical reasons, underscore is word class instead of
463 ;; symbol class. GNU conventions say it should be symbol class, but
464 ;; there's a natural conflict between what major mode authors want
465 ;; and what users expect from `forward-word' and `backward-word'.
466 ;; Guido and I have hashed this out and have decided to keep
467 ;; underscore in word class. If you're tempted to change it, try
468 ;; binding M-f and M-b to py-forward-into-nomenclature and
469 ;; py-backward-into-nomenclature instead.
470 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
471 ;; Both single quote and double quote are string delimiters
472 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
473 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
474 ;; backquote is open and close paren
475 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
476 ;; comment delimiters
477 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
478 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
479 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000480
Barry Warsawb3e81d51996-09-04 15:12:42 +0000481
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000482
Barry Warsaw42f707f1996-07-29 21:05:05 +0000483;; Menu definitions, only relevent if you have the easymenu.el package
484;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000485(defvar py-menu nil
486 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000487This menu will get created automatically if you have the `easymenu'
488package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000489
Barry Warsawc72c11c1997-08-09 06:42:08 +0000490(and (py-safe (require 'easymenu) t)
491 (easy-menu-define
492 py-menu py-mode-map "Python Mode menu"
493 '("Python"
494 ["Comment Out Region" py-comment-region (mark)]
495 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
496 "-"
497 ["Mark current block" py-mark-block t]
498 ["Mark current def" mark-python-def-or-class t]
499 ["Mark current class" (mark-python-def-or-class t) t]
500 "-"
501 ["Shift region left" py-shift-region-left (mark)]
502 ["Shift region right" py-shift-region-right (mark)]
503 "-"
504 ["Execute buffer" py-execute-buffer t]
505 ["Execute region" py-execute-region (mark)]
506 ["Start interpreter..." py-shell t]
507 "-"
508 ["Go to start of block" py-goto-block-up t]
509 ["Go to start of class" (beginning-of-python-def-or-class t) t]
510 ["Move to end of class" (end-of-python-def-or-class t) t]
511 ["Move to start of def" beginning-of-python-def-or-class t]
512 ["Move to end of def" end-of-python-def-or-class t]
513 "-"
514 ["Describe mode" py-describe-mode t]
515 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000516
Barry Warsaw81437461996-08-01 19:48:02 +0000517
518
519;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
520(defvar imenu-example--python-class-regexp
521 (concat ; <<classes>>
522 "\\(" ;
523 "^[ \t]*" ; newline and maybe whitespace
524 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
525 ; possibly multiple superclasses
526 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
527 "[ \t]*:" ; and the final :
528 "\\)" ; >>classes<<
529 )
530 "Regexp for Python classes for use with the imenu package."
531 )
532
533(defvar imenu-example--python-method-regexp
534 (concat ; <<methods and functions>>
535 "\\(" ;
536 "^[ \t]*" ; new line and maybe whitespace
537 "\\(def[ \t]+" ; function definitions start with def
538 "\\([a-zA-Z0-9_]+\\)" ; name is here
539 ; function arguments...
540 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
541 "\\)" ; end of def
542 "[ \t]*:" ; and then the :
543 "\\)" ; >>methods and functions<<
544 )
545 "Regexp for Python methods/functions for use with the imenu package."
546 )
547
548(defvar imenu-example--python-method-no-arg-parens '(2 8)
549 "Indicies into groups of the Python regexp for use with imenu.
550
551Using these values will result in smaller imenu lists, as arguments to
552functions are not listed.
553
554See the variable `imenu-example--python-show-method-args-p' for more
555information.")
556
557(defvar imenu-example--python-method-arg-parens '(2 7)
558 "Indicies into groups of the Python regexp for use with imenu.
559Using these values will result in large imenu lists, as arguments to
560functions are listed.
561
562See the variable `imenu-example--python-show-method-args-p' for more
563information.")
564
565;; Note that in this format, this variable can still be used with the
566;; imenu--generic-function. Otherwise, there is no real reason to have
567;; it.
568(defvar imenu-example--generic-python-expression
569 (cons
570 (concat
571 imenu-example--python-class-regexp
572 "\\|" ; or...
573 imenu-example--python-method-regexp
574 )
575 imenu-example--python-method-no-arg-parens)
576 "Generic Python expression which may be used directly with imenu.
577Used by setting the variable `imenu-generic-expression' to this value.
578Also, see the function \\[imenu-example--create-python-index] for a
579better alternative for finding the index.")
580
581;; These next two variables are used when searching for the python
582;; class/definitions. Just saving some time in accessing the
583;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000584(defvar imenu-example--python-generic-regexp nil)
585(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000586
587
588;;;###autoload
589(eval-when-compile
590 ;; Imenu isn't used in XEmacs, so just ignore load errors
591 (condition-case ()
592 (progn
593 (require 'cl)
594 (require 'imenu))
595 (error nil)))
596
597(defun imenu-example--create-python-index ()
598 "Python interface function for imenu package.
599Finds all python classes and functions/methods. Calls function
600\\[imenu-example--create-python-index-engine]. See that function for
601the details of how this works."
602 (setq imenu-example--python-generic-regexp
603 (car imenu-example--generic-python-expression))
604 (setq imenu-example--python-generic-parens
605 (if imenu-example--python-show-method-args-p
606 imenu-example--python-method-arg-parens
607 imenu-example--python-method-no-arg-parens))
608 (goto-char (point-min))
609 (imenu-example--create-python-index-engine nil))
610
611(defun imenu-example--create-python-index-engine (&optional start-indent)
612 "Function for finding imenu definitions in Python.
613
614Finds all definitions (classes, methods, or functions) in a Python
615file for the imenu package.
616
617Returns a possibly nested alist of the form
618
619 (INDEX-NAME . INDEX-POSITION)
620
621The second element of the alist may be an alist, producing a nested
622list as in
623
624 (INDEX-NAME . INDEX-ALIST)
625
626This function should not be called directly, as it calls itself
627recursively and requires some setup. Rather this is the engine for
628the function \\[imenu-example--create-python-index].
629
630It works recursively by looking for all definitions at the current
631indention level. When it finds one, it adds it to the alist. If it
632finds a definition at a greater indentation level, it removes the
633previous definition from the alist. In it's place it adds all
634definitions found at the next indentation level. When it finds a
635definition that is less indented then the current level, it retuns the
636alist it has created thus far.
637
638The optional argument START-INDENT indicates the starting indentation
639at which to continue looking for Python classes, methods, or
640functions. If this is not supplied, the function uses the indentation
641of the first definition found."
642 (let ((index-alist '())
643 (sub-method-alist '())
644 looking-p
645 def-name prev-name
646 cur-indent def-pos
647 (class-paren (first imenu-example--python-generic-parens))
648 (def-paren (second imenu-example--python-generic-parens)))
649 (setq looking-p
650 (re-search-forward imenu-example--python-generic-regexp
651 (point-max) t))
652 (while looking-p
653 (save-excursion
654 ;; used to set def-name to this value but generic-extract-name is
655 ;; new to imenu-1.14. this way it still works with imenu-1.11
656 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
657 (let ((cur-paren (if (match-beginning class-paren)
658 class-paren def-paren)))
659 (setq def-name
660 (buffer-substring (match-beginning cur-paren)
661 (match-end cur-paren))))
662 (beginning-of-line)
663 (setq cur-indent (current-indentation)))
664
665 ;; HACK: want to go to the next correct definition location. we
666 ;; explicitly list them here. would be better to have them in a
667 ;; list.
668 (setq def-pos
669 (or (match-beginning class-paren)
670 (match-beginning def-paren)))
671
672 ;; if we don't have a starting indent level, take this one
673 (or start-indent
674 (setq start-indent cur-indent))
675
676 ;; if we don't have class name yet, take this one
677 (or prev-name
678 (setq prev-name def-name))
679
680 ;; what level is the next definition on? must be same, deeper
681 ;; or shallower indentation
682 (cond
683 ;; at the same indent level, add it to the list...
684 ((= start-indent cur-indent)
685
686 ;; if we don't have push, use the following...
687 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
688 (push (cons def-name def-pos) index-alist))
689
690 ;; deeper indented expression, recur...
691 ((< start-indent cur-indent)
692
693 ;; the point is currently on the expression we're supposed to
694 ;; start on, so go back to the last expression. The recursive
695 ;; call will find this place again and add it to the correct
696 ;; list
697 (re-search-backward imenu-example--python-generic-regexp
698 (point-min) 'move)
699 (setq sub-method-alist (imenu-example--create-python-index-engine
700 cur-indent))
701
702 (if sub-method-alist
703 ;; we put the last element on the index-alist on the start
704 ;; of the submethod alist so the user can still get to it.
705 (let ((save-elmt (pop index-alist)))
706 (push (cons (imenu-create-submenu-name prev-name)
707 (cons save-elmt sub-method-alist))
708 index-alist))))
709
710 ;; found less indented expression, we're done.
711 (t
712 (setq looking-p nil)
713 (re-search-backward imenu-example--python-generic-regexp
714 (point-min) t)))
715 (setq prev-name def-name)
716 (and looking-p
717 (setq looking-p
718 (re-search-forward imenu-example--python-generic-regexp
719 (point-max) 'move))))
720 (nreverse index-alist)))
721
Barry Warsaw42f707f1996-07-29 21:05:05 +0000722
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000723;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000724(defun python-mode ()
725 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000726To submit a problem report, enter `\\[py-submit-bug-report]' from a
727`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
728documentation. To see what version of `python-mode' you are running,
729enter `\\[py-version]'.
730
731This mode knows about Python indentation, tokens, comments and
732continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000733
734COMMANDS
735\\{py-mode-map}
736VARIABLES
737
Barry Warsaw42f707f1996-07-29 21:05:05 +0000738py-indent-offset\t\tindentation increment
739py-block-comment-prefix\t\tcomment string used by comment-region
740py-python-command\t\tshell command to invoke Python interpreter
741py-scroll-process-buffer\t\talways scroll Python process buffer
742py-temp-directory\t\tdirectory used for temp files (if needed)
743py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000745 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000746 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000747 (make-local-variable 'font-lock-defaults)
748 (make-local-variable 'paragraph-separate)
749 (make-local-variable 'paragraph-start)
750 (make-local-variable 'require-final-newline)
751 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000752 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000753 (make-local-variable 'comment-start-skip)
754 (make-local-variable 'comment-column)
755 (make-local-variable 'indent-region-function)
756 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000757 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000758 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000759 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000760 (setq major-mode 'python-mode
761 mode-name "Python"
762 local-abbrev-table python-mode-abbrev-table
Barry Warsaw615d4a41996-09-04 14:14:10 +0000763 paragraph-separate "^[ \t]*$"
764 paragraph-start "^[ \t]*$"
765 require-final-newline t
766 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000767 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000768 comment-start-skip "# *"
769 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000770 indent-region-function 'py-indent-region
771 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000772 ;; tell add-log.el how to find the current function/method/variable
773 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000774 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000775 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000776 ;; add the menu
777 (if py-menu
778 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000779 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000780 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000781 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000782 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000783 ;;
784 ;; not sure where the magic comment has to be; to save time
785 ;; searching for a rarity, we give up if it's not found prior to the
786 ;; first executable statement.
787 ;;
788 ;; BAW - on first glance, this seems like complete hackery. Why was
789 ;; this necessary, and is it still necessary?
790 (let ((case-fold-search nil)
791 (start (point))
792 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000793 (if (re-search-forward
794 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
795 (prog2 (py-next-statement 1) (point) (goto-char 1))
796 t)
797 (progn
798 (setq new-tab-width
799 (string-to-int
800 (buffer-substring (match-beginning 1) (match-end 1))))
801 (if (= tab-width new-tab-width)
802 nil
803 (setq tab-width new-tab-width)
804 (message "Caution: tab-width changed to %d" new-tab-width)
805 (if py-beep-if-tab-change (beep)))))
806 (goto-char start))
807
Barry Warsaw755c6711996-08-01 20:02:55 +0000808 ;; install imenu
809 (setq imenu-create-index-function
810 (function imenu-example--create-python-index))
811 (if (fboundp 'imenu-add-to-menubar)
812 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
813
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000814 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000815 (if python-mode-hook
816 (run-hooks 'python-mode-hook)
817 (run-hooks 'py-mode-hook)))
818
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000819
Barry Warsawb91b7431995-03-14 15:55:20 +0000820;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000821(defun py-outdent-p ()
822 ;; returns non-nil if the current line should outdent one level
823 (save-excursion
824 (and (progn (back-to-indentation)
825 (looking-at py-outdent-re))
826 (progn (backward-to-indentation 1)
827 (while (or (looking-at py-blank-or-comment-re)
828 (bobp))
829 (backward-to-indentation 1))
830 (not (looking-at py-no-outdent-re)))
831 )))
832
Barry Warsawb91b7431995-03-14 15:55:20 +0000833(defun py-electric-colon (arg)
834 "Insert a colon.
835In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000836argument is provided, that many colons are inserted non-electrically.
837Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000838 (interactive "P")
839 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000840 ;; are we in a string or comment?
841 (if (save-excursion
842 (let ((pps (parse-partial-sexp (save-excursion
843 (beginning-of-python-def-or-class)
844 (point))
845 (point))))
846 (not (or (nth 3 pps) (nth 4 pps)))))
847 (save-excursion
848 (let ((here (point))
849 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000850 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000851 (if (and (not arg)
852 (py-outdent-p)
853 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000854 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000855 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000856 )
857 (setq outdent py-indent-offset))
858 ;; Don't indent, only outdent. This assumes that any lines that
859 ;; are already outdented relative to py-compute-indentation were
860 ;; put there on purpose. Its highly annoying to have `:' indent
861 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
862 ;; there a better way to determine this???
863 (if (< (current-indentation) indent) nil
864 (goto-char here)
865 (beginning-of-line)
866 (delete-horizontal-space)
867 (indent-to (- indent outdent))
868 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000869
870
Barry Warsaw7ae77681994-12-12 20:38:05 +0000871;;; Functions that execute Python commands in a subprocess
Barry Warsawc72ad871996-09-03 16:16:04 +0000872;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000873(defun py-shell ()
874 "Start an interactive Python interpreter in another window.
875This is like Shell mode, except that Python is running in the window
876instead of a shell. See the `Interactive Shell' and `Shell Mode'
877sections of the Emacs manual for details, especially for the key
878bindings active in the `*Python*' buffer.
879
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000880See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000881behavior in the process window.
882
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000883Warning: Don't use an interactive Python if you change sys.ps1 or
884sys.ps2 from their default values, or if you're running code that
885prints `>>> ' or `... ' at the start of a line. `python-mode' can't
886distinguish your output from Python's output, and assumes that `>>> '
887at the start of a line is a prompt from Python. Similarly, the Emacs
888Shell mode code assumes that both `>>> ' and `... ' at the start of a
889line are Python prompts. Bad things can happen if you fool either
890mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000891
892Warning: If you do any editing *in* the process buffer *while* the
893buffer is accepting output from Python, do NOT attempt to `undo' the
894changes. Some of the output (nowhere near the parts you changed!) may
895be lost if you do. This appears to be an Emacs bug, an unfortunate
896interaction between undo and process filters; the same problem exists in
897non-Python process buffers using the default (Emacs-supplied) process
898filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000899 ;; BAW - should undo be disabled in the python process buffer, if
900 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901 (interactive)
Barry Warsawe6648961997-07-10 15:58:36 +0000902 (require 'comint)
903 (switch-to-buffer-other-window (make-comint "Python" py-python-command))
904 (make-local-variable 'comint-prompt-regexp)
905 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
906 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
907 (set-syntax-table py-mode-syntax-table)
908 (local-set-key [tab] 'self-insert-command))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909
910(defun py-execute-region (start end)
911 "Send the region between START and END to a Python interpreter.
912If there is a *Python* process it is used.
913
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000914Hint: If you want to execute part of a Python file several times
915\(e.g., perhaps you're developing a function and want to flesh it out
916a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
917the region of interest, and send the code to a *Python* process via
918`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000919
920Following are subtleties to note when using a *Python* process:
921
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000922If a *Python* process is used, the region is copied into a temporary
923file (in directory `py-temp-directory'), and an `execfile' command is
924sent to Python naming that file. If you send regions faster than
925Python can execute them, `python-mode' will save them into distinct
926temp files, and execute the next one in the queue the next time it
927sees a `>>> ' prompt from Python. Each time this happens, the process
928buffer is popped into a window (if it's not already in some window) so
929you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000930
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000931 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000932
933is inserted at the end.
934
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000935Caution: No more than 26 regions can be pending at any given time.
936This limit is (indirectly) inherited from libc's mktemp(3).
937`python-mode' does not try to protect you from exceeding the limit.
938It's extremely unlikely that you'll get anywhere close to the limit in
939practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940
941See the `\\[py-shell]' docs for additional warnings."
942 (interactive "r")
943 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000944 (let ((pyproc (get-process "Python"))
945 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000946 (if (null pyproc)
947 (shell-command-on-region start end py-python-command)
948 ;; else feed it thru a temp file
949 (setq fname (py-make-temp-name))
950 (write-region start end fname nil 'no-msg)
951 (setq py-file-queue (append py-file-queue (list fname)))
952 (if (cdr py-file-queue)
953 (message "File %s queued for execution" fname)
954 ;; else
955 (py-execute-file pyproc fname)))))
956
957(defun py-execute-file (pyproc fname)
958 (py-append-to-process-buffer
959 pyproc
960 (format "## working on region in file %s ...\n" fname))
961 (process-send-string pyproc (format "execfile('%s')\n" fname)))
962
963(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000964 (let ((curbuf (current-buffer))
965 (pbuf (process-buffer pyproc))
966 (pmark (process-mark pyproc))
967 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000968
969 ;; make sure we switch to a different buffer at least once. if we
970 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000971 ;; window, and point is before the end, and lots of output is
972 ;; coming at a fast pace, then (a) simple cursor-movement commands
973 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
974 ;; to have a visible effect (the window just doesn't get updated,
975 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
976 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000978 ;; #b makes no sense to me at all. #a almost makes sense: unless
979 ;; we actually change buffers, set_buffer_internal in buffer.c
980 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
981 ;; seems to make the Emacs command loop reluctant to update the
982 ;; display. Perhaps the default process filter in process.c's
983 ;; read_process_output has update_mode_lines++ for a similar
984 ;; reason? beats me ...
985
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000986 (unwind-protect
987 ;; make sure current buffer is restored
988 ;; BAW - we want to check to see if this still applies
989 (progn
990 ;; mysterious ugly hack
991 (if (eq curbuf pbuf)
992 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000993
Barry Warsaw7a73ef81996-09-30 23:00:40 +0000994 (set-buffer pbuf)
995 (let* ((start (point))
996 (goback (< start pmark))
997 (goend (and (not goback) (= start (point-max))))
998 (buffer-read-only nil))
999 (goto-char pmark)
1000 (insert string)
1001 (move-marker pmark (point))
1002 (setq file-finished
1003 (and py-file-queue
1004 (equal ">>> "
1005 (buffer-substring
1006 (prog2 (beginning-of-line) (point)
1007 (goto-char pmark))
1008 (point)))))
1009 (if goback (goto-char start)
1010 ;; else
1011 (if py-scroll-process-buffer
1012 (let* ((pop-up-windows t)
1013 (pwin (display-buffer pbuf)))
1014 (set-window-point pwin (point)))))
1015 (set-buffer curbuf)
1016 (if file-finished
1017 (progn
1018 (py-delete-file-silently (car py-file-queue))
1019 (setq py-file-queue (cdr py-file-queue))
1020 (if py-file-queue
1021 (py-execute-file pyproc (car py-file-queue)))))
1022 (and goend
1023 (progn (set-buffer pbuf)
1024 (goto-char (point-max))))
1025 ))
1026 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027
1028(defun py-execute-buffer ()
1029 "Send the contents of the buffer to a Python interpreter.
1030If there is a *Python* process buffer it is used. If a clipping
1031restriction is in effect, only the accessible portion of the buffer is
1032sent. A trailing newline will be supplied if needed.
1033
1034See the `\\[py-execute-region]' docs for an account of some subtleties."
1035 (interactive)
1036 (py-execute-region (point-min) (point-max)))
1037
1038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001039
1040;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +00001041(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001042 "Reduce indentation or delete character.
Barry Warsawb0539931996-12-17 22:05:07 +00001043
Barry Warsaw7ae77681994-12-12 20:38:05 +00001044If point is at the leftmost column, deletes the preceding newline.
Barry Warsawb0539931996-12-17 22:05:07 +00001045Deletion is performed by calling the function in `py-delete-function'
1046with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001047
1048Else if point is at the leftmost non-blank character of a line that is
1049neither a continuation line nor a non-indenting comment line, or if
1050point is at the end of a blank line, reduces the indentation to match
1051that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001052opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +00001053of where you are. With numeric count, outdents that many blocks (but
1054not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001055
1056Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +00001057needed so that only a single column position is deleted. Numeric
1058argument delets that many characters."
1059 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001060 (if (or (/= (current-indentation) (current-column))
1061 (bolp)
1062 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001063 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001064 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsawb0539931996-12-17 22:05:07 +00001065 (funcall py-delete-function count)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001066 ;; else indent the same as the colon line that opened the block
1067
1068 ;; force non-blank so py-goto-block-up doesn't ignore it
1069 (insert-char ?* 1)
1070 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001071 (let ((base-indent 0) ; indentation of base line
1072 (base-text "") ; and text of base line
1073 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001074 (save-excursion
1075 (while (< 0 count)
1076 (condition-case nil ; in case no enclosing block
1077 (progn
1078 (py-goto-block-up 'no-mark)
1079 (setq base-indent (current-indentation)
1080 base-text (py-suck-up-leading-text)
1081 base-found-p t))
1082 (error nil))
1083 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 (delete-char 1) ; toss the dummy character
1085 (delete-horizontal-space)
1086 (indent-to base-indent)
1087 (if base-found-p
1088 (message "Closes block: %s" base-text)))))
1089
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001090;; required for pending-del and delsel modes
1091(put 'py-delete-char 'delete-selection 'supersede)
1092(put 'py-delete-char 'pending-delete 'supersede)
1093
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001094(defun py-indent-line (&optional arg)
1095 "Fix the indentation of the current line according to Python rules.
1096With \\[universal-argument], ignore outdenting rules for block
1097closing statements (e.g. return, raise, break, continue, pass)
1098
1099This function is normally bound to `indent-line-function' so
1100\\[indent-for-tab-command] will call it."
1101 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001102 (let* ((ci (current-indentation))
1103 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001104 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001105 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001106 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001107 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001108 (if (/= ci need)
1109 (save-excursion
1110 (beginning-of-line)
1111 (delete-horizontal-space)
1112 (indent-to need)))
1113 (if move-to-indentation-p (back-to-indentation))))
1114
1115(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001116 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001117This is just `strives to' because correct indentation can't be computed
1118from scratch for Python code. In general, deletes the whitespace before
1119point, inserts a newline, and takes an educated guess as to how you want
1120the new line indented."
1121 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001122 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001123 (if (< ci (current-column)) ; if point beyond indentation
1124 (newline-and-indent)
1125 ;; else try to act like newline-and-indent "normally" acts
1126 (beginning-of-line)
1127 (insert-char ?\n 1)
1128 (move-to-column ci))))
1129
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001130(defun py-compute-indentation (honor-block-close-p)
1131 ;; implements all the rules for indentation computation. when
1132 ;; honor-block-close-p is non-nil, statements such as return, raise,
1133 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +00001135 (let ((pps (parse-partial-sexp (save-excursion
1136 (beginning-of-python-def-or-class)
1137 (point))
1138 (point))))
1139 (beginning-of-line)
1140 (cond
1141 ;; are we inside a string or comment?
1142 ((or (nth 3 pps) (nth 4 pps))
1143 (save-excursion
1144 (if (not py-align-multiline-strings-p) 0
1145 ;; skip back over blank & non-indenting comment lines
1146 ;; note: will skip a blank or non-indenting comment line
1147 ;; that happens to be a continuation line too
1148 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1149 (back-to-indentation)
1150 (current-column))))
1151 ;; are we on a continuation line?
1152 ((py-continuation-line-p)
1153 (let ((startpos (point))
1154 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001155 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001156 (if open-bracket-pos
1157 (progn
1158 ;; align with first item in list; else a normal
1159 ;; indent beyond the line with the open bracket
1160 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1161 ;; is the first list item on the same line?
1162 (skip-chars-forward " \t")
1163 (if (null (memq (following-char) '(?\n ?# ?\\)))
1164 ; yes, so line up with it
1165 (current-column)
1166 ;; first list item on another line, or doesn't exist yet
1167 (forward-line 1)
1168 (while (and (< (point) startpos)
1169 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1170 (forward-line 1))
1171 (if (< (point) startpos)
1172 ;; again mimic the first list item
1173 (current-indentation)
1174 ;; else they're about to enter the first item
1175 (goto-char open-bracket-pos)
1176 (+ (current-indentation) py-indent-offset))))
1177
1178 ;; else on backslash continuation line
1179 (forward-line -1)
1180 (if (py-continuation-line-p) ; on at least 3rd line in block
1181 (current-indentation) ; so just continue the pattern
1182 ;; else started on 2nd line in block, so indent more.
1183 ;; if base line is an assignment with a start on a RHS,
1184 ;; indent to 2 beyond the leftmost "="; else skip first
1185 ;; chunk of non-whitespace characters on base line, + 1 more
1186 ;; column
1187 (end-of-line)
1188 (setq endpos (point) searching t)
1189 (back-to-indentation)
1190 (setq startpos (point))
1191 ;; look at all "=" from left to right, stopping at first
1192 ;; one not nested in a list or string
1193 (while searching
1194 (skip-chars-forward "^=" endpos)
1195 (if (= (point) endpos)
1196 (setq searching nil)
1197 (forward-char 1)
1198 (setq state (parse-partial-sexp startpos (point)))
1199 (if (and (zerop (car state)) ; not in a bracket
1200 (null (nth 3 state))) ; & not in a string
1201 (progn
1202 (setq searching nil) ; done searching in any case
1203 (setq found
1204 (not (or
1205 (eq (following-char) ?=)
1206 (memq (char-after (- (point) 2))
1207 '(?< ?> ?!)))))))))
1208 (if (or (not found) ; not an assignment
1209 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1210 (progn
1211 (goto-char startpos)
1212 (skip-chars-forward "^ \t\n")))
1213 (1+ (current-column))))))
1214
1215 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001216 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001217
Barry Warsawa7891711996-08-01 15:53:09 +00001218 ;; Dfn: "Indenting comment line". A line containing only a
1219 ;; comment, but which is treated like a statement for
1220 ;; indentation calculation purposes. Such lines are only
1221 ;; treated specially by the mode; they are not treated
1222 ;; specially by the Python interpreter.
1223
1224 ;; The rules for indenting comment lines are a line where:
1225 ;; - the first non-whitespace character is `#', and
1226 ;; - the character following the `#' is whitespace, and
1227 ;; - the line is outdented with respect to (i.e. to the left
1228 ;; of) the indentation of the preceding non-blank line.
1229
1230 ;; The first non-blank line following an indenting comment
1231 ;; line is given the same amount of indentation as the
1232 ;; indenting comment line.
1233
1234 ;; All other comment-only lines are ignored for indentation
1235 ;; purposes.
1236
1237 ;; Are we looking at a comment-only line which is *not* an
1238 ;; indenting comment line? If so, we assume that its been
1239 ;; placed at the desired indentation, so leave it alone.
1240 ;; Indenting comment lines are aligned as statements down
1241 ;; below.
1242 ((and (looking-at "[ \t]*#[^ \t\n]")
1243 ;; NOTE: this test will not be performed in older Emacsen
1244 (fboundp 'forward-comment)
1245 (<= (current-indentation)
1246 (save-excursion
1247 (forward-comment (- (point-max)))
1248 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001249 (current-indentation))
1250
1251 ;; else indentation based on that of the statement that
1252 ;; precedes us; use the first line of that statement to
1253 ;; establish the base, in case the user forced a non-std
1254 ;; indentation for the continuation lines (if any)
1255 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001256 ;; skip back over blank & non-indenting comment lines note:
1257 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001258 ;; happens to be a continuation line too. use fast Emacs 19
1259 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001260 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001261 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001262 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001263 (let (done)
1264 (while (not done)
1265 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1266 nil 'move)
1267 (setq done (or (eq py-honor-comment-indentation t)
1268 (bobp)
1269 (/= (following-char) ?#)
1270 (not (zerop (current-column)))))
1271 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001272 ;; if we landed inside a string, go to the beginning of that
1273 ;; string. this handles triple quoted, multi-line spanning
1274 ;; strings.
1275 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001276 (+ (current-indentation)
1277 (if (py-statement-opens-block-p)
1278 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001279 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001280 (- py-indent-offset)
1281 0)))
1282 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001283
1284(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001285 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001286By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001287`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001288Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001289`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001290their own buffer-local copy), both those currently existing and those
1291created later in the Emacs session.
1292
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001293Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001294There's no excuse for such foolishness, but sometimes you have to deal
1295with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001296`py-indent-offset' to what it thinks it was when they created the
1297mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001298
1299Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001300looking for a line that opens a block of code. `py-indent-offset' is
1301set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001302statement following it. If the search doesn't succeed going forward,
1303it's tried again going backward."
1304 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001305 (let (new-value
1306 (start (point))
1307 restart
1308 (found nil)
1309 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001310 (py-goto-initial-line)
1311 (while (not (or found (eobp)))
1312 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1313 (progn
1314 (setq restart (point))
1315 (py-goto-initial-line)
1316 (if (py-statement-opens-block-p)
1317 (setq found t)
1318 (goto-char restart)))))
1319 (if found
1320 ()
1321 (goto-char start)
1322 (py-goto-initial-line)
1323 (while (not (or found (bobp)))
1324 (setq found
1325 (and
1326 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1327 (or (py-goto-initial-line) t) ; always true -- side effect
1328 (py-statement-opens-block-p)))))
1329 (setq colon-indent (current-indentation)
1330 found (and found (zerop (py-next-statement 1)))
1331 new-value (- (current-indentation) colon-indent))
1332 (goto-char start)
1333 (if found
1334 (progn
1335 (funcall (if global 'kill-local-variable 'make-local-variable)
1336 'py-indent-offset)
1337 (setq py-indent-offset new-value)
1338 (message "%s value of py-indent-offset set to %d"
1339 (if global "Global" "Local")
1340 py-indent-offset))
1341 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1342
1343(defun py-shift-region (start end count)
1344 (save-excursion
1345 (goto-char end) (beginning-of-line) (setq end (point))
1346 (goto-char start) (beginning-of-line) (setq start (point))
1347 (indent-rigidly start end count)))
1348
1349(defun py-shift-region-left (start end &optional count)
1350 "Shift region of Python code to the left.
1351The lines from the line containing the start of the current region up
1352to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001353shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354
1355If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001356many columns. With no active region, outdent only the current line.
1357You cannot outdent the region if any line is already at column zero."
1358 (interactive
1359 (let ((p (point))
1360 (m (mark))
1361 (arg current-prefix-arg))
1362 (if m
1363 (list (min p m) (max p m) arg)
1364 (list p (save-excursion (forward-line 1) (point)) arg))))
1365 ;; if any line is at column zero, don't shift the region
1366 (save-excursion
1367 (goto-char start)
1368 (while (< (point) end)
1369 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001370 (if (and (zerop (current-column))
1371 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001372 (error "Region is at left edge."))
1373 (forward-line 1)))
1374 (py-shift-region start end (- (prefix-numeric-value
1375 (or count py-indent-offset))))
1376 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001377
1378(defun py-shift-region-right (start end &optional count)
1379 "Shift region of Python code to the right.
1380The lines from the line containing the start of the current region up
1381to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001382shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001383
1384If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001385many columns. With no active region, indent only the current line."
1386 (interactive
1387 (let ((p (point))
1388 (m (mark))
1389 (arg current-prefix-arg))
1390 (if m
1391 (list (min p m) (max p m) arg)
1392 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001394 (or count py-indent-offset)))
1395 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001396
1397(defun py-indent-region (start end &optional indent-offset)
1398 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001399
Barry Warsaw7ae77681994-12-12 20:38:05 +00001400The lines from the line containing the start of the current region up
1401to (but not including) the line containing the end of the region are
1402reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001403character in the first column, the first line is left alone and the
1404rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001405region is reindented with respect to the (closest code or indenting
1406comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001407
1408This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409control structures are introduced or removed, or to reformat code
1410using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001411
1412If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001413the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001414used.
1415
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001416Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001417is called! This function does not compute proper indentation from
1418scratch (that's impossible in Python), it merely adjusts the existing
1419indentation to be correct in context.
1420
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001421Warning: This function really has no idea what to do with
1422non-indenting comment lines, and shifts them as if they were indenting
1423comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001424
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001425Special cases: whitespace is deleted from blank lines; continuation
1426lines are shifted by the same amount their initial line was shifted,
1427in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001428initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001429 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001430 (save-excursion
1431 (goto-char end) (beginning-of-line) (setq end (point-marker))
1432 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001433 (let ((py-indent-offset (prefix-numeric-value
1434 (or indent-offset py-indent-offset)))
1435 (indents '(-1)) ; stack of active indent levels
1436 (target-column 0) ; column to which to indent
1437 (base-shifted-by 0) ; amount last base line was shifted
1438 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001439 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001440 0))
1441 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001442 (while (< (point) end)
1443 (setq ci (current-indentation))
1444 ;; figure out appropriate target column
1445 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001446 ((or (eq (following-char) ?#) ; comment in column 1
1447 (looking-at "[ \t]*$")) ; entirely blank
1448 (setq target-column 0))
1449 ((py-continuation-line-p) ; shift relative to base line
1450 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001451 (t ; new base line
1452 (if (> ci (car indents)) ; going deeper; push it
1453 (setq indents (cons ci indents))
1454 ;; else we should have seen this indent before
1455 (setq indents (memq ci indents)) ; pop deeper indents
1456 (if (null indents)
1457 (error "Bad indentation in region, at line %d"
1458 (save-restriction
1459 (widen)
1460 (1+ (count-lines 1 (point)))))))
1461 (setq target-column (+ indent-base
1462 (* py-indent-offset
1463 (- (length indents) 2))))
1464 (setq base-shifted-by (- target-column ci))))
1465 ;; shift as needed
1466 (if (/= ci target-column)
1467 (progn
1468 (delete-horizontal-space)
1469 (indent-to target-column)))
1470 (forward-line 1))))
1471 (set-marker end nil))
1472
Barry Warsawa7891711996-08-01 15:53:09 +00001473(defun py-comment-region (beg end &optional arg)
1474 "Like `comment-region' but uses double hash (`#') comment starter."
1475 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001476 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001477 (comment-region beg end arg)))
1478
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479
1480;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001481(defun py-previous-statement (count)
1482 "Go to the start of previous Python statement.
1483If the statement at point is the i'th Python statement, goes to the
1484start of statement i-COUNT. If there is no such statement, goes to the
1485first statement. Returns count of statements left to move.
1486`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001487 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001488 (if (< count 0) (py-next-statement (- count))
1489 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001490 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001492 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001493 (> count 0)
1494 (zerop (forward-line -1))
1495 (py-goto-statement-at-or-above))
1496 (setq count (1- count)))
1497 (if (> count 0) (goto-char start)))
1498 count))
1499
1500(defun py-next-statement (count)
1501 "Go to the start of next Python statement.
1502If the statement at point is the i'th Python statement, goes to the
1503start of statement i+COUNT. If there is no such statement, goes to the
1504last statement. Returns count of statements left to move. `Statements'
1505do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001506 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001507 (if (< count 0) (py-previous-statement (- count))
1508 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001509 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001510 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001511 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001512 (> count 0)
1513 (py-goto-statement-below))
1514 (setq count (1- count)))
1515 (if (> count 0) (goto-char start)))
1516 count))
1517
1518(defun py-goto-block-up (&optional nomark)
1519 "Move up to start of current block.
1520Go to the statement that starts the smallest enclosing block; roughly
1521speaking, this will be the closest preceding statement that ends with a
1522colon and is indented less than the statement you started on. If
1523successful, also sets the mark to the starting point.
1524
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001525`\\[py-mark-block]' can be used afterward to mark the whole code
1526block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001527
1528If called from a program, the mark will not be set if optional argument
1529NOMARK is not nil."
1530 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531 (let ((start (point))
1532 (found nil)
1533 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001534 (py-goto-initial-line)
1535 ;; if on blank or non-indenting comment line, use the preceding stmt
1536 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1537 (progn
1538 (py-goto-statement-at-or-above)
1539 (setq found (py-statement-opens-block-p))))
1540 ;; search back for colon line indented less
1541 (setq initial-indent (current-indentation))
1542 (if (zerop initial-indent)
1543 ;; force fast exit
1544 (goto-char (point-min)))
1545 (while (not (or found (bobp)))
1546 (setq found
1547 (and
1548 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1549 (or (py-goto-initial-line) t) ; always true -- side effect
1550 (< (current-indentation) initial-indent)
1551 (py-statement-opens-block-p))))
1552 (if found
1553 (progn
1554 (or nomark (push-mark start))
1555 (back-to-indentation))
1556 (goto-char start)
1557 (error "Enclosing block not found"))))
1558
1559(defun beginning-of-python-def-or-class (&optional class)
1560 "Move point to start of def (or class, with prefix arg).
1561
1562Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001563arg, looks for a `class' instead. The docs assume the `def' case;
1564just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001565
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001566If point is in a def statement already, and after the `d', simply
1567moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001568
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001569Else (point is not in a def statement, or at or before the `d' of a
1570def statement), searches for the closest preceding def statement, and
1571leaves point at its start. If no such statement can be found, leaves
1572point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573
1574Returns t iff a def statement is found by these rules.
1575
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001576Note that doing this command repeatedly will take you closer to the
1577start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579If you want to mark the current def/class, see
1580`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001582 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1583 (start-of-line (progn (beginning-of-line) (point)))
1584 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001585 (if (or (/= start-of-stmt start-of-line)
1586 (not at-or-before-p))
1587 (end-of-line)) ; OK to match on this line
1588 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001589 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001590
1591(defun end-of-python-def-or-class (&optional class)
1592 "Move point beyond end of def (or class, with prefix arg) body.
1593
1594By default, looks for an appropriate `def'. If you supply a prefix arg,
1595looks for a `class' instead. The docs assume the `def' case; just
1596substitute `class' for `def' for the other case.
1597
1598If point is in a def statement already, this is the def we use.
1599
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001600Else if the def found by `\\[beginning-of-python-def-or-class]'
1601contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001602
1603Else we search forward for the closest following def, and use that.
1604
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001605If a def can be found by these rules, point is moved to the start of
1606the line immediately following the def block, and the position of the
1607start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001608
1609Else point is moved to the end of the buffer, and nil is returned.
1610
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001611Note that doing this command repeatedly will take you closer to the
1612end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001614If you want to mark the current def/class, see
1615`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001616 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001617 (let ((start (progn (py-goto-initial-line) (point)))
1618 (which (if class "class" "def"))
1619 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001620 ;; move point to start of appropriate def/class
1621 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1622 (setq state 'at-beginning)
1623 ;; else see if beginning-of-python-def-or-class hits container
1624 (if (and (beginning-of-python-def-or-class class)
1625 (progn (py-goto-beyond-block)
1626 (> (point) start)))
1627 (setq state 'at-end)
1628 ;; else search forward
1629 (goto-char start)
1630 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1631 (progn (setq state 'at-beginning)
1632 (beginning-of-line)))))
1633 (cond
1634 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1635 ((eq state 'at-end) t)
1636 ((eq state 'not-found) nil)
1637 (t (error "internal error in end-of-python-def-or-class")))))
1638
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001639
1640;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001641(defun py-mark-block (&optional extend just-move)
1642 "Mark following block of lines. With prefix arg, mark structure.
1643Easier to use than explain. It sets the region to an `interesting'
1644block of succeeding lines. If point is on a blank line, it goes down to
1645the next non-blank line. That will be the start of the region. The end
1646of the region depends on the kind of line at the start:
1647
1648 - If a comment, the region will include all succeeding comment lines up
1649 to (but not including) the next non-comment line (if any).
1650
1651 - Else if a prefix arg is given, and the line begins one of these
1652 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001653
1654 if elif else try except finally for while def class
1655
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656 the region will be set to the body of the structure, including
1657 following blocks that `belong' to it, but excluding trailing blank
1658 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001659 and all (if any) of the following `except' and `finally' blocks
1660 that belong to the `try' structure will be in the region. Ditto
1661 for if/elif/else, for/else and while/else structures, and (a bit
1662 degenerate, since they're always one-block structures) def and
1663 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001664
1665 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001666 block (see list above), and the block is not a `one-liner' (i.e.,
1667 the statement ends with a colon, not with code), the region will
1668 include all succeeding lines up to (but not including) the next
1669 code statement (if any) that's indented no more than the starting
1670 line, except that trailing blank and comment lines are excluded.
1671 E.g., if the starting line begins a multi-statement `def'
1672 structure, the region will be set to the full function definition,
1673 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674
1675 - Else the region will include all succeeding lines up to (but not
1676 including) the next blank line, or code or indenting-comment line
1677 indented strictly less than the starting line. Trailing indenting
1678 comment lines are included in this case, but not trailing blank
1679 lines.
1680
1681A msg identifying the location of the mark is displayed in the echo
1682area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1683
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001684If called from a program, optional argument EXTEND plays the role of
1685the prefix arg, and if optional argument JUST-MOVE is not nil, just
1686moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001687 (interactive "P") ; raw prefix arg
1688 (py-goto-initial-line)
1689 ;; skip over blank lines
1690 (while (and
1691 (looking-at "[ \t]*$") ; while blank line
1692 (not (eobp))) ; & somewhere to go
1693 (forward-line 1))
1694 (if (eobp)
1695 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001696 (let ((initial-pos (point))
1697 (initial-indent (current-indentation))
1698 last-pos ; position of last stmt in region
1699 (followers
1700 '((if elif else) (elif elif else) (else)
1701 (try except finally) (except except) (finally)
1702 (for else) (while else)
1703 (def) (class) ) )
1704 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001705
1706 (cond
1707 ;; if comment line, suck up the following comment lines
1708 ((looking-at "[ \t]*#")
1709 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1710 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1711 (setq last-pos (point)))
1712
1713 ;; else if line is a block line and EXTEND given, suck up
1714 ;; the whole structure
1715 ((and extend
1716 (setq first-symbol (py-suck-up-first-keyword) )
1717 (assq first-symbol followers))
1718 (while (and
1719 (or (py-goto-beyond-block) t) ; side effect
1720 (forward-line -1) ; side effect
1721 (setq last-pos (point)) ; side effect
1722 (py-goto-statement-below)
1723 (= (current-indentation) initial-indent)
1724 (setq next-symbol (py-suck-up-first-keyword))
1725 (memq next-symbol (cdr (assq first-symbol followers))))
1726 (setq first-symbol next-symbol)))
1727
1728 ;; else if line *opens* a block, search for next stmt indented <=
1729 ((py-statement-opens-block-p)
1730 (while (and
1731 (setq last-pos (point)) ; always true -- side effect
1732 (py-goto-statement-below)
1733 (> (current-indentation) initial-indent))
1734 nil))
1735
1736 ;; else plain code line; stop at next blank line, or stmt or
1737 ;; indenting comment line indented <
1738 (t
1739 (while (and
1740 (setq last-pos (point)) ; always true -- side effect
1741 (or (py-goto-beyond-final-line) t)
1742 (not (looking-at "[ \t]*$")) ; stop at blank line
1743 (or
1744 (>= (current-indentation) initial-indent)
1745 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1746 nil)))
1747
1748 ;; skip to end of last stmt
1749 (goto-char last-pos)
1750 (py-goto-beyond-final-line)
1751
1752 ;; set mark & display
1753 (if just-move
1754 () ; just return
1755 (push-mark (point) 'no-msg)
1756 (forward-line -1)
1757 (message "Mark set after: %s" (py-suck-up-leading-text))
1758 (goto-char initial-pos))))
1759
1760(defun mark-python-def-or-class (&optional class)
1761 "Set region to body of def (or class, with prefix arg) enclosing point.
1762Pushes the current mark, then point, on the mark ring (all language
1763modes do this, but although it's handy it's never documented ...).
1764
1765In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001766hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1767`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768
1769And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770Turned out that was more confusing than useful: the `goto start' and
1771`goto end' commands are usually used to search through a file, and
1772people expect them to act a lot like `search backward' and `search
1773forward' string-search commands. But because Python `def' and `class'
1774can nest to arbitrary levels, finding the smallest def containing
1775point cannot be done via a simple backward search: the def containing
1776point may not be the closest preceding def, or even the closest
1777preceding def that's indented less. The fancy algorithm required is
1778appropriate for the usual uses of this `mark' command, but not for the
1779`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001780
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001781So the def marked by this command may not be the one either of the
1782`goto' commands find: If point is on a blank or non-indenting comment
1783line, moves back to start of the closest preceding code statement or
1784indenting comment line. If this is a `def' statement, that's the def
1785we use. Else searches for the smallest enclosing `def' block and uses
1786that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001787
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788When an enclosing def is found: The mark is left immediately beyond
1789the last line of the def block. Point is left at the start of the
1790def, except that: if the def is preceded by a number of comment lines
1791followed by (at most) one optional blank line, point is left at the
1792start of the comments; else if the def is preceded by a blank line,
1793point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001794
1795The intent is to mark the containing def/class and its associated
1796documentation, to make moving and duplicating functions and classes
1797pleasant."
1798 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001799 (let ((start (point))
1800 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001801 (push-mark start)
1802 (if (not (py-go-up-tree-to-keyword which))
1803 (progn (goto-char start)
1804 (error "Enclosing %s not found" which))
1805 ;; else enclosing def/class found
1806 (setq start (point))
1807 (py-goto-beyond-block)
1808 (push-mark (point))
1809 (goto-char start)
1810 (if (zerop (forward-line -1)) ; if there is a preceding line
1811 (progn
1812 (if (looking-at "[ \t]*$") ; it's blank
1813 (setq start (point)) ; so reset start point
1814 (goto-char start)) ; else try again
1815 (if (zerop (forward-line -1))
1816 (if (looking-at "[ \t]*#") ; a comment
1817 ;; look back for non-comment line
1818 ;; tricky: note that the regexp matches a blank
1819 ;; line, cuz \n is in the 2nd character class
1820 (and
1821 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1822 (forward-line 1))
1823 ;; no comment, so go back
1824 (goto-char start))))))))
1825
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001826;; ripped from cc-mode
1827(defun py-forward-into-nomenclature (&optional arg)
1828 "Move forward to end of a nomenclature section or word.
1829With arg, to it arg times.
1830
1831A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1832 (interactive "p")
1833 (let ((case-fold-search nil))
1834 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001835 (re-search-forward
1836 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
1837 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001838 (while (and (< arg 0)
1839 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00001840 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001841 (point-min) 0))
1842 (forward-char 1)
1843 (setq arg (1+ arg)))))
1844 (py-keep-region-active))
1845
1846(defun py-backward-into-nomenclature (&optional arg)
1847 "Move backward to beginning of a nomenclature section or word.
1848With optional ARG, move that many times. If ARG is negative, move
1849forward.
1850
1851A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1852 (interactive "p")
1853 (py-forward-into-nomenclature (- arg))
1854 (py-keep-region-active))
1855
1856
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857
1858;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001859
1860;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001861;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1862;; out of the right places, along with the keys they're on & current
1863;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864(defun py-dump-help-string (str)
1865 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001866 (let ((locals (buffer-local-variables))
1867 funckind funcname func funcdoc
1868 (start 0) mstart end
1869 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001870 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1871 (setq mstart (match-beginning 0) end (match-end 0)
1872 funckind (substring str (match-beginning 1) (match-end 1))
1873 funcname (substring str (match-beginning 2) (match-end 2))
1874 func (intern funcname))
1875 (princ (substitute-command-keys (substring str start mstart)))
1876 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 ((equal funckind "c") ; command
1878 (setq funcdoc (documentation func)
1879 keys (concat
1880 "Key(s): "
1881 (mapconcat 'key-description
1882 (where-is-internal func py-mode-map)
1883 ", "))))
1884 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00001885 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001886 keys (if (assq func locals)
1887 (concat
1888 "Local/Global values: "
1889 (prin1-to-string (symbol-value func))
1890 " / "
1891 (prin1-to-string (default-value func)))
1892 (concat
1893 "Value: "
1894 (prin1-to-string (symbol-value func))))))
1895 (t ; unexpected
1896 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001897 (princ (format "\n-> %s:\t%s\t%s\n\n"
1898 (if (equal funckind "c") "Command" "Variable")
1899 funcname keys))
1900 (princ funcdoc)
1901 (terpri)
1902 (setq start end))
1903 (princ (substitute-command-keys (substring str start))))
1904 (print-help-return-message)))
1905
1906(defun py-describe-mode ()
1907 "Dump long form of Python-mode docs."
1908 (interactive)
1909 (py-dump-help-string "Major mode for editing Python files.
1910Knows about Python indentation, tokens, comments and continuation lines.
1911Paragraphs are separated by blank lines only.
1912
1913Major sections below begin with the string `@'; specific function and
1914variable docs begin with `->'.
1915
1916@EXECUTING PYTHON CODE
1917
1918\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1919\\[py-execute-region]\tsends the current region
1920\\[py-shell]\tstarts a Python interpreter window; this will be used by
1921\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1922%c:py-execute-buffer
1923%c:py-execute-region
1924%c:py-shell
1925
1926@VARIABLES
1927
1928py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00001929py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930
1931py-python-command\tshell command to invoke Python interpreter
1932py-scroll-process-buffer\talways scroll Python process buffer
1933py-temp-directory\tdirectory used for temp files (if needed)
1934
1935py-beep-if-tab-change\tring the bell if tab-width is changed
1936%v:py-indent-offset
1937%v:py-block-comment-prefix
1938%v:py-python-command
1939%v:py-scroll-process-buffer
1940%v:py-temp-directory
1941%v:py-beep-if-tab-change
1942
1943@KINDS OF LINES
1944
1945Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001946preceding line ends with a backslash that's not part of a comment, or
1947the paren/bracket/brace nesting level at the start of the line is
1948non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949
1950An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001951possibly blanks or tabs), a `comment line' (leftmost non-blank
1952character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001953
1954Comment Lines
1955
1956Although all comment lines are treated alike by Python, Python mode
1957recognizes two kinds that act differently with respect to indentation.
1958
1959An `indenting comment line' is a comment line with a blank, tab or
1960nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001962indenting comment line will be indented like the comment line. All
1963other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001964following the initial `#') are `non-indenting comment lines', and
1965their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001966
1967Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968whenever possible. Non-indenting comment lines are useful in cases
1969like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001970
1971\ta = b # a very wordy single-line comment that ends up being
1972\t #... continued onto another line
1973
1974\tif a == b:
1975##\t\tprint 'panic!' # old code we've `commented out'
1976\t\treturn a
1977
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001978Since the `#...' and `##' comment lines have a non-whitespace
1979character following the initial `#', Python mode ignores them when
1980computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981
1982Continuation Lines and Statements
1983
1984The Python-mode commands generally work on statements instead of on
1985individual lines, where a `statement' is a comment or blank line, or a
1986code line and all of its following continuation lines (if any)
1987considered as a single logical unit. The commands in this mode
1988generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001989statement containing point, even if point happens to be in the middle
1990of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991
1992
1993@INDENTATION
1994
1995Primarily for entering new code:
1996\t\\[indent-for-tab-command]\t indent line appropriately
1997\t\\[py-newline-and-indent]\t insert newline, then indent
1998\t\\[py-delete-char]\t reduce indentation, or delete single character
1999
2000Primarily for reindenting existing code:
2001\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2002\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2003
2004\t\\[py-indent-region]\t reindent region to match its context
2005\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2006\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2007
2008Unlike most programming languages, Python uses indentation, and only
2009indentation, to specify block structure. Hence the indentation supplied
2010automatically by Python-mode is just an educated guess: only you know
2011the block structure you intend, so only you can supply correct
2012indentation.
2013
2014The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2015the indentation of preceding statements. E.g., assuming
2016py-indent-offset is 4, after you enter
2017\tif a > 0: \\[py-newline-and-indent]
2018the cursor will be moved to the position of the `_' (_ is not a
2019character in the file, it's just used here to indicate the location of
2020the cursor):
2021\tif a > 0:
2022\t _
2023If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2024to
2025\tif a > 0:
2026\t c = d
2027\t _
2028Python-mode cannot know whether that's what you intended, or whether
2029\tif a > 0:
2030\t c = d
2031\t_
2032was your intent. In general, Python-mode either reproduces the
2033indentation of the (closest code or indenting-comment) preceding
2034statement, or adds an extra py-indent-offset blanks if the preceding
2035statement has `:' as its last significant (non-whitespace and non-
2036comment) character. If the suggested indentation is too much, use
2037\\[py-delete-char] to reduce it.
2038
2039Continuation lines are given extra indentation. If you don't like the
2040suggested indentation, change it to something you do like, and Python-
2041mode will strive to indent later lines of the statement in the same way.
2042
2043If a line is a continuation line by virtue of being in an unclosed
2044paren/bracket/brace structure (`list', for short), the suggested
2045indentation depends on whether the current line contains the first item
2046in the list. If it does, it's indented py-indent-offset columns beyond
2047the indentation of the line containing the open bracket. If you don't
2048like that, change it by hand. The remaining items in the list will mimic
2049whatever indentation you give to the first item.
2050
2051If a line is a continuation line because the line preceding it ends with
2052a backslash, the third and following lines of the statement inherit their
2053indentation from the line preceding them. The indentation of the second
2054line in the statement depends on the form of the first (base) line: if
2055the base line is an assignment statement with anything more interesting
2056than the backslash following the leftmost assigning `=', the second line
2057is indented two columns beyond that `='. Else it's indented to two
2058columns beyond the leftmost solid chunk of non-whitespace characters on
2059the base line.
2060
2061Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2062repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2063structure you intend.
2064%c:indent-for-tab-command
2065%c:py-newline-and-indent
2066%c:py-delete-char
2067
2068
2069The next function may be handy when editing code you didn't write:
2070%c:py-guess-indent-offset
2071
2072
2073The remaining `indent' functions apply to a region of Python code. They
2074assume the block structure (equals indentation, in Python) of the region
2075is correct, and alter the indentation in various ways while preserving
2076the block structure:
2077%c:py-indent-region
2078%c:py-shift-region-left
2079%c:py-shift-region-right
2080
2081@MARKING & MANIPULATING REGIONS OF CODE
2082
2083\\[py-mark-block]\t mark block of lines
2084\\[mark-python-def-or-class]\t mark smallest enclosing def
2085\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002086\\[comment-region]\t comment out region of code
2087\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002088%c:py-mark-block
2089%c:mark-python-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002090%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002091
2092@MOVING POINT
2093
2094\\[py-previous-statement]\t move to statement preceding point
2095\\[py-next-statement]\t move to statement following point
2096\\[py-goto-block-up]\t move up to start of current block
2097\\[beginning-of-python-def-or-class]\t move to start of def
2098\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2099\\[end-of-python-def-or-class]\t move to end of def
2100\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2101
2102The first two move to one statement beyond the statement that contains
2103point. A numeric prefix argument tells them to move that many
2104statements instead. Blank lines, comment lines, and continuation lines
2105do not count as `statements' for these commands. So, e.g., you can go
2106to the first code statement in a file by entering
2107\t\\[beginning-of-buffer]\t to move to the top of the file
2108\t\\[py-next-statement]\t to skip over initial comments and blank lines
2109Or do `\\[py-previous-statement]' with a huge prefix argument.
2110%c:py-previous-statement
2111%c:py-next-statement
2112%c:py-goto-block-up
2113%c:beginning-of-python-def-or-class
2114%c:end-of-python-def-or-class
2115
2116@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2117
2118`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2119
2120`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2121overall class and def structure of a module.
2122
2123`\\[back-to-indentation]' moves point to a line's first non-blank character.
2124
2125`\\[indent-relative]' is handy for creating odd indentation.
2126
2127@OTHER EMACS HINTS
2128
2129If you don't like the default value of a variable, change its value to
2130whatever you do like by putting a `setq' line in your .emacs file.
2131E.g., to set the indentation increment to 4, put this line in your
2132.emacs:
2133\t(setq py-indent-offset 4)
2134To see the value of a variable, do `\\[describe-variable]' and enter the variable
2135name at the prompt.
2136
2137When entering a key sequence like `C-c C-n', it is not necessary to
2138release the CONTROL key after doing the `C-c' part -- it suffices to
2139press the CONTROL key, press and release `c' (while still holding down
2140CONTROL), press and release `n' (while still holding down CONTROL), &
2141then release CONTROL.
2142
2143Entering Python mode calls with no arguments the value of the variable
2144`python-mode-hook', if that value exists and is not nil; for backward
2145compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2146the Elisp manual for details.
2147
2148Obscure: When python-mode is first loaded, it looks for all bindings
2149to newline-and-indent in the global keymap, and shadows them with
2150local bindings to py-newline-and-indent."))
2151
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002152
2153;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154(defvar py-parse-state-re
2155 (concat
2156 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2157 "\\|"
2158 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002159
Barry Warsaw7ae77681994-12-12 20:38:05 +00002160;; returns the parse state at point (see parse-partial-sexp docs)
2161(defun py-parse-state ()
2162 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002163 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002164 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002165 (while (not done)
2166 ;; back up to the first preceding line (if any; else start of
2167 ;; buffer) that begins with a popular Python keyword, or a
2168 ;; non- whitespace and non-comment character. These are good
2169 ;; places to start parsing to see whether where we started is
2170 ;; at a non-zero nesting level. It may be slow for people who
2171 ;; write huge code blocks or huge lists ... tough beans.
2172 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002173 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002174 (beginning-of-line)
2175 (save-excursion
2176 (setq pps (parse-partial-sexp (point) here)))
2177 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002178 (setq done (or (zerop ci)
2179 (not (nth 3 pps))
2180 (bobp)))
2181 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002182 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183
2184;; if point is at a non-zero nesting level, returns the number of the
2185;; character that opens the smallest enclosing unclosed list; else
2186;; returns nil.
2187(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002188 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002189 (if (zerop (car status))
2190 nil ; not in a nest
2191 (car (cdr status))))) ; char# of open bracket
2192
2193;; t iff preceding line ends with backslash that's not in a comment
2194(defun py-backslash-continuation-line-p ()
2195 (save-excursion
2196 (beginning-of-line)
2197 (and
2198 ;; use a cheap test first to avoid the regexp if possible
2199 ;; use 'eq' because char-after may return nil
2200 (eq (char-after (- (point) 2)) ?\\ )
2201 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002202 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002203 (looking-at py-continued-re))))
2204
2205;; t iff current line is a continuation line
2206(defun py-continuation-line-p ()
2207 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002208 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002209 (or (py-backslash-continuation-line-p)
2210 (py-nesting-level))))
2211
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212;; go to initial line of current statement; usually this is the line
2213;; we're on, but if we're on the 2nd or following lines of a
2214;; continuation block, we need to go up to the first line of the
2215;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002216;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002217;; Tricky: We want to avoid quadratic-time behavior for long continued
2218;; blocks, whether of the backslash or open-bracket varieties, or a
2219;; mix of the two. The following manages to do that in the usual
2220;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002221(defun py-goto-initial-line ()
2222 (let ( open-bracket-pos )
2223 (while (py-continuation-line-p)
2224 (beginning-of-line)
2225 (if (py-backslash-continuation-line-p)
2226 (while (py-backslash-continuation-line-p)
2227 (forward-line -1))
2228 ;; else zip out of nested brackets/braces/parens
2229 (while (setq open-bracket-pos (py-nesting-level))
2230 (goto-char open-bracket-pos)))))
2231 (beginning-of-line))
2232
2233;; go to point right beyond final line of current statement; usually
2234;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002235;; statement we need to skip over the continuation lines. Tricky:
2236;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002237(defun py-goto-beyond-final-line ()
2238 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002239 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002240 (while (and (py-continuation-line-p)
2241 (not (eobp)))
2242 ;; skip over the backslash flavor
2243 (while (and (py-backslash-continuation-line-p)
2244 (not (eobp)))
2245 (forward-line 1))
2246 ;; if in nest, zip to the end of the nest
2247 (setq state (py-parse-state))
2248 (if (and (not (zerop (car state)))
2249 (not (eobp)))
2250 (progn
Barry Warsawf7705781997-01-30 19:49:39 +00002251 (parse-partial-sexp (point) (point-max)
2252 (if py-parse-partial-sexp-works-p
2253 0 (- 0 (car state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002254 nil state)
2255 (forward-line 1))))))
2256
2257;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002258;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002259(defun py-statement-opens-block-p ()
2260 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002261 (let ((start (point))
2262 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2263 (searching t)
2264 (answer nil)
2265 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266 (goto-char start)
2267 (while searching
2268 ;; look for a colon with nothing after it except whitespace, and
2269 ;; maybe a comment
2270 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2271 finish t)
2272 (if (eq (point) finish) ; note: no `else' clause; just
2273 ; keep searching if we're not at
2274 ; the end yet
2275 ;; sure looks like it opens a block -- but it might
2276 ;; be in a comment
2277 (progn
2278 (setq searching nil) ; search is done either way
2279 (setq state (parse-partial-sexp start
2280 (match-beginning 0)))
2281 (setq answer (not (nth 4 state)))))
2282 ;; search failed: couldn't find another interesting colon
2283 (setq searching nil)))
2284 answer)))
2285
Barry Warsawf831d811996-07-31 20:42:59 +00002286(defun py-statement-closes-block-p ()
2287 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002288 ;; starts with `return', `raise', `break', `continue', and `pass'.
2289 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002290 (let ((here (point)))
2291 (back-to-indentation)
2292 (prog1
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002293 (looking-at "\\(return\\|raise\\|break\\|continue\\|pass\\)\\>")
Barry Warsawf831d811996-07-31 20:42:59 +00002294 (goto-char here))))
2295
Barry Warsaw7ae77681994-12-12 20:38:05 +00002296;; go to point right beyond final line of block begun by the current
2297;; line. This is the same as where py-goto-beyond-final-line goes
2298;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002299;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002300(defun py-goto-beyond-block ()
2301 (if (py-statement-opens-block-p)
2302 (py-mark-block nil 'just-move)
2303 (py-goto-beyond-final-line)))
2304
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002305;; go to start of first statement (not blank or comment or
2306;; continuation line) at or preceding point. returns t if there is
2307;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002308(defun py-goto-statement-at-or-above ()
2309 (py-goto-initial-line)
2310 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002311 ;; skip back over blank & comment lines
2312 ;; note: will skip a blank or comment line that happens to be
2313 ;; a continuation line too
2314 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2315 (progn (py-goto-initial-line) t)
2316 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002317 t))
2318
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002319;; go to start of first statement (not blank or comment or
2320;; continuation line) following the statement containing point returns
2321;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322(defun py-goto-statement-below ()
2323 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002324 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002325 (py-goto-beyond-final-line)
2326 (while (and
2327 (looking-at py-blank-or-comment-re)
2328 (not (eobp)))
2329 (forward-line 1))
2330 (if (eobp)
2331 (progn (goto-char start) nil)
2332 t)))
2333
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002334;; go to start of statement, at or preceding point, starting with
2335;; keyword KEY. Skips blank lines and non-indenting comments upward
2336;; first. If that statement starts with KEY, done, else go back to
2337;; first enclosing block starting with KEY. If successful, leaves
2338;; point at the start of the KEY line & returns t. Else leaves point
2339;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002340(defun py-go-up-tree-to-keyword (key)
2341 ;; skip blanks and non-indenting #
2342 (py-goto-initial-line)
2343 (while (and
2344 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2345 (zerop (forward-line -1))) ; go back
2346 nil)
2347 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002348 (let* ((re (concat "[ \t]*" key "\\b"))
2349 (case-fold-search nil) ; let* so looking-at sees this
2350 (found (looking-at re))
2351 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002352 (while (not (or found dead))
2353 (condition-case nil ; in case no enclosing block
2354 (py-goto-block-up 'no-mark)
2355 (error (setq dead t)))
2356 (or dead (setq found (looking-at re))))
2357 (beginning-of-line)
2358 found))
2359
2360;; return string in buffer from start of indentation to end of line;
2361;; prefix "..." if leading whitespace was skipped
2362(defun py-suck-up-leading-text ()
2363 (save-excursion
2364 (back-to-indentation)
2365 (concat
2366 (if (bolp) "" "...")
2367 (buffer-substring (point) (progn (end-of-line) (point))))))
2368
2369;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2370;; as a Lisp symbol; return nil if none
2371(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002372 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002373 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2374 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2375 nil)))
2376
2377(defun py-make-temp-name ()
2378 (make-temp-name
2379 (concat (file-name-as-directory py-temp-directory) "python")))
2380
2381(defun py-delete-file-silently (fname)
2382 (condition-case nil
2383 (delete-file fname)
2384 (error nil)))
2385
2386(defun py-kill-emacs-hook ()
2387 ;; delete our temp files
Barry Warsawc72c11c1997-08-09 06:42:08 +00002388 (py-safe (while py-file-queue
2389 (py-delete-file-silently (car py-file-queue))
2390 (setq py-file-queue (cdr py-file-queue)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002391
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002392;; make PROCESS's buffer visible, append STRING to it, and force
2393;; display; also make shell-mode believe the user typed this string,
2394;; so that kill-output-from-shell and show-output-from-shell work
2395;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00002396(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002397 (let ((cbuf (current-buffer))
2398 (pbuf (process-buffer process))
2399 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002400 (set-buffer pbuf)
2401 (goto-char (point-max))
2402 (move-marker (process-mark process) (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002403 (funcall (process-filter process) process string)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002404 (set-buffer cbuf))
2405 (sit-for 0))
2406
Barry Warsaw3622e0d1996-10-29 15:32:57 +00002407;; older Emacsen don't have this function
2408(if (not (fboundp 'match-string))
2409 (defun match-string (n)
2410 (let ((beg (match-beginning n))
2411 (end (match-end n)))
2412 (if (and beg end)
2413 (buffer-substring beg end)
2414 nil))))
2415
Barry Warsawb3e81d51996-09-04 15:12:42 +00002416(defun py-current-defun ()
2417 ;; tell add-log.el how to find the current function/method/variable
2418 (save-excursion
2419 (if (re-search-backward py-defun-start-re nil t)
2420 (or (match-string 3)
2421 (let ((method (match-string 2)))
2422 (if (and (not (zerop (length (match-string 1))))
2423 (re-search-backward py-class-start-re nil t))
2424 (concat (match-string 1) "." method)
2425 method)))
2426 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002427
2428
Barry Warsawfec75d61995-07-05 23:26:15 +00002429(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002430 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002431
Barry Warsaw850437a1995-03-08 21:50:28 +00002432(defun py-version ()
2433 "Echo the current version of `python-mode' in the minibuffer."
2434 (interactive)
2435 (message "Using `python-mode' version %s" py-version)
2436 (py-keep-region-active))
2437
2438;; only works under Emacs 19
2439;(eval-when-compile
2440; (require 'reporter))
2441
2442(defun py-submit-bug-report (enhancement-p)
2443 "Submit via mail a bug report on `python-mode'.
2444With \\[universal-argument] just submit an enhancement request."
2445 (interactive
2446 (list (not (y-or-n-p
2447 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002448 (let ((reporter-prompt-for-summary-p (if enhancement-p
2449 "(Very) brief summary: "
2450 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002451 (require 'reporter)
2452 (reporter-submit-bug-report
2453 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002454 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002455 ;; varlist
2456 (if enhancement-p nil
2457 '(py-python-command
2458 py-indent-offset
2459 py-block-comment-prefix
2460 py-scroll-process-buffer
2461 py-temp-directory
2462 py-beep-if-tab-change))
2463 nil ;pre-hooks
2464 nil ;post-hooks
2465 "Dear Barry,") ;salutation
2466 (if enhancement-p nil
2467 (set-mark (point))
2468 (insert
2469"Please replace this text with a sufficiently large code sample\n\
2470and an exact recipe so that I can reproduce your problem. Failure\n\
2471to do so may mean a greater delay in fixing your bug.\n\n")
2472 (exchange-point-and-mark)
2473 (py-keep-region-active))))
2474
2475
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002476;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002477(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002478
2479
2480
2481(provide 'python-mode)
2482;;; python-mode.el ends here