blob: 4cb40a6288598177445f4141576563117359aad2 [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 Warsaw4669d7e1996-03-22 16:13:24 +00005;; Author: 1995-1996 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 Warsaw7b0f5681995-03-08 21:33:04 +00009;; Version: $Revision$
10;; Last Modified: $Date$
Barry Warsaw4669d7e1996-03-22 16:13:24 +000011;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000012
Barry Warsawcfec3591995-03-10 15:58:16 +000013;; This software is provided as-is, without express or implied
14;; warranty. Permission to use, copy, modify, distribute or sell this
15;; software, without fee, for any purpose and by any individual or
16;; organization, is hereby granted, provided that the above copyright
17;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000018
19;;; Commentary:
Barry Warsaw7ae77681994-12-12 20:38:05 +000020;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000021;; This is a major mode for editing Python programs. It was developed
22;; by Tim Peters <tim@ksr.com> after an original idea by Michael
23;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000024;; (Barry) have undertaken maintenance of the mode.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000025
26;; At some point this mode will undergo a rewrite to bring it more in
27;; line with GNU Emacs Lisp coding standards. But all in all, the
Barry Warsaw03970731996-07-03 23:12:52 +000028;; mode works exceedingly well, and I've simply been tweaking it as I
Barry Warsaw4669d7e1996-03-22 16:13:24 +000029;; go along. Ain't it wonderful that Python has a much more sane
Barry Warsaw03970731996-07-03 23:12:52 +000030;; syntax than C? (or <shudder> C++?! :-). I can say that; I maintain
31;; cc-mode!
Barry Warsaw7b0f5681995-03-08 21:33:04 +000032
33;; The following statements, placed in your .emacs file or
34;; site-init.el, will cause this file to be autoloaded, and
35;; python-mode invoked, when visiting .py files (assuming this file is
36;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000037;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000038;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000039;; (setq auto-mode-alist
40;; (cons '("\\.py$" . python-mode) auto-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000041;;
42;; If you want font-lock support for Python source code (a.k.a. syntax
43;; coloring, highlighting), add this to your .emacs file:
44;;
45;; (add-hook 'python-mode-hook 'turn-on-font-lock)
Barry Warsaw7ae77681994-12-12 20:38:05 +000046
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000047;; Here's a brief list of recent additions/improvements:
48;;
49;; - Wrapping and indentation within triple quote strings should work
50;; properly now.
51;; - `Standard' bug reporting mechanism (use C-c C-b)
52;; - py-mark-block was moved to C-c C-m
53;; - C-c C-v shows you the python-mode version
54;; - a basic python-font-lock-keywords has been added for Emacs 19
55;; font-lock colorizations.
56;; - proper interaction with pending-del and del-sel modes.
57;; - New py-electric-colon (:) command for improved outdenting. Also
58;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw03970731996-07-03 23:12:52 +000059;; - improved (I think) C-c > and C-c <
Barry Warsaw9e5a9c81996-07-24 18:26:53 +000060;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
61;; M-f and M-b respectively.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000062
Barry Warsaw7b0f5681995-03-08 21:33:04 +000063;; Here's a brief to do list:
64;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000065;; - Better integration with gud-mode for debugging.
66;; - Rewrite according to GNU Emacs Lisp standards.
67;; - py-delete-char should obey numeric arguments.
68;; - even better support for outdenting. Guido suggests outdents of
69;; at least one level after a return, raise, break, or continue
Barry Warsawfc9cc3a1996-07-08 22:37:06 +000070;; statement. I also suggest trying to match up try/finally's and
71;; the like.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000072;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000073
Barry Warsaw7b0f5681995-03-08 21:33:04 +000074;; If you can think of more things you'd like to see, drop me a line.
75;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
76;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000077;; Note that I only test things on XEmacs. If you port stuff to FSF
78;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
79;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
Barry Warsaw7b0f5681995-03-08 21:33:04 +000081;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000082;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000083;; |Major mode for editing Python programs
84;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000085
Barry Warsaw7b0f5681995-03-08 21:33:04 +000086;;; Code:
87
88
89;; user definable variables
90;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000091
92(defvar py-python-command "python"
93 "*Shell command used to start Python interpreter.")
94
Barry Warsaw17914f41995-11-03 18:25:15 +000095(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000096 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000097Note that `\\[py-guess-indent-offset]' can usually guess a good value
98when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000099
Barry Warsaw095e9c61995-09-19 20:01:42 +0000100(defvar py-align-multiline-strings-p t
101 "*Flag describing how multiline triple quoted strings are aligned.
102When this flag is non-nil, continuation lines are lined up under the
103preceding line's indentation. When this flag is nil, continuation
104lines are aligned to column zero.")
105
Barry Warsaw7ae77681994-12-12 20:38:05 +0000106(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000107 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000108This should follow the convention for non-indenting comment lines so
109that the indentation commands won't get confused (i.e., the string
110should be of the form `#x...' where `x' is not a blank or a tab, and
111`...' is arbitrary).")
112
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000113(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000114 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000115
Barry Warsaw6d627751996-03-06 18:41:38 +0000116When nil, all comment lines are skipped for indentation purposes, and
117in Emacs 19, a faster algorithm is used.
118
119When t, lines that begin with a single `#' are a hint to subsequent
120line indentation. If the previous line is such a comment line (as
121opposed to one that starts with `py-block-comment-prefix'), then it's
122indentation is used as a hint for this line's indentation. Lines that
123begin with `py-block-comment-prefix' are ignored for indentation
124purposes.
125
126When not nil or t, comment lines that begin with a `#' are used as
127indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000128
Barry Warsaw7ae77681994-12-12 20:38:05 +0000129(defvar py-scroll-process-buffer t
130 "*Scroll Python process buffer as output arrives.
131If nil, the Python process buffer acts, with respect to scrolling, like
132Shell-mode buffers normally act. This is surprisingly complicated and
133so won't be explained here; in fact, you can't get the whole story
134without studying the Emacs C code.
135
136If non-nil, the behavior is different in two respects (which are
137slightly inaccurate in the interest of brevity):
138
139 - If the buffer is in a window, and you left point at its end, the
140 window will scroll as new output arrives, and point will move to the
141 buffer's end, even if the window is not the selected window (that
142 being the one the cursor is in). The usual behavior for shell-mode
143 windows is not to scroll, and to leave point where it was, if the
144 buffer is in a window other than the selected window.
145
146 - If the buffer is not visible in any window, and you left point at
147 its end, the buffer will be popped into a window as soon as more
148 output arrives. This is handy if you have a long-running
149 computation and don't want to tie up screen area waiting for the
150 output. The usual behavior for a shell-mode buffer is to stay
151 invisible until you explicitly visit it.
152
153Note the `and if you left point at its end' clauses in both of the
154above: you can `turn off' the special behaviors while output is in
155progress, by visiting the Python buffer and moving point to anywhere
156besides the end. Then the buffer won't scroll, point will remain where
157you leave it, and if you hide the buffer it will stay hidden until you
158visit it again. You can enable and disable the special behaviors as
159often as you like, while output is in progress, by (respectively) moving
160point to, or away from, the end of the buffer.
161
162Warning: If you expect a large amount of output, you'll probably be
163happier setting this option to nil.
164
165Obscure: `End of buffer' above should really say `at or beyond the
166process mark', but if you know what that means you didn't need to be
167told <grin>.")
168
169(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000170 (let ((ok '(lambda (x)
171 (and x
172 (setq x (expand-file-name x)) ; always true
173 (file-directory-p x)
174 (file-writable-p x)
175 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000176 (or (funcall ok (getenv "TMPDIR"))
177 (funcall ok "/usr/tmp")
178 (funcall ok "/tmp")
179 (funcall ok ".")
180 (error
181 "Couldn't find a usable temp directory -- set py-temp-directory")))
182 "*Directory used for temp files created by a *Python* process.
183By default, the first directory from this list that exists and that you
184can write into: the value (if any) of the environment variable TMPDIR,
185/usr/tmp, /tmp, or the current directory.")
186
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000187(defvar py-beep-if-tab-change t
188 "*Ring the bell if tab-width is changed.
189If a comment of the form
190
191 \t# vi:set tabsize=<number>:
192
193is found before the first code line when the file is entered, and the
194current value of (the general Emacs variable) `tab-width' does not
195equal <number>, `tab-width' is set to <number>, a message saying so is
196displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
197the Emacs bell is also rung as a warning.")
198
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000199(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000200 (let* ((keywords '("access" "and" "break" "class"
201 "continue" "def" "del" "elif"
202 "else:" "except" "except:" "exec"
203 "finally:" "for" "from" "global"
204 "if" "import" "in" "is"
205 "lambda" "not" "or" "pass"
206 "print" "raise" "return" "try:"
207 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000208 ))
209 (kwregex (mapconcat 'identity keywords "\\|")))
210 (list
211 ;; keywords not at beginning of line
212 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
213 ;; keywords at beginning of line. i don't think regexps are
214 ;; powerful enough to handle these two cases in one regexp.
215 ;; prove me wrong!
216 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
217 ;; classes
218 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
219 1 font-lock-type-face)
220 ;; functions
221 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
222 1 font-lock-function-name-face)
223 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000224 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000225
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000226
227;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
228;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
229
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000230(make-variable-buffer-local 'py-indent-offset)
231
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000232;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
233;; seems to be the standard way of checking this.
234;; BAW - This is *not* the right solution. When at all possible,
235;; instead of testing for the version of Emacs, use feature tests.
236
237(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
238(setq py-this-is-emacs-19-p
239 (and
240 (not py-this-is-lucid-emacs-p)
241 (string-match "^19\\." emacs-version)))
242
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243;; have to bind py-file-queue before installing the kill-emacs hook
244(defvar py-file-queue nil
245 "Queue of Python temp files awaiting execution.
246Currently-active file is at the head of the list.")
247
248;; define a mode-specific abbrev table for those who use such things
249(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251(define-abbrev-table 'python-mode-abbrev-table nil)
252
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253(defvar python-mode-hook nil
254 "*Hook called by `python-mode'.")
255
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256;; in previous version of python-mode.el, the hook was incorrectly
257;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000258(and (fboundp 'make-obsolete-variable)
259 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
260
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000261(defvar py-mode-map ()
262 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000263
Barry Warsaw7ae77681994-12-12 20:38:05 +0000264(if py-mode-map
265 ()
266 (setq py-mode-map (make-sparse-keymap))
267
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000268 ;; shadow global bindings for newline-and-indent w/ the py- version.
269 ;; BAW - this is extremely bad form, but I'm not going to change it
270 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271 (mapcar (function (lambda (key)
272 (define-key
273 py-mode-map key 'py-newline-and-indent)))
274 (where-is-internal 'newline-and-indent))
275
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 ;; BAW - you could do it this way, but its not considered proper
277 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000278 (mapcar (function
279 (lambda (x)
280 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000281 '((":" . py-electric-colon)
282 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 ("\C-c|" . py-execute-region)
284 ("\C-c!" . py-shell)
285 ("\177" . py-delete-char)
286 ("\n" . py-newline-and-indent)
287 ("\C-c:" . py-guess-indent-offset)
288 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000289 ("\C-c\C-l" . py-shift-region-left)
290 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 ("\C-c<" . py-shift-region-left)
292 ("\C-c>" . py-shift-region-right)
293 ("\C-c\C-n" . py-next-statement)
294 ("\C-c\C-p" . py-previous-statement)
295 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000296 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000297 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000298 ("\C-c?" . py-describe-mode)
299 ("\C-c\C-hm" . py-describe-mode)
300 ("\e\C-a" . beginning-of-python-def-or-class)
301 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000302 ( "\e\C-h" . mark-python-def-or-class)))
303 ;; should do all keybindings this way
304 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
305 (define-key py-mode-map "\C-c\C-v" 'py-version)
306 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000307
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000308(defvar py-mode-syntax-table nil
309 "Syntax table used in `python-mode' buffers.")
310
Barry Warsaw7ae77681994-12-12 20:38:05 +0000311(if py-mode-syntax-table
312 ()
313 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000314 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315 (mapcar (function
316 (lambda (x) (modify-syntax-entry
317 (car x) (cdr x) py-mode-syntax-table)))
318 '(( ?\( . "()" ) ( ?\) . ")(" )
319 ( ?\[ . "(]" ) ( ?\] . ")[" )
320 ( ?\{ . "(}" ) ( ?\} . "){" )
321 ;; fix operator symbols misassigned in the std table
322 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
323 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
324 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
325 ( ?\> . "." ) ( ?\| . "." )
Barry Warsawfb349421996-07-24 18:32:08 +0000326 ;; for historical reasons, underscore is word class
327 ;; instead of symbol class. it should be symbol class,
328 ;; but if you're tempted to change it, try binding M-f and
329 ;; M-b to py-forward-into-nomenclature and
330 ;; py-backward-into-nomenclature instead. -baw
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000331 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000332 ( ?\' . "\"") ; single quote is string quote
333 ( ?\" . "\"" ) ; double quote is string quote too
334 ( ?\` . "$") ; backquote is open and close paren
335 ( ?\# . "<") ; hash starts comment
336 ( ?\n . ">")))) ; newline ends comment
337
338(defconst py-stringlit-re
339 (concat
340 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
341 "\\|" ; or
342 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000343 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000344
345;; this is tricky because a trailing backslash does not mean
346;; continuation if it's in a comment
347(defconst py-continued-re
348 (concat
349 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
350 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000351 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000352
353(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000354 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000355
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000356(defconst py-outdent-re
357 (concat "\\(" (mapconcat 'identity
358 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000359 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000360 "finally:"
361 "elif\\s +.*:")
362 "\\|")
363 "\\)")
364 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000365
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000366(defconst py-no-outdent-re
367 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000368 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000369 "except\\(\\s +.*\\)?:"
370 "while\\s +.*:"
371 "for\\s +.*:"
372 "if\\s +.*:"
373 "elif\\s +.*:")
374 "\\|")
375 "\\)")
376 "Regexp matching lines to not outdent after.")
377
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378
379;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000380(defun python-mode ()
381 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000382To submit a problem report, enter `\\[py-submit-bug-report]' from a
383`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
384documentation. To see what version of `python-mode' you are running,
385enter `\\[py-version]'.
386
387This mode knows about Python indentation, tokens, comments and
388continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000389
390COMMANDS
391\\{py-mode-map}
392VARIABLES
393
394py-indent-offset\tindentation increment
395py-block-comment-prefix\tcomment string used by py-comment-region
396py-python-command\tshell command to invoke Python interpreter
397py-scroll-process-buffer\talways scroll Python process buffer
398py-temp-directory\tdirectory used for temp files (if needed)
399py-beep-if-tab-change\tring the bell if tab-width is changed"
400 (interactive)
401 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000402 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000403 (setq major-mode 'python-mode
404 mode-name "Python"
405 local-abbrev-table python-mode-abbrev-table)
406 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000407 ;; Emacs 19 requires this
408 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
409 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000410 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000411 (mapcar (function (lambda (x)
412 (make-local-variable (car x))
413 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 '((paragraph-separate . "^[ \t]*$")
415 (paragraph-start . "^[ \t]*$")
416 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000417 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000418 (comment-start-skip . "# *")
419 (comment-column . 40)
420 (indent-region-function . py-indent-region)
421 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000422 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000423 ;;
424 ;; not sure where the magic comment has to be; to save time
425 ;; searching for a rarity, we give up if it's not found prior to the
426 ;; first executable statement.
427 ;;
428 ;; BAW - on first glance, this seems like complete hackery. Why was
429 ;; this necessary, and is it still necessary?
430 (let ((case-fold-search nil)
431 (start (point))
432 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000433 (if (re-search-forward
434 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
435 (prog2 (py-next-statement 1) (point) (goto-char 1))
436 t)
437 (progn
438 (setq new-tab-width
439 (string-to-int
440 (buffer-substring (match-beginning 1) (match-end 1))))
441 (if (= tab-width new-tab-width)
442 nil
443 (setq tab-width new-tab-width)
444 (message "Caution: tab-width changed to %d" new-tab-width)
445 (if py-beep-if-tab-change (beep)))))
446 (goto-char start))
447
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000448 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000449 (if python-mode-hook
450 (run-hooks 'python-mode-hook)
451 (run-hooks 'py-mode-hook)))
452
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000453
Barry Warsaw826255b1996-03-22 16:09:34 +0000454(defun py-keep-region-active ()
455 ;; Do whatever is necessary to keep the region active in
456 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
457 ;; ignore byte-compiler warnings you might see.
458 (and (boundp 'zmacs-region-stays)
459 (setq zmacs-region-stays t)))
460
Barry Warsawb91b7431995-03-14 15:55:20 +0000461;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000462(defun py-outdent-p ()
463 ;; returns non-nil if the current line should outdent one level
464 (save-excursion
465 (and (progn (back-to-indentation)
466 (looking-at py-outdent-re))
467 (progn (backward-to-indentation 1)
468 (while (or (looking-at py-blank-or-comment-re)
469 (bobp))
470 (backward-to-indentation 1))
471 (not (looking-at py-no-outdent-re)))
472 )))
473
474
Barry Warsawb91b7431995-03-14 15:55:20 +0000475(defun py-electric-colon (arg)
476 "Insert a colon.
477In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000478argument is provided, that many colons are inserted non-electrically.
479Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000480 (interactive "P")
481 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000482 ;; are we in a string or comment?
483 (if (save-excursion
484 (let ((pps (parse-partial-sexp (save-excursion
485 (beginning-of-python-def-or-class)
486 (point))
487 (point))))
488 (not (or (nth 3 pps) (nth 4 pps)))))
489 (save-excursion
490 (let ((here (point))
491 (outdent 0)
492 (indent (py-compute-indentation)))
493 (if (and (not arg)
494 (py-outdent-p)
495 (= indent (save-excursion
496 (forward-line -1)
497 (py-compute-indentation)))
498 )
499 (setq outdent py-indent-offset))
500 ;; Don't indent, only outdent. This assumes that any lines that
501 ;; are already outdented relative to py-compute-indentation were
502 ;; put there on purpose. Its highly annoying to have `:' indent
503 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
504 ;; there a better way to determine this???
505 (if (< (current-indentation) indent) nil
506 (goto-char here)
507 (beginning-of-line)
508 (delete-horizontal-space)
509 (indent-to (- indent outdent))
510 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000511
512
Barry Warsaw7ae77681994-12-12 20:38:05 +0000513;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000514(defun py-shell ()
515 "Start an interactive Python interpreter in another window.
516This is like Shell mode, except that Python is running in the window
517instead of a shell. See the `Interactive Shell' and `Shell Mode'
518sections of the Emacs manual for details, especially for the key
519bindings active in the `*Python*' buffer.
520
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000521See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000522behavior in the process window.
523
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000524Warning: Don't use an interactive Python if you change sys.ps1 or
525sys.ps2 from their default values, or if you're running code that
526prints `>>> ' or `... ' at the start of a line. `python-mode' can't
527distinguish your output from Python's output, and assumes that `>>> '
528at the start of a line is a prompt from Python. Similarly, the Emacs
529Shell mode code assumes that both `>>> ' and `... ' at the start of a
530line are Python prompts. Bad things can happen if you fool either
531mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000532
533Warning: If you do any editing *in* the process buffer *while* the
534buffer is accepting output from Python, do NOT attempt to `undo' the
535changes. Some of the output (nowhere near the parts you changed!) may
536be lost if you do. This appears to be an Emacs bug, an unfortunate
537interaction between undo and process filters; the same problem exists in
538non-Python process buffers using the default (Emacs-supplied) process
539filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000540 ;; BAW - should undo be disabled in the python process buffer, if
541 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542 (interactive)
543 (if py-this-is-emacs-19-p
544 (progn
545 (require 'comint)
546 (switch-to-buffer-other-window
547 (make-comint "Python" py-python-command)))
548 (progn
549 (require 'shell)
550 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000551 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000552 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000553 (make-local-variable 'shell-prompt-pattern)
554 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
555 (set-process-filter (get-buffer-process (current-buffer))
556 'py-process-filter)
557 (set-syntax-table py-mode-syntax-table))
558
559(defun py-execute-region (start end)
560 "Send the region between START and END to a Python interpreter.
561If there is a *Python* process it is used.
562
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000563Hint: If you want to execute part of a Python file several times
564\(e.g., perhaps you're developing a function and want to flesh it out
565a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
566the region of interest, and send the code to a *Python* process via
567`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000568
569Following are subtleties to note when using a *Python* process:
570
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000571If a *Python* process is used, the region is copied into a temporary
572file (in directory `py-temp-directory'), and an `execfile' command is
573sent to Python naming that file. If you send regions faster than
574Python can execute them, `python-mode' will save them into distinct
575temp files, and execute the next one in the queue the next time it
576sees a `>>> ' prompt from Python. Each time this happens, the process
577buffer is popped into a window (if it's not already in some window) so
578you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000579
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000580 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000581
582is inserted at the end.
583
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000584Caution: No more than 26 regions can be pending at any given time.
585This limit is (indirectly) inherited from libc's mktemp(3).
586`python-mode' does not try to protect you from exceeding the limit.
587It's extremely unlikely that you'll get anywhere close to the limit in
588practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000589
590See the `\\[py-shell]' docs for additional warnings."
591 (interactive "r")
592 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000593 (let ((pyproc (get-process "Python"))
594 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000595 (if (null pyproc)
596 (shell-command-on-region start end py-python-command)
597 ;; else feed it thru a temp file
598 (setq fname (py-make-temp-name))
599 (write-region start end fname nil 'no-msg)
600 (setq py-file-queue (append py-file-queue (list fname)))
601 (if (cdr py-file-queue)
602 (message "File %s queued for execution" fname)
603 ;; else
604 (py-execute-file pyproc fname)))))
605
606(defun py-execute-file (pyproc fname)
607 (py-append-to-process-buffer
608 pyproc
609 (format "## working on region in file %s ...\n" fname))
610 (process-send-string pyproc (format "execfile('%s')\n" fname)))
611
612(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000613 (let ((curbuf (current-buffer))
614 (pbuf (process-buffer pyproc))
615 (pmark (process-mark pyproc))
616 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000617
618 ;; make sure we switch to a different buffer at least once. if we
619 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000620 ;; window, and point is before the end, and lots of output is
621 ;; coming at a fast pace, then (a) simple cursor-movement commands
622 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
623 ;; to have a visible effect (the window just doesn't get updated,
624 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
625 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000626 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000627 ;; #b makes no sense to me at all. #a almost makes sense: unless
628 ;; we actually change buffers, set_buffer_internal in buffer.c
629 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
630 ;; seems to make the Emacs command loop reluctant to update the
631 ;; display. Perhaps the default process filter in process.c's
632 ;; read_process_output has update_mode_lines++ for a similar
633 ;; reason? beats me ...
634
635 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000636 (if (eq curbuf pbuf) ; mysterious ugly hack
637 (set-buffer (get-buffer-create "*scratch*")))
638
639 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000640 (let* ((start (point))
641 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000642 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000643 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000644 (goto-char pmark)
645 (insert string)
646 (move-marker pmark (point))
647 (setq file-finished
648 (and py-file-queue
649 (equal ">>> "
650 (buffer-substring
651 (prog2 (beginning-of-line) (point)
652 (goto-char pmark))
653 (point)))))
654 (if goback (goto-char start)
655 ;; else
656 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000657 (let* ((pop-up-windows t)
658 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000659 (set-window-point pwin (point)))))
660 (set-buffer curbuf)
661 (if file-finished
662 (progn
663 (py-delete-file-silently (car py-file-queue))
664 (setq py-file-queue (cdr py-file-queue))
665 (if py-file-queue
666 (py-execute-file pyproc (car py-file-queue)))))
667 (and goend
668 (progn (set-buffer pbuf)
669 (goto-char (point-max))))
670 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000671
672(defun py-execute-buffer ()
673 "Send the contents of the buffer to a Python interpreter.
674If there is a *Python* process buffer it is used. If a clipping
675restriction is in effect, only the accessible portion of the buffer is
676sent. A trailing newline will be supplied if needed.
677
678See the `\\[py-execute-region]' docs for an account of some subtleties."
679 (interactive)
680 (py-execute-region (point-min) (point-max)))
681
682
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000683
684;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000685(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000686 "Reduce indentation or delete character.
687If point is at the leftmost column, deletes the preceding newline.
688
689Else if point is at the leftmost non-blank character of a line that is
690neither a continuation line nor a non-indenting comment line, or if
691point is at the end of a blank line, reduces the indentation to match
692that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000693opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000694of where you are. With numeric count, outdents that many blocks (but
695not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000696
697Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000698needed so that only a single column position is deleted. Numeric
699argument delets that many characters."
700 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000701 (if (or (/= (current-indentation) (current-column))
702 (bolp)
703 (py-continuation-line-p)
704 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000705 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000706 ;; else indent the same as the colon line that opened the block
707
708 ;; force non-blank so py-goto-block-up doesn't ignore it
709 (insert-char ?* 1)
710 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000711 (let ((base-indent 0) ; indentation of base line
712 (base-text "") ; and text of base line
713 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000714 (save-excursion
715 (while (< 0 count)
716 (condition-case nil ; in case no enclosing block
717 (progn
718 (py-goto-block-up 'no-mark)
719 (setq base-indent (current-indentation)
720 base-text (py-suck-up-leading-text)
721 base-found-p t))
722 (error nil))
723 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000724 (delete-char 1) ; toss the dummy character
725 (delete-horizontal-space)
726 (indent-to base-indent)
727 (if base-found-p
728 (message "Closes block: %s" base-text)))))
729
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000730;; required for pending-del and delsel modes
731(put 'py-delete-char 'delete-selection 'supersede)
732(put 'py-delete-char 'pending-delete 'supersede)
733
Barry Warsaw7ae77681994-12-12 20:38:05 +0000734(defun py-indent-line ()
735 "Fix the indentation of the current line according to Python rules."
736 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000737 (let* ((ci (current-indentation))
738 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000739 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000740 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000741 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000742 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000743 (if (/= ci need)
744 (save-excursion
745 (beginning-of-line)
746 (delete-horizontal-space)
747 (indent-to need)))
748 (if move-to-indentation-p (back-to-indentation))))
749
750(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000751 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000752This is just `strives to' because correct indentation can't be computed
753from scratch for Python code. In general, deletes the whitespace before
754point, inserts a newline, and takes an educated guess as to how you want
755the new line indented."
756 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000757 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000758 (if (< ci (current-column)) ; if point beyond indentation
759 (newline-and-indent)
760 ;; else try to act like newline-and-indent "normally" acts
761 (beginning-of-line)
762 (insert-char ?\n 1)
763 (move-to-column ci))))
764
765(defun py-compute-indentation ()
766 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000767 (let ((pps (parse-partial-sexp (save-excursion
768 (beginning-of-python-def-or-class)
769 (point))
770 (point))))
771 (beginning-of-line)
772 (cond
773 ;; are we inside a string or comment?
774 ((or (nth 3 pps) (nth 4 pps))
775 (save-excursion
776 (if (not py-align-multiline-strings-p) 0
777 ;; skip back over blank & non-indenting comment lines
778 ;; note: will skip a blank or non-indenting comment line
779 ;; that happens to be a continuation line too
780 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
781 (back-to-indentation)
782 (current-column))))
783 ;; are we on a continuation line?
784 ((py-continuation-line-p)
785 (let ((startpos (point))
786 (open-bracket-pos (py-nesting-level))
787 endpos searching found)
788 (if open-bracket-pos
789 (progn
790 ;; align with first item in list; else a normal
791 ;; indent beyond the line with the open bracket
792 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
793 ;; is the first list item on the same line?
794 (skip-chars-forward " \t")
795 (if (null (memq (following-char) '(?\n ?# ?\\)))
796 ; yes, so line up with it
797 (current-column)
798 ;; first list item on another line, or doesn't exist yet
799 (forward-line 1)
800 (while (and (< (point) startpos)
801 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
802 (forward-line 1))
803 (if (< (point) startpos)
804 ;; again mimic the first list item
805 (current-indentation)
806 ;; else they're about to enter the first item
807 (goto-char open-bracket-pos)
808 (+ (current-indentation) py-indent-offset))))
809
810 ;; else on backslash continuation line
811 (forward-line -1)
812 (if (py-continuation-line-p) ; on at least 3rd line in block
813 (current-indentation) ; so just continue the pattern
814 ;; else started on 2nd line in block, so indent more.
815 ;; if base line is an assignment with a start on a RHS,
816 ;; indent to 2 beyond the leftmost "="; else skip first
817 ;; chunk of non-whitespace characters on base line, + 1 more
818 ;; column
819 (end-of-line)
820 (setq endpos (point) searching t)
821 (back-to-indentation)
822 (setq startpos (point))
823 ;; look at all "=" from left to right, stopping at first
824 ;; one not nested in a list or string
825 (while searching
826 (skip-chars-forward "^=" endpos)
827 (if (= (point) endpos)
828 (setq searching nil)
829 (forward-char 1)
830 (setq state (parse-partial-sexp startpos (point)))
831 (if (and (zerop (car state)) ; not in a bracket
832 (null (nth 3 state))) ; & not in a string
833 (progn
834 (setq searching nil) ; done searching in any case
835 (setq found
836 (not (or
837 (eq (following-char) ?=)
838 (memq (char-after (- (point) 2))
839 '(?< ?> ?!)))))))))
840 (if (or (not found) ; not an assignment
841 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
842 (progn
843 (goto-char startpos)
844 (skip-chars-forward "^ \t\n")))
845 (1+ (current-column))))))
846
847 ;; not on a continuation line
848
849 ;; if at start of restriction, or on a non-indenting comment
850 ;; line, assume they intended whatever's there
851 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
852 (current-indentation))
853
854 ;; else indentation based on that of the statement that
855 ;; precedes us; use the first line of that statement to
856 ;; establish the base, in case the user forced a non-std
857 ;; indentation for the continuation lines (if any)
858 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000859 ;; skip back over blank & non-indenting comment lines note:
860 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000861 ;; happens to be a continuation line too. use fast Emacs 19
862 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000863 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000864 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000865 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000866 (let (done)
867 (while (not done)
868 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
869 nil 'move)
870 (setq done (or (eq py-honor-comment-indentation t)
871 (bobp)
872 (/= (following-char) ?#)
873 (not (zerop (current-column)))))
874 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000875 ;; if we landed inside a string, go to the beginning of that
876 ;; string. this handles triple quoted, multi-line spanning
877 ;; strings.
878 (py-goto-initial-line)
879 (if (py-statement-opens-block-p)
880 (+ (current-indentation) py-indent-offset)
881 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000882
883(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000884 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000885By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000886`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000888`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000889their own buffer-local copy), both those currently existing and those
890created later in the Emacs session.
891
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000892Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000893There's no excuse for such foolishness, but sometimes you have to deal
894with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000895`py-indent-offset' to what it thinks it was when they created the
896mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000897
898Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000899looking for a line that opens a block of code. `py-indent-offset' is
900set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000901statement following it. If the search doesn't succeed going forward,
902it's tried again going backward."
903 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000904 (let (new-value
905 (start (point))
906 restart
907 (found nil)
908 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000909 (py-goto-initial-line)
910 (while (not (or found (eobp)))
911 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
912 (progn
913 (setq restart (point))
914 (py-goto-initial-line)
915 (if (py-statement-opens-block-p)
916 (setq found t)
917 (goto-char restart)))))
918 (if found
919 ()
920 (goto-char start)
921 (py-goto-initial-line)
922 (while (not (or found (bobp)))
923 (setq found
924 (and
925 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
926 (or (py-goto-initial-line) t) ; always true -- side effect
927 (py-statement-opens-block-p)))))
928 (setq colon-indent (current-indentation)
929 found (and found (zerop (py-next-statement 1)))
930 new-value (- (current-indentation) colon-indent))
931 (goto-char start)
932 (if found
933 (progn
934 (funcall (if global 'kill-local-variable 'make-local-variable)
935 'py-indent-offset)
936 (setq py-indent-offset new-value)
937 (message "%s value of py-indent-offset set to %d"
938 (if global "Global" "Local")
939 py-indent-offset))
940 (error "Sorry, couldn't guess a value for py-indent-offset"))))
941
942(defun py-shift-region (start end count)
943 (save-excursion
944 (goto-char end) (beginning-of-line) (setq end (point))
945 (goto-char start) (beginning-of-line) (setq start (point))
946 (indent-rigidly start end count)))
947
948(defun py-shift-region-left (start end &optional count)
949 "Shift region of Python code to the left.
950The lines from the line containing the start of the current region up
951to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000952shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000953
954If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000955many columns. With no active region, outdent only the current line.
956You cannot outdent the region if any line is already at column zero."
957 (interactive
958 (let ((p (point))
959 (m (mark))
960 (arg current-prefix-arg))
961 (if m
962 (list (min p m) (max p m) arg)
963 (list p (save-excursion (forward-line 1) (point)) arg))))
964 ;; if any line is at column zero, don't shift the region
965 (save-excursion
966 (goto-char start)
967 (while (< (point) end)
968 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +0000969 (if (and (zerop (current-column))
970 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +0000971 (error "Region is at left edge."))
972 (forward-line 1)))
973 (py-shift-region start end (- (prefix-numeric-value
974 (or count py-indent-offset))))
975 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000976
977(defun py-shift-region-right (start end &optional count)
978 "Shift region of Python code to the right.
979The lines from the line containing the start of the current region up
980to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000981shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000982
983If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000984many columns. With no active region, indent only the current line."
985 (interactive
986 (let ((p (point))
987 (m (mark))
988 (arg current-prefix-arg))
989 (if m
990 (list (min p m) (max p m) arg)
991 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000993 (or count py-indent-offset)))
994 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
996(defun py-indent-region (start end &optional indent-offset)
997 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000998
Barry Warsaw7ae77681994-12-12 20:38:05 +0000999The lines from the line containing the start of the current region up
1000to (but not including) the line containing the end of the region are
1001reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001002character in the first column, the first line is left alone and the
1003rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001004region is reindented with respect to the (closest code or indenting
1005comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006
1007This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001008control structures are introduced or removed, or to reformat code
1009using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001010
1011If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013used.
1014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001015Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001016is called! This function does not compute proper indentation from
1017scratch (that's impossible in Python), it merely adjusts the existing
1018indentation to be correct in context.
1019
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001020Warning: This function really has no idea what to do with
1021non-indenting comment lines, and shifts them as if they were indenting
1022comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001024Special cases: whitespace is deleted from blank lines; continuation
1025lines are shifted by the same amount their initial line was shifted,
1026in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001027initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001028 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029 (save-excursion
1030 (goto-char end) (beginning-of-line) (setq end (point-marker))
1031 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001032 (let ((py-indent-offset (prefix-numeric-value
1033 (or indent-offset py-indent-offset)))
1034 (indents '(-1)) ; stack of active indent levels
1035 (target-column 0) ; column to which to indent
1036 (base-shifted-by 0) ; amount last base line was shifted
1037 (indent-base (if (looking-at "[ \t\n]")
1038 (py-compute-indentation)
1039 0))
1040 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041 (while (< (point) end)
1042 (setq ci (current-indentation))
1043 ;; figure out appropriate target column
1044 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001045 ((or (eq (following-char) ?#) ; comment in column 1
1046 (looking-at "[ \t]*$")) ; entirely blank
1047 (setq target-column 0))
1048 ((py-continuation-line-p) ; shift relative to base line
1049 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001050 (t ; new base line
1051 (if (> ci (car indents)) ; going deeper; push it
1052 (setq indents (cons ci indents))
1053 ;; else we should have seen this indent before
1054 (setq indents (memq ci indents)) ; pop deeper indents
1055 (if (null indents)
1056 (error "Bad indentation in region, at line %d"
1057 (save-restriction
1058 (widen)
1059 (1+ (count-lines 1 (point)))))))
1060 (setq target-column (+ indent-base
1061 (* py-indent-offset
1062 (- (length indents) 2))))
1063 (setq base-shifted-by (- target-column ci))))
1064 ;; shift as needed
1065 (if (/= ci target-column)
1066 (progn
1067 (delete-horizontal-space)
1068 (indent-to target-column)))
1069 (forward-line 1))))
1070 (set-marker end nil))
1071
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072
1073;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001074(defun py-previous-statement (count)
1075 "Go to the start of previous Python statement.
1076If the statement at point is the i'th Python statement, goes to the
1077start of statement i-COUNT. If there is no such statement, goes to the
1078first statement. Returns count of statements left to move.
1079`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001081 (if (< count 0) (py-next-statement (- count))
1082 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001086 (> count 0)
1087 (zerop (forward-line -1))
1088 (py-goto-statement-at-or-above))
1089 (setq count (1- count)))
1090 (if (> count 0) (goto-char start)))
1091 count))
1092
1093(defun py-next-statement (count)
1094 "Go to the start of next Python statement.
1095If the statement at point is the i'th Python statement, goes to the
1096start of statement i+COUNT. If there is no such statement, goes to the
1097last statement. Returns count of statements left to move. `Statements'
1098do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001099 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 (if (< count 0) (py-previous-statement (- count))
1101 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001102 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001103 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001104 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001105 (> count 0)
1106 (py-goto-statement-below))
1107 (setq count (1- count)))
1108 (if (> count 0) (goto-char start)))
1109 count))
1110
1111(defun py-goto-block-up (&optional nomark)
1112 "Move up to start of current block.
1113Go to the statement that starts the smallest enclosing block; roughly
1114speaking, this will be the closest preceding statement that ends with a
1115colon and is indented less than the statement you started on. If
1116successful, also sets the mark to the starting point.
1117
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001118`\\[py-mark-block]' can be used afterward to mark the whole code
1119block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001120
1121If called from a program, the mark will not be set if optional argument
1122NOMARK is not nil."
1123 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001124 (let ((start (point))
1125 (found nil)
1126 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001127 (py-goto-initial-line)
1128 ;; if on blank or non-indenting comment line, use the preceding stmt
1129 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1130 (progn
1131 (py-goto-statement-at-or-above)
1132 (setq found (py-statement-opens-block-p))))
1133 ;; search back for colon line indented less
1134 (setq initial-indent (current-indentation))
1135 (if (zerop initial-indent)
1136 ;; force fast exit
1137 (goto-char (point-min)))
1138 (while (not (or found (bobp)))
1139 (setq found
1140 (and
1141 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1142 (or (py-goto-initial-line) t) ; always true -- side effect
1143 (< (current-indentation) initial-indent)
1144 (py-statement-opens-block-p))))
1145 (if found
1146 (progn
1147 (or nomark (push-mark start))
1148 (back-to-indentation))
1149 (goto-char start)
1150 (error "Enclosing block not found"))))
1151
1152(defun beginning-of-python-def-or-class (&optional class)
1153 "Move point to start of def (or class, with prefix arg).
1154
1155Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001156arg, looks for a `class' instead. The docs assume the `def' case;
1157just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001158
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001159If point is in a def statement already, and after the `d', simply
1160moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001161
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001162Else (point is not in a def statement, or at or before the `d' of a
1163def statement), searches for the closest preceding def statement, and
1164leaves point at its start. If no such statement can be found, leaves
1165point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001166
1167Returns t iff a def statement is found by these rules.
1168
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001169Note that doing this command repeatedly will take you closer to the
1170start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001171
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001172If you want to mark the current def/class, see
1173`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001174 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001175 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1176 (start-of-line (progn (beginning-of-line) (point)))
1177 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001178 (if (or (/= start-of-stmt start-of-line)
1179 (not at-or-before-p))
1180 (end-of-line)) ; OK to match on this line
1181 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001182 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001183
1184(defun end-of-python-def-or-class (&optional class)
1185 "Move point beyond end of def (or class, with prefix arg) body.
1186
1187By default, looks for an appropriate `def'. If you supply a prefix arg,
1188looks for a `class' instead. The docs assume the `def' case; just
1189substitute `class' for `def' for the other case.
1190
1191If point is in a def statement already, this is the def we use.
1192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193Else if the def found by `\\[beginning-of-python-def-or-class]'
1194contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001195
1196Else we search forward for the closest following def, and use that.
1197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001198If a def can be found by these rules, point is moved to the start of
1199the line immediately following the def block, and the position of the
1200start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
1202Else point is moved to the end of the buffer, and nil is returned.
1203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001204Note that doing this command repeatedly will take you closer to the
1205end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001206
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001207If you want to mark the current def/class, see
1208`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001209 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001210 (let ((start (progn (py-goto-initial-line) (point)))
1211 (which (if class "class" "def"))
1212 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001213 ;; move point to start of appropriate def/class
1214 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1215 (setq state 'at-beginning)
1216 ;; else see if beginning-of-python-def-or-class hits container
1217 (if (and (beginning-of-python-def-or-class class)
1218 (progn (py-goto-beyond-block)
1219 (> (point) start)))
1220 (setq state 'at-end)
1221 ;; else search forward
1222 (goto-char start)
1223 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1224 (progn (setq state 'at-beginning)
1225 (beginning-of-line)))))
1226 (cond
1227 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1228 ((eq state 'at-end) t)
1229 ((eq state 'not-found) nil)
1230 (t (error "internal error in end-of-python-def-or-class")))))
1231
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001232
1233;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001234(defun py-mark-block (&optional extend just-move)
1235 "Mark following block of lines. With prefix arg, mark structure.
1236Easier to use than explain. It sets the region to an `interesting'
1237block of succeeding lines. If point is on a blank line, it goes down to
1238the next non-blank line. That will be the start of the region. The end
1239of the region depends on the kind of line at the start:
1240
1241 - If a comment, the region will include all succeeding comment lines up
1242 to (but not including) the next non-comment line (if any).
1243
1244 - Else if a prefix arg is given, and the line begins one of these
1245 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001246
1247 if elif else try except finally for while def class
1248
Barry Warsaw7ae77681994-12-12 20:38:05 +00001249 the region will be set to the body of the structure, including
1250 following blocks that `belong' to it, but excluding trailing blank
1251 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001252 and all (if any) of the following `except' and `finally' blocks
1253 that belong to the `try' structure will be in the region. Ditto
1254 for if/elif/else, for/else and while/else structures, and (a bit
1255 degenerate, since they're always one-block structures) def and
1256 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001257
1258 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001259 block (see list above), and the block is not a `one-liner' (i.e.,
1260 the statement ends with a colon, not with code), the region will
1261 include all succeeding lines up to (but not including) the next
1262 code statement (if any) that's indented no more than the starting
1263 line, except that trailing blank and comment lines are excluded.
1264 E.g., if the starting line begins a multi-statement `def'
1265 structure, the region will be set to the full function definition,
1266 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001267
1268 - Else the region will include all succeeding lines up to (but not
1269 including) the next blank line, or code or indenting-comment line
1270 indented strictly less than the starting line. Trailing indenting
1271 comment lines are included in this case, but not trailing blank
1272 lines.
1273
1274A msg identifying the location of the mark is displayed in the echo
1275area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1276
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001277If called from a program, optional argument EXTEND plays the role of
1278the prefix arg, and if optional argument JUST-MOVE is not nil, just
1279moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280 (interactive "P") ; raw prefix arg
1281 (py-goto-initial-line)
1282 ;; skip over blank lines
1283 (while (and
1284 (looking-at "[ \t]*$") ; while blank line
1285 (not (eobp))) ; & somewhere to go
1286 (forward-line 1))
1287 (if (eobp)
1288 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001289 (let ((initial-pos (point))
1290 (initial-indent (current-indentation))
1291 last-pos ; position of last stmt in region
1292 (followers
1293 '((if elif else) (elif elif else) (else)
1294 (try except finally) (except except) (finally)
1295 (for else) (while else)
1296 (def) (class) ) )
1297 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001298
1299 (cond
1300 ;; if comment line, suck up the following comment lines
1301 ((looking-at "[ \t]*#")
1302 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1303 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1304 (setq last-pos (point)))
1305
1306 ;; else if line is a block line and EXTEND given, suck up
1307 ;; the whole structure
1308 ((and extend
1309 (setq first-symbol (py-suck-up-first-keyword) )
1310 (assq first-symbol followers))
1311 (while (and
1312 (or (py-goto-beyond-block) t) ; side effect
1313 (forward-line -1) ; side effect
1314 (setq last-pos (point)) ; side effect
1315 (py-goto-statement-below)
1316 (= (current-indentation) initial-indent)
1317 (setq next-symbol (py-suck-up-first-keyword))
1318 (memq next-symbol (cdr (assq first-symbol followers))))
1319 (setq first-symbol next-symbol)))
1320
1321 ;; else if line *opens* a block, search for next stmt indented <=
1322 ((py-statement-opens-block-p)
1323 (while (and
1324 (setq last-pos (point)) ; always true -- side effect
1325 (py-goto-statement-below)
1326 (> (current-indentation) initial-indent))
1327 nil))
1328
1329 ;; else plain code line; stop at next blank line, or stmt or
1330 ;; indenting comment line indented <
1331 (t
1332 (while (and
1333 (setq last-pos (point)) ; always true -- side effect
1334 (or (py-goto-beyond-final-line) t)
1335 (not (looking-at "[ \t]*$")) ; stop at blank line
1336 (or
1337 (>= (current-indentation) initial-indent)
1338 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1339 nil)))
1340
1341 ;; skip to end of last stmt
1342 (goto-char last-pos)
1343 (py-goto-beyond-final-line)
1344
1345 ;; set mark & display
1346 (if just-move
1347 () ; just return
1348 (push-mark (point) 'no-msg)
1349 (forward-line -1)
1350 (message "Mark set after: %s" (py-suck-up-leading-text))
1351 (goto-char initial-pos))))
1352
1353(defun mark-python-def-or-class (&optional class)
1354 "Set region to body of def (or class, with prefix arg) enclosing point.
1355Pushes the current mark, then point, on the mark ring (all language
1356modes do this, but although it's handy it's never documented ...).
1357
1358In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1360`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361
1362And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363Turned out that was more confusing than useful: the `goto start' and
1364`goto end' commands are usually used to search through a file, and
1365people expect them to act a lot like `search backward' and `search
1366forward' string-search commands. But because Python `def' and `class'
1367can nest to arbitrary levels, finding the smallest def containing
1368point cannot be done via a simple backward search: the def containing
1369point may not be the closest preceding def, or even the closest
1370preceding def that's indented less. The fancy algorithm required is
1371appropriate for the usual uses of this `mark' command, but not for the
1372`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001373
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001374So the def marked by this command may not be the one either of the
1375`goto' commands find: If point is on a blank or non-indenting comment
1376line, moves back to start of the closest preceding code statement or
1377indenting comment line. If this is a `def' statement, that's the def
1378we use. Else searches for the smallest enclosing `def' block and uses
1379that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001381When an enclosing def is found: The mark is left immediately beyond
1382the last line of the def block. Point is left at the start of the
1383def, except that: if the def is preceded by a number of comment lines
1384followed by (at most) one optional blank line, point is left at the
1385start of the comments; else if the def is preceded by a blank line,
1386point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001387
1388The intent is to mark the containing def/class and its associated
1389documentation, to make moving and duplicating functions and classes
1390pleasant."
1391 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001392 (let ((start (point))
1393 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001394 (push-mark start)
1395 (if (not (py-go-up-tree-to-keyword which))
1396 (progn (goto-char start)
1397 (error "Enclosing %s not found" which))
1398 ;; else enclosing def/class found
1399 (setq start (point))
1400 (py-goto-beyond-block)
1401 (push-mark (point))
1402 (goto-char start)
1403 (if (zerop (forward-line -1)) ; if there is a preceding line
1404 (progn
1405 (if (looking-at "[ \t]*$") ; it's blank
1406 (setq start (point)) ; so reset start point
1407 (goto-char start)) ; else try again
1408 (if (zerop (forward-line -1))
1409 (if (looking-at "[ \t]*#") ; a comment
1410 ;; look back for non-comment line
1411 ;; tricky: note that the regexp matches a blank
1412 ;; line, cuz \n is in the 2nd character class
1413 (and
1414 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1415 (forward-line 1))
1416 ;; no comment, so go back
1417 (goto-char start))))))))
1418
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001419;; ripped from cc-mode
1420(defun py-forward-into-nomenclature (&optional arg)
1421 "Move forward to end of a nomenclature section or word.
1422With arg, to it arg times.
1423
1424A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1425 (interactive "p")
1426 (let ((case-fold-search nil))
1427 (if (> arg 0)
Barry Warsawc846f461996-07-25 18:53:17 +00001428 (re-search-forward "\\W*\\([A-Z_]*[a-z0-9]*\\)" (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00001429 (while (and (< arg 0)
1430 (re-search-backward
1431 "\\(\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\W\\w+\\)"
1432 (point-min) 0))
1433 (forward-char 1)
1434 (setq arg (1+ arg)))))
1435 (py-keep-region-active))
1436
1437(defun py-backward-into-nomenclature (&optional arg)
1438 "Move backward to beginning of a nomenclature section or word.
1439With optional ARG, move that many times. If ARG is negative, move
1440forward.
1441
1442A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
1443 (interactive "p")
1444 (py-forward-into-nomenclature (- arg))
1445 (py-keep-region-active))
1446
1447
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001448
1449;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001450
1451;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001452;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1453;; out of the right places, along with the keys they're on & current
1454;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455(defun py-dump-help-string (str)
1456 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001457 (let ((locals (buffer-local-variables))
1458 funckind funcname func funcdoc
1459 (start 0) mstart end
1460 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1462 (setq mstart (match-beginning 0) end (match-end 0)
1463 funckind (substring str (match-beginning 1) (match-end 1))
1464 funcname (substring str (match-beginning 2) (match-end 2))
1465 func (intern funcname))
1466 (princ (substitute-command-keys (substring str start mstart)))
1467 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001468 ((equal funckind "c") ; command
1469 (setq funcdoc (documentation func)
1470 keys (concat
1471 "Key(s): "
1472 (mapconcat 'key-description
1473 (where-is-internal func py-mode-map)
1474 ", "))))
1475 ((equal funckind "v") ; variable
1476 (setq funcdoc (substitute-command-keys
1477 (get func 'variable-documentation))
1478 keys (if (assq func locals)
1479 (concat
1480 "Local/Global values: "
1481 (prin1-to-string (symbol-value func))
1482 " / "
1483 (prin1-to-string (default-value func)))
1484 (concat
1485 "Value: "
1486 (prin1-to-string (symbol-value func))))))
1487 (t ; unexpected
1488 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001489 (princ (format "\n-> %s:\t%s\t%s\n\n"
1490 (if (equal funckind "c") "Command" "Variable")
1491 funcname keys))
1492 (princ funcdoc)
1493 (terpri)
1494 (setq start end))
1495 (princ (substitute-command-keys (substring str start))))
1496 (print-help-return-message)))
1497
1498(defun py-describe-mode ()
1499 "Dump long form of Python-mode docs."
1500 (interactive)
1501 (py-dump-help-string "Major mode for editing Python files.
1502Knows about Python indentation, tokens, comments and continuation lines.
1503Paragraphs are separated by blank lines only.
1504
1505Major sections below begin with the string `@'; specific function and
1506variable docs begin with `->'.
1507
1508@EXECUTING PYTHON CODE
1509
1510\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1511\\[py-execute-region]\tsends the current region
1512\\[py-shell]\tstarts a Python interpreter window; this will be used by
1513\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1514%c:py-execute-buffer
1515%c:py-execute-region
1516%c:py-shell
1517
1518@VARIABLES
1519
1520py-indent-offset\tindentation increment
1521py-block-comment-prefix\tcomment string used by py-comment-region
1522
1523py-python-command\tshell command to invoke Python interpreter
1524py-scroll-process-buffer\talways scroll Python process buffer
1525py-temp-directory\tdirectory used for temp files (if needed)
1526
1527py-beep-if-tab-change\tring the bell if tab-width is changed
1528%v:py-indent-offset
1529%v:py-block-comment-prefix
1530%v:py-python-command
1531%v:py-scroll-process-buffer
1532%v:py-temp-directory
1533%v:py-beep-if-tab-change
1534
1535@KINDS OF LINES
1536
1537Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001538preceding line ends with a backslash that's not part of a comment, or
1539the paren/bracket/brace nesting level at the start of the line is
1540non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001541
1542An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001543possibly blanks or tabs), a `comment line' (leftmost non-blank
1544character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
1546Comment Lines
1547
1548Although all comment lines are treated alike by Python, Python mode
1549recognizes two kinds that act differently with respect to indentation.
1550
1551An `indenting comment line' is a comment line with a blank, tab or
1552nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001553treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001554indenting comment line will be indented like the comment line. All
1555other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001556following the initial `#') are `non-indenting comment lines', and
1557their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001558
1559Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560whenever possible. Non-indenting comment lines are useful in cases
1561like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001562
1563\ta = b # a very wordy single-line comment that ends up being
1564\t #... continued onto another line
1565
1566\tif a == b:
1567##\t\tprint 'panic!' # old code we've `commented out'
1568\t\treturn a
1569
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570Since the `#...' and `##' comment lines have a non-whitespace
1571character following the initial `#', Python mode ignores them when
1572computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573
1574Continuation Lines and Statements
1575
1576The Python-mode commands generally work on statements instead of on
1577individual lines, where a `statement' is a comment or blank line, or a
1578code line and all of its following continuation lines (if any)
1579considered as a single logical unit. The commands in this mode
1580generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001581statement containing point, even if point happens to be in the middle
1582of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001583
1584
1585@INDENTATION
1586
1587Primarily for entering new code:
1588\t\\[indent-for-tab-command]\t indent line appropriately
1589\t\\[py-newline-and-indent]\t insert newline, then indent
1590\t\\[py-delete-char]\t reduce indentation, or delete single character
1591
1592Primarily for reindenting existing code:
1593\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1594\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1595
1596\t\\[py-indent-region]\t reindent region to match its context
1597\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1598\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1599
1600Unlike most programming languages, Python uses indentation, and only
1601indentation, to specify block structure. Hence the indentation supplied
1602automatically by Python-mode is just an educated guess: only you know
1603the block structure you intend, so only you can supply correct
1604indentation.
1605
1606The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1607the indentation of preceding statements. E.g., assuming
1608py-indent-offset is 4, after you enter
1609\tif a > 0: \\[py-newline-and-indent]
1610the cursor will be moved to the position of the `_' (_ is not a
1611character in the file, it's just used here to indicate the location of
1612the cursor):
1613\tif a > 0:
1614\t _
1615If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1616to
1617\tif a > 0:
1618\t c = d
1619\t _
1620Python-mode cannot know whether that's what you intended, or whether
1621\tif a > 0:
1622\t c = d
1623\t_
1624was your intent. In general, Python-mode either reproduces the
1625indentation of the (closest code or indenting-comment) preceding
1626statement, or adds an extra py-indent-offset blanks if the preceding
1627statement has `:' as its last significant (non-whitespace and non-
1628comment) character. If the suggested indentation is too much, use
1629\\[py-delete-char] to reduce it.
1630
1631Continuation lines are given extra indentation. If you don't like the
1632suggested indentation, change it to something you do like, and Python-
1633mode will strive to indent later lines of the statement in the same way.
1634
1635If a line is a continuation line by virtue of being in an unclosed
1636paren/bracket/brace structure (`list', for short), the suggested
1637indentation depends on whether the current line contains the first item
1638in the list. If it does, it's indented py-indent-offset columns beyond
1639the indentation of the line containing the open bracket. If you don't
1640like that, change it by hand. The remaining items in the list will mimic
1641whatever indentation you give to the first item.
1642
1643If a line is a continuation line because the line preceding it ends with
1644a backslash, the third and following lines of the statement inherit their
1645indentation from the line preceding them. The indentation of the second
1646line in the statement depends on the form of the first (base) line: if
1647the base line is an assignment statement with anything more interesting
1648than the backslash following the leftmost assigning `=', the second line
1649is indented two columns beyond that `='. Else it's indented to two
1650columns beyond the leftmost solid chunk of non-whitespace characters on
1651the base line.
1652
1653Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1654repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1655structure you intend.
1656%c:indent-for-tab-command
1657%c:py-newline-and-indent
1658%c:py-delete-char
1659
1660
1661The next function may be handy when editing code you didn't write:
1662%c:py-guess-indent-offset
1663
1664
1665The remaining `indent' functions apply to a region of Python code. They
1666assume the block structure (equals indentation, in Python) of the region
1667is correct, and alter the indentation in various ways while preserving
1668the block structure:
1669%c:py-indent-region
1670%c:py-shift-region-left
1671%c:py-shift-region-right
1672
1673@MARKING & MANIPULATING REGIONS OF CODE
1674
1675\\[py-mark-block]\t mark block of lines
1676\\[mark-python-def-or-class]\t mark smallest enclosing def
1677\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1678\\[py-comment-region]\t comment out region of code
1679\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1680%c:py-mark-block
1681%c:mark-python-def-or-class
1682%c:py-comment-region
1683
1684@MOVING POINT
1685
1686\\[py-previous-statement]\t move to statement preceding point
1687\\[py-next-statement]\t move to statement following point
1688\\[py-goto-block-up]\t move up to start of current block
1689\\[beginning-of-python-def-or-class]\t move to start of def
1690\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1691\\[end-of-python-def-or-class]\t move to end of def
1692\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1693
1694The first two move to one statement beyond the statement that contains
1695point. A numeric prefix argument tells them to move that many
1696statements instead. Blank lines, comment lines, and continuation lines
1697do not count as `statements' for these commands. So, e.g., you can go
1698to the first code statement in a file by entering
1699\t\\[beginning-of-buffer]\t to move to the top of the file
1700\t\\[py-next-statement]\t to skip over initial comments and blank lines
1701Or do `\\[py-previous-statement]' with a huge prefix argument.
1702%c:py-previous-statement
1703%c:py-next-statement
1704%c:py-goto-block-up
1705%c:beginning-of-python-def-or-class
1706%c:end-of-python-def-or-class
1707
1708@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1709
1710`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1711
1712`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1713overall class and def structure of a module.
1714
1715`\\[back-to-indentation]' moves point to a line's first non-blank character.
1716
1717`\\[indent-relative]' is handy for creating odd indentation.
1718
1719@OTHER EMACS HINTS
1720
1721If you don't like the default value of a variable, change its value to
1722whatever you do like by putting a `setq' line in your .emacs file.
1723E.g., to set the indentation increment to 4, put this line in your
1724.emacs:
1725\t(setq py-indent-offset 4)
1726To see the value of a variable, do `\\[describe-variable]' and enter the variable
1727name at the prompt.
1728
1729When entering a key sequence like `C-c C-n', it is not necessary to
1730release the CONTROL key after doing the `C-c' part -- it suffices to
1731press the CONTROL key, press and release `c' (while still holding down
1732CONTROL), press and release `n' (while still holding down CONTROL), &
1733then release CONTROL.
1734
1735Entering Python mode calls with no arguments the value of the variable
1736`python-mode-hook', if that value exists and is not nil; for backward
1737compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1738the Elisp manual for details.
1739
1740Obscure: When python-mode is first loaded, it looks for all bindings
1741to newline-and-indent in the global keymap, and shadows them with
1742local bindings to py-newline-and-indent."))
1743
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001744
1745;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746(defvar py-parse-state-re
1747 (concat
1748 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1749 "\\|"
1750 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752;; returns the parse state at point (see parse-partial-sexp docs)
1753(defun py-parse-state ()
1754 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001755 (let ((here (point))
1756 pps done)
1757 (while (not done)
1758 ;; back up to the first preceding line (if any; else start of
1759 ;; buffer) that begins with a popular Python keyword, or a
1760 ;; non- whitespace and non-comment character. These are good
1761 ;; places to start parsing to see whether where we started is
1762 ;; at a non-zero nesting level. It may be slow for people who
1763 ;; write huge code blocks or huge lists ... tough beans.
1764 (re-search-backward py-parse-state-re nil 'move)
1765 (beginning-of-line)
1766 (save-excursion
1767 (setq pps (parse-partial-sexp (point) here)))
1768 ;; make sure we don't land inside a triple-quoted string
1769 (setq done (or (not (nth 3 pps)) (bobp))))
1770 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771
1772;; if point is at a non-zero nesting level, returns the number of the
1773;; character that opens the smallest enclosing unclosed list; else
1774;; returns nil.
1775(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001776 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001777 (if (zerop (car status))
1778 nil ; not in a nest
1779 (car (cdr status))))) ; char# of open bracket
1780
1781;; t iff preceding line ends with backslash that's not in a comment
1782(defun py-backslash-continuation-line-p ()
1783 (save-excursion
1784 (beginning-of-line)
1785 (and
1786 ;; use a cheap test first to avoid the regexp if possible
1787 ;; use 'eq' because char-after may return nil
1788 (eq (char-after (- (point) 2)) ?\\ )
1789 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001790 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791 (looking-at py-continued-re))))
1792
1793;; t iff current line is a continuation line
1794(defun py-continuation-line-p ()
1795 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001796 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797 (or (py-backslash-continuation-line-p)
1798 (py-nesting-level))))
1799
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800;; go to initial line of current statement; usually this is the line
1801;; we're on, but if we're on the 2nd or following lines of a
1802;; continuation block, we need to go up to the first line of the
1803;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001804;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001805;; Tricky: We want to avoid quadratic-time behavior for long continued
1806;; blocks, whether of the backslash or open-bracket varieties, or a
1807;; mix of the two. The following manages to do that in the usual
1808;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001809(defun py-goto-initial-line ()
1810 (let ( open-bracket-pos )
1811 (while (py-continuation-line-p)
1812 (beginning-of-line)
1813 (if (py-backslash-continuation-line-p)
1814 (while (py-backslash-continuation-line-p)
1815 (forward-line -1))
1816 ;; else zip out of nested brackets/braces/parens
1817 (while (setq open-bracket-pos (py-nesting-level))
1818 (goto-char open-bracket-pos)))))
1819 (beginning-of-line))
1820
1821;; go to point right beyond final line of current statement; usually
1822;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001823;; statement we need to skip over the continuation lines. Tricky:
1824;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001825(defun py-goto-beyond-final-line ()
1826 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828 (while (and (py-continuation-line-p)
1829 (not (eobp)))
1830 ;; skip over the backslash flavor
1831 (while (and (py-backslash-continuation-line-p)
1832 (not (eobp)))
1833 (forward-line 1))
1834 ;; if in nest, zip to the end of the nest
1835 (setq state (py-parse-state))
1836 (if (and (not (zerop (car state)))
1837 (not (eobp)))
1838 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001839 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840 ;; the 3rd argument should be plain 0
1841 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1842 nil state)
1843 (forward-line 1))))))
1844
1845;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001847(defun py-statement-opens-block-p ()
1848 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849 (let ((start (point))
1850 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1851 (searching t)
1852 (answer nil)
1853 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854 (goto-char start)
1855 (while searching
1856 ;; look for a colon with nothing after it except whitespace, and
1857 ;; maybe a comment
1858 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1859 finish t)
1860 (if (eq (point) finish) ; note: no `else' clause; just
1861 ; keep searching if we're not at
1862 ; the end yet
1863 ;; sure looks like it opens a block -- but it might
1864 ;; be in a comment
1865 (progn
1866 (setq searching nil) ; search is done either way
1867 (setq state (parse-partial-sexp start
1868 (match-beginning 0)))
1869 (setq answer (not (nth 4 state)))))
1870 ;; search failed: couldn't find another interesting colon
1871 (setq searching nil)))
1872 answer)))
1873
1874;; go to point right beyond final line of block begun by the current
1875;; line. This is the same as where py-goto-beyond-final-line goes
1876;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878(defun py-goto-beyond-block ()
1879 (if (py-statement-opens-block-p)
1880 (py-mark-block nil 'just-move)
1881 (py-goto-beyond-final-line)))
1882
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001883;; go to start of first statement (not blank or comment or
1884;; continuation line) at or preceding point. returns t if there is
1885;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001886(defun py-goto-statement-at-or-above ()
1887 (py-goto-initial-line)
1888 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001889 ;; skip back over blank & comment lines
1890 ;; note: will skip a blank or comment line that happens to be
1891 ;; a continuation line too
1892 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1893 (progn (py-goto-initial-line) t)
1894 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895 t))
1896
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897;; go to start of first statement (not blank or comment or
1898;; continuation line) following the statement containing point returns
1899;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001900(defun py-goto-statement-below ()
1901 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001902 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001903 (py-goto-beyond-final-line)
1904 (while (and
1905 (looking-at py-blank-or-comment-re)
1906 (not (eobp)))
1907 (forward-line 1))
1908 (if (eobp)
1909 (progn (goto-char start) nil)
1910 t)))
1911
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001912;; go to start of statement, at or preceding point, starting with
1913;; keyword KEY. Skips blank lines and non-indenting comments upward
1914;; first. If that statement starts with KEY, done, else go back to
1915;; first enclosing block starting with KEY. If successful, leaves
1916;; point at the start of the KEY line & returns t. Else leaves point
1917;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918(defun py-go-up-tree-to-keyword (key)
1919 ;; skip blanks and non-indenting #
1920 (py-goto-initial-line)
1921 (while (and
1922 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1923 (zerop (forward-line -1))) ; go back
1924 nil)
1925 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001926 (let* ((re (concat "[ \t]*" key "\\b"))
1927 (case-fold-search nil) ; let* so looking-at sees this
1928 (found (looking-at re))
1929 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930 (while (not (or found dead))
1931 (condition-case nil ; in case no enclosing block
1932 (py-goto-block-up 'no-mark)
1933 (error (setq dead t)))
1934 (or dead (setq found (looking-at re))))
1935 (beginning-of-line)
1936 found))
1937
1938;; return string in buffer from start of indentation to end of line;
1939;; prefix "..." if leading whitespace was skipped
1940(defun py-suck-up-leading-text ()
1941 (save-excursion
1942 (back-to-indentation)
1943 (concat
1944 (if (bolp) "" "...")
1945 (buffer-substring (point) (progn (end-of-line) (point))))))
1946
1947;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1948;; as a Lisp symbol; return nil if none
1949(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1952 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1953 nil)))
1954
1955(defun py-make-temp-name ()
1956 (make-temp-name
1957 (concat (file-name-as-directory py-temp-directory) "python")))
1958
1959(defun py-delete-file-silently (fname)
1960 (condition-case nil
1961 (delete-file fname)
1962 (error nil)))
1963
1964(defun py-kill-emacs-hook ()
1965 ;; delete our temp files
1966 (while py-file-queue
1967 (py-delete-file-silently (car py-file-queue))
1968 (setq py-file-queue (cdr py-file-queue)))
1969 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1970 ;; run the hook we inherited, if any
1971 (and py-inherited-kill-emacs-hook
1972 (funcall py-inherited-kill-emacs-hook))))
1973
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974;; make PROCESS's buffer visible, append STRING to it, and force
1975;; display; also make shell-mode believe the user typed this string,
1976;; so that kill-output-from-shell and show-output-from-shell work
1977;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001978(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001979 (let ((cbuf (current-buffer))
1980 (pbuf (process-buffer process))
1981 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001982 (set-buffer pbuf)
1983 (goto-char (point-max))
1984 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001985 (if (not (or py-this-is-emacs-19-p
1986 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001987 (move-marker last-input-start (point))) ; muck w/ shell-mode
1988 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001989 (if (not (or py-this-is-emacs-19-p
1990 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991 (move-marker last-input-end (point))) ; muck w/ shell-mode
1992 (set-buffer cbuf))
1993 (sit-for 0))
1994
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001995(defun py-keep-region-active ()
1996 ;; do whatever is necessary to keep the region active in XEmacs.
1997 ;; Ignore byte-compiler warnings you might see. Also note that
1998 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1999 ;; require us to take explicit action.
2000 (and (boundp 'zmacs-region-stays)
2001 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002
2003
Barry Warsaw850437a1995-03-08 21:50:28 +00002004(defconst py-version "$Revision$"
2005 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00002006(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002007 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002008
Barry Warsaw850437a1995-03-08 21:50:28 +00002009(defun py-version ()
2010 "Echo the current version of `python-mode' in the minibuffer."
2011 (interactive)
2012 (message "Using `python-mode' version %s" py-version)
2013 (py-keep-region-active))
2014
2015;; only works under Emacs 19
2016;(eval-when-compile
2017; (require 'reporter))
2018
2019(defun py-submit-bug-report (enhancement-p)
2020 "Submit via mail a bug report on `python-mode'.
2021With \\[universal-argument] just submit an enhancement request."
2022 (interactive
2023 (list (not (y-or-n-p
2024 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002025 (let ((reporter-prompt-for-summary-p (if enhancement-p
2026 "(Very) brief summary: "
2027 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002028 (require 'reporter)
2029 (reporter-submit-bug-report
2030 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002031 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002032 ;; varlist
2033 (if enhancement-p nil
2034 '(py-python-command
2035 py-indent-offset
2036 py-block-comment-prefix
2037 py-scroll-process-buffer
2038 py-temp-directory
2039 py-beep-if-tab-change))
2040 nil ;pre-hooks
2041 nil ;post-hooks
2042 "Dear Barry,") ;salutation
2043 (if enhancement-p nil
2044 (set-mark (point))
2045 (insert
2046"Please replace this text with a sufficiently large code sample\n\
2047and an exact recipe so that I can reproduce your problem. Failure\n\
2048to do so may mean a greater delay in fixing your bug.\n\n")
2049 (exchange-point-and-mark)
2050 (py-keep-region-active))))
2051
2052
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002053;; arrange to kill temp files when Emacs exists
2054(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2055 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2056 ;; have to trust that other people are as respectful of our hook
2057 ;; fiddling as we are of theirs
2058 (if (boundp 'py-inherited-kill-emacs-hook)
2059 ;; we were loaded before -- trust others not to have screwed us
2060 ;; in the meantime (no choice, really)
2061 nil
2062 ;; else arrange for our hook to run theirs
2063 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2064 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2065
2066
2067
2068(provide 'python-mode)
2069;;; python-mode.el ends here