blob: 96600c4bf4f0eb888eef1d09c4dbed7c096c5881 [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 Warsawb5e0ecb1995-03-14 18:32:54 +000060
Barry Warsaw7b0f5681995-03-08 21:33:04 +000061;; Here's a brief to do list:
62;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000063;; - Better integration with gud-mode for debugging.
64;; - Rewrite according to GNU Emacs Lisp standards.
65;; - py-delete-char should obey numeric arguments.
66;; - even better support for outdenting. Guido suggests outdents of
67;; at least one level after a return, raise, break, or continue
68;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000069;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000070
Barry Warsaw7b0f5681995-03-08 21:33:04 +000071;; If you can think of more things you'd like to see, drop me a line.
72;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
73;;
Barry Warsaw4669d7e1996-03-22 16:13:24 +000074;; Note that I only test things on XEmacs. If you port stuff to FSF
75;; Emacs 19, or Emacs 18, please send me your patches. Byte compiler
76;; complaints can probably be safely ignored.
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsaw7b0f5681995-03-08 21:33:04 +000078;; LCD Archive Entry:
Barry Warsawfec75d61995-07-05 23:26:15 +000079;; python-mode|Barry A. Warsaw|python-mode@python.org
Barry Warsaw7b0f5681995-03-08 21:33:04 +000080;; |Major mode for editing Python programs
81;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000082
Barry Warsaw7b0f5681995-03-08 21:33:04 +000083;;; Code:
84
85
86;; user definable variables
87;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000088
89(defvar py-python-command "python"
90 "*Shell command used to start Python interpreter.")
91
Barry Warsaw17914f41995-11-03 18:25:15 +000092(defvar py-indent-offset 4
Barry Warsaw7ae77681994-12-12 20:38:05 +000093 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000094Note that `\\[py-guess-indent-offset]' can usually guess a good value
95when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000096
Barry Warsaw095e9c61995-09-19 20:01:42 +000097(defvar py-align-multiline-strings-p t
98 "*Flag describing how multiline triple quoted strings are aligned.
99When this flag is non-nil, continuation lines are lined up under the
100preceding line's indentation. When this flag is nil, continuation
101lines are aligned to column zero.")
102
Barry Warsaw7ae77681994-12-12 20:38:05 +0000103(defvar py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000104 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105This should follow the convention for non-indenting comment lines so
106that the indentation commands won't get confused (i.e., the string
107should be of the form `#x...' where `x' is not a blank or a tab, and
108`...' is arbitrary).")
109
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000110(defvar py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000111 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000112
Barry Warsaw6d627751996-03-06 18:41:38 +0000113When nil, all comment lines are skipped for indentation purposes, and
114in Emacs 19, a faster algorithm is used.
115
116When t, lines that begin with a single `#' are a hint to subsequent
117line indentation. If the previous line is such a comment line (as
118opposed to one that starts with `py-block-comment-prefix'), then it's
119indentation is used as a hint for this line's indentation. Lines that
120begin with `py-block-comment-prefix' are ignored for indentation
121purposes.
122
123When not nil or t, comment lines that begin with a `#' are used as
124indentation hints, unless the comment character is in column zero.")
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000125
Barry Warsaw7ae77681994-12-12 20:38:05 +0000126(defvar py-scroll-process-buffer t
127 "*Scroll Python process buffer as output arrives.
128If nil, the Python process buffer acts, with respect to scrolling, like
129Shell-mode buffers normally act. This is surprisingly complicated and
130so won't be explained here; in fact, you can't get the whole story
131without studying the Emacs C code.
132
133If non-nil, the behavior is different in two respects (which are
134slightly inaccurate in the interest of brevity):
135
136 - If the buffer is in a window, and you left point at its end, the
137 window will scroll as new output arrives, and point will move to the
138 buffer's end, even if the window is not the selected window (that
139 being the one the cursor is in). The usual behavior for shell-mode
140 windows is not to scroll, and to leave point where it was, if the
141 buffer is in a window other than the selected window.
142
143 - If the buffer is not visible in any window, and you left point at
144 its end, the buffer will be popped into a window as soon as more
145 output arrives. This is handy if you have a long-running
146 computation and don't want to tie up screen area waiting for the
147 output. The usual behavior for a shell-mode buffer is to stay
148 invisible until you explicitly visit it.
149
150Note the `and if you left point at its end' clauses in both of the
151above: you can `turn off' the special behaviors while output is in
152progress, by visiting the Python buffer and moving point to anywhere
153besides the end. Then the buffer won't scroll, point will remain where
154you leave it, and if you hide the buffer it will stay hidden until you
155visit it again. You can enable and disable the special behaviors as
156often as you like, while output is in progress, by (respectively) moving
157point to, or away from, the end of the buffer.
158
159Warning: If you expect a large amount of output, you'll probably be
160happier setting this option to nil.
161
162Obscure: `End of buffer' above should really say `at or beyond the
163process mark', but if you know what that means you didn't need to be
164told <grin>.")
165
166(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000167 (let ((ok '(lambda (x)
168 (and x
169 (setq x (expand-file-name x)) ; always true
170 (file-directory-p x)
171 (file-writable-p x)
172 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000173 (or (funcall ok (getenv "TMPDIR"))
174 (funcall ok "/usr/tmp")
175 (funcall ok "/tmp")
176 (funcall ok ".")
177 (error
178 "Couldn't find a usable temp directory -- set py-temp-directory")))
179 "*Directory used for temp files created by a *Python* process.
180By default, the first directory from this list that exists and that you
181can write into: the value (if any) of the environment variable TMPDIR,
182/usr/tmp, /tmp, or the current directory.")
183
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000184(defvar py-beep-if-tab-change t
185 "*Ring the bell if tab-width is changed.
186If a comment of the form
187
188 \t# vi:set tabsize=<number>:
189
190is found before the first code line when the file is entered, and the
191current value of (the general Emacs variable) `tab-width' does not
192equal <number>, `tab-width' is set to <number>, a message saying so is
193displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
194the Emacs bell is also rung as a warning.")
195
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000196(defconst python-font-lock-keywords
Barry Warsaw44b72201996-07-05 20:11:35 +0000197 (let* ((keywords '("access" "and" "break" "class"
198 "continue" "def" "del" "elif"
199 "else:" "except" "except:" "exec"
200 "finally:" "for" "from" "global"
201 "if" "import" "in" "is"
202 "lambda" "not" "or" "pass"
203 "print" "raise" "return" "try:"
204 "while"
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000205 ))
206 (kwregex (mapconcat 'identity keywords "\\|")))
207 (list
208 ;; keywords not at beginning of line
209 (cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
210 ;; keywords at beginning of line. i don't think regexps are
211 ;; powerful enough to handle these two cases in one regexp.
212 ;; prove me wrong!
213 (cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
214 ;; classes
215 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
216 1 font-lock-type-face)
217 ;; functions
218 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
219 1 font-lock-function-name-face)
220 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000221 "Additional expressions to highlight in Python mode.")
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000222
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000223
224;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
225;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
226
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000227(make-variable-buffer-local 'py-indent-offset)
228
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000229;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
230;; seems to be the standard way of checking this.
231;; BAW - This is *not* the right solution. When at all possible,
232;; instead of testing for the version of Emacs, use feature tests.
233
234(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
235(setq py-this-is-emacs-19-p
236 (and
237 (not py-this-is-lucid-emacs-p)
238 (string-match "^19\\." emacs-version)))
239
Barry Warsaw7ae77681994-12-12 20:38:05 +0000240;; have to bind py-file-queue before installing the kill-emacs hook
241(defvar py-file-queue nil
242 "Queue of Python temp files awaiting execution.
243Currently-active file is at the head of the list.")
244
245;; define a mode-specific abbrev table for those who use such things
246(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000247 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000248(define-abbrev-table 'python-mode-abbrev-table nil)
249
Barry Warsaw7ae77681994-12-12 20:38:05 +0000250(defvar python-mode-hook nil
251 "*Hook called by `python-mode'.")
252
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000253;; in previous version of python-mode.el, the hook was incorrectly
254;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000255(and (fboundp 'make-obsolete-variable)
256 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
257
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000258(defvar py-mode-map ()
259 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000260
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261(if py-mode-map
262 ()
263 (setq py-mode-map (make-sparse-keymap))
264
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000265 ;; shadow global bindings for newline-and-indent w/ the py- version.
266 ;; BAW - this is extremely bad form, but I'm not going to change it
267 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000268 (mapcar (function (lambda (key)
269 (define-key
270 py-mode-map key 'py-newline-and-indent)))
271 (where-is-internal 'newline-and-indent))
272
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000273 ;; BAW - you could do it this way, but its not considered proper
274 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000275 (mapcar (function
276 (lambda (x)
277 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000278 '((":" . py-electric-colon)
279 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000280 ("\C-c|" . py-execute-region)
281 ("\C-c!" . py-shell)
282 ("\177" . py-delete-char)
283 ("\n" . py-newline-and-indent)
284 ("\C-c:" . py-guess-indent-offset)
285 ("\C-c\t" . py-indent-region)
Barry Warsawdea4a291996-07-03 22:59:12 +0000286 ("\C-c\C-l" . py-shift-region-left)
287 ("\C-c\C-r" . py-shift-region-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000288 ("\C-c<" . py-shift-region-left)
289 ("\C-c>" . py-shift-region-right)
290 ("\C-c\C-n" . py-next-statement)
291 ("\C-c\C-p" . py-previous-statement)
292 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000293 ("\C-c\C-m" . py-mark-block)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000294 ("\C-c#" . comment-region)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000295 ("\C-c?" . py-describe-mode)
296 ("\C-c\C-hm" . py-describe-mode)
297 ("\e\C-a" . beginning-of-python-def-or-class)
298 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000299 ( "\e\C-h" . mark-python-def-or-class)))
300 ;; should do all keybindings this way
301 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
302 (define-key py-mode-map "\C-c\C-v" 'py-version)
303 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000304
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000305(defvar py-mode-syntax-table nil
306 "Syntax table used in `python-mode' buffers.")
307
Barry Warsaw7ae77681994-12-12 20:38:05 +0000308(if py-mode-syntax-table
309 ()
310 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000311 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000312 (mapcar (function
313 (lambda (x) (modify-syntax-entry
314 (car x) (cdr x) py-mode-syntax-table)))
315 '(( ?\( . "()" ) ( ?\) . ")(" )
316 ( ?\[ . "(]" ) ( ?\] . ")[" )
317 ( ?\{ . "(}" ) ( ?\} . "){" )
318 ;; fix operator symbols misassigned in the std table
319 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
320 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
321 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
322 ( ?\> . "." ) ( ?\| . "." )
Barry Warsaw8e9d7d71996-07-03 23:15:51 +0000323 ;; Guido and I disagree about this. Underscore should be
324 ;; symbol constituent by not word. For historical
325 ;; reasons, I leave it as is. -baw
326 ;;( ?\_ . "_" ) ; underscore is legit in symbols, but not words
327 ( ?\_ . "w" ) ; underscore is legit in words
Barry Warsaw7ae77681994-12-12 20:38:05 +0000328 ( ?\' . "\"") ; single quote is string quote
329 ( ?\" . "\"" ) ; double quote is string quote too
330 ( ?\` . "$") ; backquote is open and close paren
331 ( ?\# . "<") ; hash starts comment
332 ( ?\n . ">")))) ; newline ends comment
333
334(defconst py-stringlit-re
335 (concat
336 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
337 "\\|" ; or
338 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000339 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000340
341;; this is tricky because a trailing backslash does not mean
342;; continuation if it's in a comment
343(defconst py-continued-re
344 (concat
345 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
346 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000347 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000348
349(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000350 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000351
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000352(defconst py-outdent-re
353 (concat "\\(" (mapconcat 'identity
354 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000355 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000356 "finally:"
357 "elif\\s +.*:")
358 "\\|")
359 "\\)")
360 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000361
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000362(defconst py-no-outdent-re
363 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000364 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000365 "except\\(\\s +.*\\)?:"
366 "while\\s +.*:"
367 "for\\s +.*:"
368 "if\\s +.*:"
369 "elif\\s +.*:")
370 "\\|")
371 "\\)")
372 "Regexp matching lines to not outdent after.")
373
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000374
375;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000376(defun python-mode ()
377 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000378To submit a problem report, enter `\\[py-submit-bug-report]' from a
379`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
380documentation. To see what version of `python-mode' you are running,
381enter `\\[py-version]'.
382
383This mode knows about Python indentation, tokens, comments and
384continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000385
386COMMANDS
387\\{py-mode-map}
388VARIABLES
389
390py-indent-offset\tindentation increment
391py-block-comment-prefix\tcomment string used by py-comment-region
392py-python-command\tshell command to invoke Python interpreter
393py-scroll-process-buffer\talways scroll Python process buffer
394py-temp-directory\tdirectory used for temp files (if needed)
395py-beep-if-tab-change\tring the bell if tab-width is changed"
396 (interactive)
397 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000398 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000399 (setq major-mode 'python-mode
400 mode-name "Python"
401 local-abbrev-table python-mode-abbrev-table)
402 (use-local-map py-mode-map)
Barry Warsaw57697af1995-09-14 20:01:14 +0000403 ;; Emacs 19 requires this
404 (if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
405 (setq comment-multi-line nil))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000406 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000407 (mapcar (function (lambda (x)
408 (make-local-variable (car x))
409 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000410 '((paragraph-separate . "^[ \t]*$")
411 (paragraph-start . "^[ \t]*$")
412 (require-final-newline . t)
Barry Warsaw867a32a1996-03-07 18:30:26 +0000413 (comment-start . "## ")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 (comment-start-skip . "# *")
415 (comment-column . 40)
416 (indent-region-function . py-indent-region)
417 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000418 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000419 ;;
420 ;; not sure where the magic comment has to be; to save time
421 ;; searching for a rarity, we give up if it's not found prior to the
422 ;; first executable statement.
423 ;;
424 ;; BAW - on first glance, this seems like complete hackery. Why was
425 ;; this necessary, and is it still necessary?
426 (let ((case-fold-search nil)
427 (start (point))
428 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000429 (if (re-search-forward
430 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
431 (prog2 (py-next-statement 1) (point) (goto-char 1))
432 t)
433 (progn
434 (setq new-tab-width
435 (string-to-int
436 (buffer-substring (match-beginning 1) (match-end 1))))
437 (if (= tab-width new-tab-width)
438 nil
439 (setq tab-width new-tab-width)
440 (message "Caution: tab-width changed to %d" new-tab-width)
441 (if py-beep-if-tab-change (beep)))))
442 (goto-char start))
443
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000444 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445 (if python-mode-hook
446 (run-hooks 'python-mode-hook)
447 (run-hooks 'py-mode-hook)))
448
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000449
Barry Warsaw826255b1996-03-22 16:09:34 +0000450(defun py-keep-region-active ()
451 ;; Do whatever is necessary to keep the region active in
452 ;; XEmacs 19. This is unnecessary, but no-op in Emacs 19, so just
453 ;; ignore byte-compiler warnings you might see.
454 (and (boundp 'zmacs-region-stays)
455 (setq zmacs-region-stays t)))
456
Barry Warsawb91b7431995-03-14 15:55:20 +0000457;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000458(defun py-outdent-p ()
459 ;; returns non-nil if the current line should outdent one level
460 (save-excursion
461 (and (progn (back-to-indentation)
462 (looking-at py-outdent-re))
463 (progn (backward-to-indentation 1)
464 (while (or (looking-at py-blank-or-comment-re)
465 (bobp))
466 (backward-to-indentation 1))
467 (not (looking-at py-no-outdent-re)))
468 )))
469
470
Barry Warsawb91b7431995-03-14 15:55:20 +0000471(defun py-electric-colon (arg)
472 "Insert a colon.
473In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000474argument is provided, that many colons are inserted non-electrically.
475Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000476 (interactive "P")
477 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000478 ;; are we in a string or comment?
479 (if (save-excursion
480 (let ((pps (parse-partial-sexp (save-excursion
481 (beginning-of-python-def-or-class)
482 (point))
483 (point))))
484 (not (or (nth 3 pps) (nth 4 pps)))))
485 (save-excursion
486 (let ((here (point))
487 (outdent 0)
488 (indent (py-compute-indentation)))
489 (if (and (not arg)
490 (py-outdent-p)
491 (= indent (save-excursion
492 (forward-line -1)
493 (py-compute-indentation)))
494 )
495 (setq outdent py-indent-offset))
496 ;; Don't indent, only outdent. This assumes that any lines that
497 ;; are already outdented relative to py-compute-indentation were
498 ;; put there on purpose. Its highly annoying to have `:' indent
499 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
500 ;; there a better way to determine this???
501 (if (< (current-indentation) indent) nil
502 (goto-char here)
503 (beginning-of-line)
504 (delete-horizontal-space)
505 (indent-to (- indent outdent))
506 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000507
508
Barry Warsaw7ae77681994-12-12 20:38:05 +0000509;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000510(defun py-shell ()
511 "Start an interactive Python interpreter in another window.
512This is like Shell mode, except that Python is running in the window
513instead of a shell. See the `Interactive Shell' and `Shell Mode'
514sections of the Emacs manual for details, especially for the key
515bindings active in the `*Python*' buffer.
516
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000517See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000518behavior in the process window.
519
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000520Warning: Don't use an interactive Python if you change sys.ps1 or
521sys.ps2 from their default values, or if you're running code that
522prints `>>> ' or `... ' at the start of a line. `python-mode' can't
523distinguish your output from Python's output, and assumes that `>>> '
524at the start of a line is a prompt from Python. Similarly, the Emacs
525Shell mode code assumes that both `>>> ' and `... ' at the start of a
526line are Python prompts. Bad things can happen if you fool either
527mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000528
529Warning: If you do any editing *in* the process buffer *while* the
530buffer is accepting output from Python, do NOT attempt to `undo' the
531changes. Some of the output (nowhere near the parts you changed!) may
532be lost if you do. This appears to be an Emacs bug, an unfortunate
533interaction between undo and process filters; the same problem exists in
534non-Python process buffers using the default (Emacs-supplied) process
535filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000536 ;; BAW - should undo be disabled in the python process buffer, if
537 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000538 (interactive)
539 (if py-this-is-emacs-19-p
540 (progn
541 (require 'comint)
542 (switch-to-buffer-other-window
543 (make-comint "Python" py-python-command)))
544 (progn
545 (require 'shell)
546 (switch-to-buffer-other-window
Barry Warsaw9fbcc6a1996-01-23 22:52:02 +0000547 (apply (if (fboundp 'make-shell) 'make-shell 'make-comint)
Barry Warsaw6e98f331995-07-05 22:06:50 +0000548 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549 (make-local-variable 'shell-prompt-pattern)
550 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
551 (set-process-filter (get-buffer-process (current-buffer))
552 'py-process-filter)
553 (set-syntax-table py-mode-syntax-table))
554
555(defun py-execute-region (start end)
556 "Send the region between START and END to a Python interpreter.
557If there is a *Python* process it is used.
558
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000559Hint: If you want to execute part of a Python file several times
560\(e.g., perhaps you're developing a function and want to flesh it out
561a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
562the region of interest, and send the code to a *Python* process via
563`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564
565Following are subtleties to note when using a *Python* process:
566
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000567If a *Python* process is used, the region is copied into a temporary
568file (in directory `py-temp-directory'), and an `execfile' command is
569sent to Python naming that file. If you send regions faster than
570Python can execute them, `python-mode' will save them into distinct
571temp files, and execute the next one in the queue the next time it
572sees a `>>> ' prompt from Python. Each time this happens, the process
573buffer is popped into a window (if it's not already in some window) so
574you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000575
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000576 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000577
578is inserted at the end.
579
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000580Caution: No more than 26 regions can be pending at any given time.
581This limit is (indirectly) inherited from libc's mktemp(3).
582`python-mode' does not try to protect you from exceeding the limit.
583It's extremely unlikely that you'll get anywhere close to the limit in
584practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000585
586See the `\\[py-shell]' docs for additional warnings."
587 (interactive "r")
588 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000589 (let ((pyproc (get-process "Python"))
590 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000591 (if (null pyproc)
592 (shell-command-on-region start end py-python-command)
593 ;; else feed it thru a temp file
594 (setq fname (py-make-temp-name))
595 (write-region start end fname nil 'no-msg)
596 (setq py-file-queue (append py-file-queue (list fname)))
597 (if (cdr py-file-queue)
598 (message "File %s queued for execution" fname)
599 ;; else
600 (py-execute-file pyproc fname)))))
601
602(defun py-execute-file (pyproc fname)
603 (py-append-to-process-buffer
604 pyproc
605 (format "## working on region in file %s ...\n" fname))
606 (process-send-string pyproc (format "execfile('%s')\n" fname)))
607
608(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000609 (let ((curbuf (current-buffer))
610 (pbuf (process-buffer pyproc))
611 (pmark (process-mark pyproc))
612 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000613
614 ;; make sure we switch to a different buffer at least once. if we
615 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000616 ;; window, and point is before the end, and lots of output is
617 ;; coming at a fast pace, then (a) simple cursor-movement commands
618 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
619 ;; to have a visible effect (the window just doesn't get updated,
620 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
621 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000622 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000623 ;; #b makes no sense to me at all. #a almost makes sense: unless
624 ;; we actually change buffers, set_buffer_internal in buffer.c
625 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
626 ;; seems to make the Emacs command loop reluctant to update the
627 ;; display. Perhaps the default process filter in process.c's
628 ;; read_process_output has update_mode_lines++ for a similar
629 ;; reason? beats me ...
630
631 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000632 (if (eq curbuf pbuf) ; mysterious ugly hack
633 (set-buffer (get-buffer-create "*scratch*")))
634
635 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000636 (let* ((start (point))
637 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000638 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000639 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000640 (goto-char pmark)
641 (insert string)
642 (move-marker pmark (point))
643 (setq file-finished
644 (and py-file-queue
645 (equal ">>> "
646 (buffer-substring
647 (prog2 (beginning-of-line) (point)
648 (goto-char pmark))
649 (point)))))
650 (if goback (goto-char start)
651 ;; else
652 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000653 (let* ((pop-up-windows t)
654 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000655 (set-window-point pwin (point)))))
656 (set-buffer curbuf)
657 (if file-finished
658 (progn
659 (py-delete-file-silently (car py-file-queue))
660 (setq py-file-queue (cdr py-file-queue))
661 (if py-file-queue
662 (py-execute-file pyproc (car py-file-queue)))))
663 (and goend
664 (progn (set-buffer pbuf)
665 (goto-char (point-max))))
666 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000667
668(defun py-execute-buffer ()
669 "Send the contents of the buffer to a Python interpreter.
670If there is a *Python* process buffer it is used. If a clipping
671restriction is in effect, only the accessible portion of the buffer is
672sent. A trailing newline will be supplied if needed.
673
674See the `\\[py-execute-region]' docs for an account of some subtleties."
675 (interactive)
676 (py-execute-region (point-min) (point-max)))
677
678
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000679
680;; Functions for Python style indentation
Barry Warsaw03970731996-07-03 23:12:52 +0000681(defun py-delete-char (count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000682 "Reduce indentation or delete character.
683If point is at the leftmost column, deletes the preceding newline.
684
685Else if point is at the leftmost non-blank character of a line that is
686neither a continuation line nor a non-indenting comment line, or if
687point is at the end of a blank line, reduces the indentation to match
688that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000689opened the block is displayed in the echo area to help you keep track
Barry Warsaw03970731996-07-03 23:12:52 +0000690of where you are. With numeric count, outdents that many blocks (but
691not past column zero).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000692
693Else the preceding character is deleted, converting a tab to spaces if
Barry Warsaw03970731996-07-03 23:12:52 +0000694needed so that only a single column position is deleted. Numeric
695argument delets that many characters."
696 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000697 (if (or (/= (current-indentation) (current-column))
698 (bolp)
699 (py-continuation-line-p)
700 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw03970731996-07-03 23:12:52 +0000701 (backward-delete-char-untabify count)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000702 ;; else indent the same as the colon line that opened the block
703
704 ;; force non-blank so py-goto-block-up doesn't ignore it
705 (insert-char ?* 1)
706 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000707 (let ((base-indent 0) ; indentation of base line
708 (base-text "") ; and text of base line
709 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +0000710 (save-excursion
711 (while (< 0 count)
712 (condition-case nil ; in case no enclosing block
713 (progn
714 (py-goto-block-up 'no-mark)
715 (setq base-indent (current-indentation)
716 base-text (py-suck-up-leading-text)
717 base-found-p t))
718 (error nil))
719 (setq count (1- count))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000720 (delete-char 1) ; toss the dummy character
721 (delete-horizontal-space)
722 (indent-to base-indent)
723 (if base-found-p
724 (message "Closes block: %s" base-text)))))
725
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000726;; required for pending-del and delsel modes
727(put 'py-delete-char 'delete-selection 'supersede)
728(put 'py-delete-char 'pending-delete 'supersede)
729
Barry Warsaw7ae77681994-12-12 20:38:05 +0000730(defun py-indent-line ()
731 "Fix the indentation of the current line according to Python rules."
732 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000733 (let* ((ci (current-indentation))
734 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000735 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000736 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000737 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000738 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000739 (if (/= ci need)
740 (save-excursion
741 (beginning-of-line)
742 (delete-horizontal-space)
743 (indent-to need)))
744 (if move-to-indentation-p (back-to-indentation))))
745
746(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000747 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000748This is just `strives to' because correct indentation can't be computed
749from scratch for Python code. In general, deletes the whitespace before
750point, inserts a newline, and takes an educated guess as to how you want
751the new line indented."
752 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000753 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000754 (if (< ci (current-column)) ; if point beyond indentation
755 (newline-and-indent)
756 ;; else try to act like newline-and-indent "normally" acts
757 (beginning-of-line)
758 (insert-char ?\n 1)
759 (move-to-column ci))))
760
761(defun py-compute-indentation ()
762 (save-excursion
Barry Warsaw095e9c61995-09-19 20:01:42 +0000763 (let ((pps (parse-partial-sexp (save-excursion
764 (beginning-of-python-def-or-class)
765 (point))
766 (point))))
767 (beginning-of-line)
768 (cond
769 ;; are we inside a string or comment?
770 ((or (nth 3 pps) (nth 4 pps))
771 (save-excursion
772 (if (not py-align-multiline-strings-p) 0
773 ;; skip back over blank & non-indenting comment lines
774 ;; note: will skip a blank or non-indenting comment line
775 ;; that happens to be a continuation line too
776 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
777 (back-to-indentation)
778 (current-column))))
779 ;; are we on a continuation line?
780 ((py-continuation-line-p)
781 (let ((startpos (point))
782 (open-bracket-pos (py-nesting-level))
783 endpos searching found)
784 (if open-bracket-pos
785 (progn
786 ;; align with first item in list; else a normal
787 ;; indent beyond the line with the open bracket
788 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
789 ;; is the first list item on the same line?
790 (skip-chars-forward " \t")
791 (if (null (memq (following-char) '(?\n ?# ?\\)))
792 ; yes, so line up with it
793 (current-column)
794 ;; first list item on another line, or doesn't exist yet
795 (forward-line 1)
796 (while (and (< (point) startpos)
797 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
798 (forward-line 1))
799 (if (< (point) startpos)
800 ;; again mimic the first list item
801 (current-indentation)
802 ;; else they're about to enter the first item
803 (goto-char open-bracket-pos)
804 (+ (current-indentation) py-indent-offset))))
805
806 ;; else on backslash continuation line
807 (forward-line -1)
808 (if (py-continuation-line-p) ; on at least 3rd line in block
809 (current-indentation) ; so just continue the pattern
810 ;; else started on 2nd line in block, so indent more.
811 ;; if base line is an assignment with a start on a RHS,
812 ;; indent to 2 beyond the leftmost "="; else skip first
813 ;; chunk of non-whitespace characters on base line, + 1 more
814 ;; column
815 (end-of-line)
816 (setq endpos (point) searching t)
817 (back-to-indentation)
818 (setq startpos (point))
819 ;; look at all "=" from left to right, stopping at first
820 ;; one not nested in a list or string
821 (while searching
822 (skip-chars-forward "^=" endpos)
823 (if (= (point) endpos)
824 (setq searching nil)
825 (forward-char 1)
826 (setq state (parse-partial-sexp startpos (point)))
827 (if (and (zerop (car state)) ; not in a bracket
828 (null (nth 3 state))) ; & not in a string
829 (progn
830 (setq searching nil) ; done searching in any case
831 (setq found
832 (not (or
833 (eq (following-char) ?=)
834 (memq (char-after (- (point) 2))
835 '(?< ?> ?!)))))))))
836 (if (or (not found) ; not an assignment
837 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
838 (progn
839 (goto-char startpos)
840 (skip-chars-forward "^ \t\n")))
841 (1+ (current-column))))))
842
843 ;; not on a continuation line
844
845 ;; if at start of restriction, or on a non-indenting comment
846 ;; line, assume they intended whatever's there
847 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
848 (current-indentation))
849
850 ;; else indentation based on that of the statement that
851 ;; precedes us; use the first line of that statement to
852 ;; establish the base, in case the user forced a non-std
853 ;; indentation for the continuation lines (if any)
854 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +0000855 ;; skip back over blank & non-indenting comment lines note:
856 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +0000857 ;; happens to be a continuation line too. use fast Emacs 19
858 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +0000859 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000860 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +0000861 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +0000862 (let (done)
863 (while (not done)
864 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
865 nil 'move)
866 (setq done (or (eq py-honor-comment-indentation t)
867 (bobp)
868 (/= (following-char) ?#)
869 (not (zerop (current-column)))))
870 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +0000871 ;; if we landed inside a string, go to the beginning of that
872 ;; string. this handles triple quoted, multi-line spanning
873 ;; strings.
874 (py-goto-initial-line)
875 (if (py-statement-opens-block-p)
876 (+ (current-indentation) py-indent-offset)
877 (current-indentation)))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000878
879(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000880 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000881By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000882`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000883Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000884`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000885their own buffer-local copy), both those currently existing and those
886created later in the Emacs session.
887
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000888Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000889There's no excuse for such foolishness, but sometimes you have to deal
890with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000891`py-indent-offset' to what it thinks it was when they created the
892mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000893
894Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000895looking for a line that opens a block of code. `py-indent-offset' is
896set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000897statement following it. If the search doesn't succeed going forward,
898it's tried again going backward."
899 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000900 (let (new-value
901 (start (point))
902 restart
903 (found nil)
904 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000905 (py-goto-initial-line)
906 (while (not (or found (eobp)))
907 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
908 (progn
909 (setq restart (point))
910 (py-goto-initial-line)
911 (if (py-statement-opens-block-p)
912 (setq found t)
913 (goto-char restart)))))
914 (if found
915 ()
916 (goto-char start)
917 (py-goto-initial-line)
918 (while (not (or found (bobp)))
919 (setq found
920 (and
921 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
922 (or (py-goto-initial-line) t) ; always true -- side effect
923 (py-statement-opens-block-p)))))
924 (setq colon-indent (current-indentation)
925 found (and found (zerop (py-next-statement 1)))
926 new-value (- (current-indentation) colon-indent))
927 (goto-char start)
928 (if found
929 (progn
930 (funcall (if global 'kill-local-variable 'make-local-variable)
931 'py-indent-offset)
932 (setq py-indent-offset new-value)
933 (message "%s value of py-indent-offset set to %d"
934 (if global "Global" "Local")
935 py-indent-offset))
936 (error "Sorry, couldn't guess a value for py-indent-offset"))))
937
938(defun py-shift-region (start end count)
939 (save-excursion
940 (goto-char end) (beginning-of-line) (setq end (point))
941 (goto-char start) (beginning-of-line) (setq start (point))
942 (indent-rigidly start end count)))
943
944(defun py-shift-region-left (start end &optional count)
945 "Shift region of Python code to the left.
946The lines from the line containing the start of the current region up
947to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000948shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000949
950If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000951many columns. With no active region, outdent only the current line.
952You cannot outdent the region if any line is already at column zero."
953 (interactive
954 (let ((p (point))
955 (m (mark))
956 (arg current-prefix-arg))
957 (if m
958 (list (min p m) (max p m) arg)
959 (list p (save-excursion (forward-line 1) (point)) arg))))
960 ;; if any line is at column zero, don't shift the region
961 (save-excursion
962 (goto-char start)
963 (while (< (point) end)
964 (back-to-indentation)
965 (if (zerop (current-column))
966 (error "Region is at left edge."))
967 (forward-line 1)))
968 (py-shift-region start end (- (prefix-numeric-value
969 (or count py-indent-offset))))
970 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971
972(defun py-shift-region-right (start end &optional count)
973 "Shift region of Python code to the right.
974The lines from the line containing the start of the current region up
975to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000976shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977
978If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +0000979many columns. With no active region, indent only the current line."
980 (interactive
981 (let ((p (point))
982 (m (mark))
983 (arg current-prefix-arg))
984 (if m
985 (list (min p m) (max p m) arg)
986 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +0000988 (or count py-indent-offset)))
989 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000990
991(defun py-indent-region (start end &optional indent-offset)
992 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +0000993
Barry Warsaw7ae77681994-12-12 20:38:05 +0000994The lines from the line containing the start of the current region up
995to (but not including) the line containing the end of the region are
996reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000997character in the first column, the first line is left alone and the
998rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +0000999region is reindented with respect to the (closest code or indenting
1000comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001001
1002This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001003control structures are introduced or removed, or to reformat code
1004using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005
1006If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008used.
1009
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001010Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011is called! This function does not compute proper indentation from
1012scratch (that's impossible in Python), it merely adjusts the existing
1013indentation to be correct in context.
1014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001015Warning: This function really has no idea what to do with
1016non-indenting comment lines, and shifts them as if they were indenting
1017comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001018
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001019Special cases: whitespace is deleted from blank lines; continuation
1020lines are shifted by the same amount their initial line was shifted,
1021in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001022initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001023 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001024 (save-excursion
1025 (goto-char end) (beginning-of-line) (setq end (point-marker))
1026 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001027 (let ((py-indent-offset (prefix-numeric-value
1028 (or indent-offset py-indent-offset)))
1029 (indents '(-1)) ; stack of active indent levels
1030 (target-column 0) ; column to which to indent
1031 (base-shifted-by 0) ; amount last base line was shifted
1032 (indent-base (if (looking-at "[ \t\n]")
1033 (py-compute-indentation)
1034 0))
1035 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001036 (while (< (point) end)
1037 (setq ci (current-indentation))
1038 ;; figure out appropriate target column
1039 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001040 ((or (eq (following-char) ?#) ; comment in column 1
1041 (looking-at "[ \t]*$")) ; entirely blank
1042 (setq target-column 0))
1043 ((py-continuation-line-p) ; shift relative to base line
1044 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001045 (t ; new base line
1046 (if (> ci (car indents)) ; going deeper; push it
1047 (setq indents (cons ci indents))
1048 ;; else we should have seen this indent before
1049 (setq indents (memq ci indents)) ; pop deeper indents
1050 (if (null indents)
1051 (error "Bad indentation in region, at line %d"
1052 (save-restriction
1053 (widen)
1054 (1+ (count-lines 1 (point)))))))
1055 (setq target-column (+ indent-base
1056 (* py-indent-offset
1057 (- (length indents) 2))))
1058 (setq base-shifted-by (- target-column ci))))
1059 ;; shift as needed
1060 (if (/= ci target-column)
1061 (progn
1062 (delete-horizontal-space)
1063 (indent-to target-column)))
1064 (forward-line 1))))
1065 (set-marker end nil))
1066
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001067
1068;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001069(defun py-previous-statement (count)
1070 "Go to the start of previous Python statement.
1071If the statement at point is the i'th Python statement, goes to the
1072start of statement i-COUNT. If there is no such statement, goes to the
1073first statement. Returns count of statements left to move.
1074`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001075 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 (if (< count 0) (py-next-statement (- count))
1077 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001079 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001080 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001081 (> count 0)
1082 (zerop (forward-line -1))
1083 (py-goto-statement-at-or-above))
1084 (setq count (1- count)))
1085 (if (> count 0) (goto-char start)))
1086 count))
1087
1088(defun py-next-statement (count)
1089 "Go to the start of next Python statement.
1090If the statement at point is the i'th Python statement, goes to the
1091start of statement i+COUNT. If there is no such statement, goes to the
1092last statement. Returns count of statements left to move. `Statements'
1093do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001095 (if (< count 0) (py-previous-statement (- count))
1096 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001097 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001098 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001099 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 (> count 0)
1101 (py-goto-statement-below))
1102 (setq count (1- count)))
1103 (if (> count 0) (goto-char start)))
1104 count))
1105
1106(defun py-goto-block-up (&optional nomark)
1107 "Move up to start of current block.
1108Go to the statement that starts the smallest enclosing block; roughly
1109speaking, this will be the closest preceding statement that ends with a
1110colon and is indented less than the statement you started on. If
1111successful, also sets the mark to the starting point.
1112
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001113`\\[py-mark-block]' can be used afterward to mark the whole code
1114block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001115
1116If called from a program, the mark will not be set if optional argument
1117NOMARK is not nil."
1118 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001119 (let ((start (point))
1120 (found nil)
1121 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001122 (py-goto-initial-line)
1123 ;; if on blank or non-indenting comment line, use the preceding stmt
1124 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1125 (progn
1126 (py-goto-statement-at-or-above)
1127 (setq found (py-statement-opens-block-p))))
1128 ;; search back for colon line indented less
1129 (setq initial-indent (current-indentation))
1130 (if (zerop initial-indent)
1131 ;; force fast exit
1132 (goto-char (point-min)))
1133 (while (not (or found (bobp)))
1134 (setq found
1135 (and
1136 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1137 (or (py-goto-initial-line) t) ; always true -- side effect
1138 (< (current-indentation) initial-indent)
1139 (py-statement-opens-block-p))))
1140 (if found
1141 (progn
1142 (or nomark (push-mark start))
1143 (back-to-indentation))
1144 (goto-char start)
1145 (error "Enclosing block not found"))))
1146
1147(defun beginning-of-python-def-or-class (&optional class)
1148 "Move point to start of def (or class, with prefix arg).
1149
1150Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001151arg, looks for a `class' instead. The docs assume the `def' case;
1152just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001153
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001154If point is in a def statement already, and after the `d', simply
1155moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001156
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001157Else (point is not in a def statement, or at or before the `d' of a
1158def statement), searches for the closest preceding def statement, and
1159leaves point at its start. If no such statement can be found, leaves
1160point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001161
1162Returns t iff a def statement is found by these rules.
1163
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001164Note that doing this command repeatedly will take you closer to the
1165start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001166
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001167If you want to mark the current def/class, see
1168`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001169 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001170 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1171 (start-of-line (progn (beginning-of-line) (point)))
1172 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001173 (if (or (/= start-of-stmt start-of-line)
1174 (not at-or-before-p))
1175 (end-of-line)) ; OK to match on this line
1176 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001177 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001178
1179(defun end-of-python-def-or-class (&optional class)
1180 "Move point beyond end of def (or class, with prefix arg) body.
1181
1182By default, looks for an appropriate `def'. If you supply a prefix arg,
1183looks for a `class' instead. The docs assume the `def' case; just
1184substitute `class' for `def' for the other case.
1185
1186If point is in a def statement already, this is the def we use.
1187
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001188Else if the def found by `\\[beginning-of-python-def-or-class]'
1189contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001190
1191Else we search forward for the closest following def, and use that.
1192
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001193If a def can be found by these rules, point is moved to the start of
1194the line immediately following the def block, and the position of the
1195start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001196
1197Else point is moved to the end of the buffer, and nil is returned.
1198
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199Note that doing this command repeatedly will take you closer to the
1200end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001202If you want to mark the current def/class, see
1203`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001204 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001205 (let ((start (progn (py-goto-initial-line) (point)))
1206 (which (if class "class" "def"))
1207 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001208 ;; move point to start of appropriate def/class
1209 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1210 (setq state 'at-beginning)
1211 ;; else see if beginning-of-python-def-or-class hits container
1212 (if (and (beginning-of-python-def-or-class class)
1213 (progn (py-goto-beyond-block)
1214 (> (point) start)))
1215 (setq state 'at-end)
1216 ;; else search forward
1217 (goto-char start)
1218 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1219 (progn (setq state 'at-beginning)
1220 (beginning-of-line)))))
1221 (cond
1222 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1223 ((eq state 'at-end) t)
1224 ((eq state 'not-found) nil)
1225 (t (error "internal error in end-of-python-def-or-class")))))
1226
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001227
1228;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001229(defun py-mark-block (&optional extend just-move)
1230 "Mark following block of lines. With prefix arg, mark structure.
1231Easier to use than explain. It sets the region to an `interesting'
1232block of succeeding lines. If point is on a blank line, it goes down to
1233the next non-blank line. That will be the start of the region. The end
1234of the region depends on the kind of line at the start:
1235
1236 - If a comment, the region will include all succeeding comment lines up
1237 to (but not including) the next non-comment line (if any).
1238
1239 - Else if a prefix arg is given, and the line begins one of these
1240 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001241
1242 if elif else try except finally for while def class
1243
Barry Warsaw7ae77681994-12-12 20:38:05 +00001244 the region will be set to the body of the structure, including
1245 following blocks that `belong' to it, but excluding trailing blank
1246 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001247 and all (if any) of the following `except' and `finally' blocks
1248 that belong to the `try' structure will be in the region. Ditto
1249 for if/elif/else, for/else and while/else structures, and (a bit
1250 degenerate, since they're always one-block structures) def and
1251 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001252
1253 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001254 block (see list above), and the block is not a `one-liner' (i.e.,
1255 the statement ends with a colon, not with code), the region will
1256 include all succeeding lines up to (but not including) the next
1257 code statement (if any) that's indented no more than the starting
1258 line, except that trailing blank and comment lines are excluded.
1259 E.g., if the starting line begins a multi-statement `def'
1260 structure, the region will be set to the full function definition,
1261 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001262
1263 - Else the region will include all succeeding lines up to (but not
1264 including) the next blank line, or code or indenting-comment line
1265 indented strictly less than the starting line. Trailing indenting
1266 comment lines are included in this case, but not trailing blank
1267 lines.
1268
1269A msg identifying the location of the mark is displayed in the echo
1270area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1271
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001272If called from a program, optional argument EXTEND plays the role of
1273the prefix arg, and if optional argument JUST-MOVE is not nil, just
1274moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001275 (interactive "P") ; raw prefix arg
1276 (py-goto-initial-line)
1277 ;; skip over blank lines
1278 (while (and
1279 (looking-at "[ \t]*$") ; while blank line
1280 (not (eobp))) ; & somewhere to go
1281 (forward-line 1))
1282 (if (eobp)
1283 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001284 (let ((initial-pos (point))
1285 (initial-indent (current-indentation))
1286 last-pos ; position of last stmt in region
1287 (followers
1288 '((if elif else) (elif elif else) (else)
1289 (try except finally) (except except) (finally)
1290 (for else) (while else)
1291 (def) (class) ) )
1292 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001293
1294 (cond
1295 ;; if comment line, suck up the following comment lines
1296 ((looking-at "[ \t]*#")
1297 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1298 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1299 (setq last-pos (point)))
1300
1301 ;; else if line is a block line and EXTEND given, suck up
1302 ;; the whole structure
1303 ((and extend
1304 (setq first-symbol (py-suck-up-first-keyword) )
1305 (assq first-symbol followers))
1306 (while (and
1307 (or (py-goto-beyond-block) t) ; side effect
1308 (forward-line -1) ; side effect
1309 (setq last-pos (point)) ; side effect
1310 (py-goto-statement-below)
1311 (= (current-indentation) initial-indent)
1312 (setq next-symbol (py-suck-up-first-keyword))
1313 (memq next-symbol (cdr (assq first-symbol followers))))
1314 (setq first-symbol next-symbol)))
1315
1316 ;; else if line *opens* a block, search for next stmt indented <=
1317 ((py-statement-opens-block-p)
1318 (while (and
1319 (setq last-pos (point)) ; always true -- side effect
1320 (py-goto-statement-below)
1321 (> (current-indentation) initial-indent))
1322 nil))
1323
1324 ;; else plain code line; stop at next blank line, or stmt or
1325 ;; indenting comment line indented <
1326 (t
1327 (while (and
1328 (setq last-pos (point)) ; always true -- side effect
1329 (or (py-goto-beyond-final-line) t)
1330 (not (looking-at "[ \t]*$")) ; stop at blank line
1331 (or
1332 (>= (current-indentation) initial-indent)
1333 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1334 nil)))
1335
1336 ;; skip to end of last stmt
1337 (goto-char last-pos)
1338 (py-goto-beyond-final-line)
1339
1340 ;; set mark & display
1341 (if just-move
1342 () ; just return
1343 (push-mark (point) 'no-msg)
1344 (forward-line -1)
1345 (message "Mark set after: %s" (py-suck-up-leading-text))
1346 (goto-char initial-pos))))
1347
1348(defun mark-python-def-or-class (&optional class)
1349 "Set region to body of def (or class, with prefix arg) enclosing point.
1350Pushes the current mark, then point, on the mark ring (all language
1351modes do this, but although it's handy it's never documented ...).
1352
1353In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001354hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1355`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001356
1357And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001358Turned out that was more confusing than useful: the `goto start' and
1359`goto end' commands are usually used to search through a file, and
1360people expect them to act a lot like `search backward' and `search
1361forward' string-search commands. But because Python `def' and `class'
1362can nest to arbitrary levels, finding the smallest def containing
1363point cannot be done via a simple backward search: the def containing
1364point may not be the closest preceding def, or even the closest
1365preceding def that's indented less. The fancy algorithm required is
1366appropriate for the usual uses of this `mark' command, but not for the
1367`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001368
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001369So the def marked by this command may not be the one either of the
1370`goto' commands find: If point is on a blank or non-indenting comment
1371line, moves back to start of the closest preceding code statement or
1372indenting comment line. If this is a `def' statement, that's the def
1373we use. Else searches for the smallest enclosing `def' block and uses
1374that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001375
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001376When an enclosing def is found: The mark is left immediately beyond
1377the last line of the def block. Point is left at the start of the
1378def, except that: if the def is preceded by a number of comment lines
1379followed by (at most) one optional blank line, point is left at the
1380start of the comments; else if the def is preceded by a blank line,
1381point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001382
1383The intent is to mark the containing def/class and its associated
1384documentation, to make moving and duplicating functions and classes
1385pleasant."
1386 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001387 (let ((start (point))
1388 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001389 (push-mark start)
1390 (if (not (py-go-up-tree-to-keyword which))
1391 (progn (goto-char start)
1392 (error "Enclosing %s not found" which))
1393 ;; else enclosing def/class found
1394 (setq start (point))
1395 (py-goto-beyond-block)
1396 (push-mark (point))
1397 (goto-char start)
1398 (if (zerop (forward-line -1)) ; if there is a preceding line
1399 (progn
1400 (if (looking-at "[ \t]*$") ; it's blank
1401 (setq start (point)) ; so reset start point
1402 (goto-char start)) ; else try again
1403 (if (zerop (forward-line -1))
1404 (if (looking-at "[ \t]*#") ; a comment
1405 ;; look back for non-comment line
1406 ;; tricky: note that the regexp matches a blank
1407 ;; line, cuz \n is in the 2nd character class
1408 (and
1409 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1410 (forward-line 1))
1411 ;; no comment, so go back
1412 (goto-char start))))))))
1413
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001414
1415;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001416
1417;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001418;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1419;; out of the right places, along with the keys they're on & current
1420;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001421(defun py-dump-help-string (str)
1422 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001423 (let ((locals (buffer-local-variables))
1424 funckind funcname func funcdoc
1425 (start 0) mstart end
1426 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001427 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1428 (setq mstart (match-beginning 0) end (match-end 0)
1429 funckind (substring str (match-beginning 1) (match-end 1))
1430 funcname (substring str (match-beginning 2) (match-end 2))
1431 func (intern funcname))
1432 (princ (substitute-command-keys (substring str start mstart)))
1433 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001434 ((equal funckind "c") ; command
1435 (setq funcdoc (documentation func)
1436 keys (concat
1437 "Key(s): "
1438 (mapconcat 'key-description
1439 (where-is-internal func py-mode-map)
1440 ", "))))
1441 ((equal funckind "v") ; variable
1442 (setq funcdoc (substitute-command-keys
1443 (get func 'variable-documentation))
1444 keys (if (assq func locals)
1445 (concat
1446 "Local/Global values: "
1447 (prin1-to-string (symbol-value func))
1448 " / "
1449 (prin1-to-string (default-value func)))
1450 (concat
1451 "Value: "
1452 (prin1-to-string (symbol-value func))))))
1453 (t ; unexpected
1454 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455 (princ (format "\n-> %s:\t%s\t%s\n\n"
1456 (if (equal funckind "c") "Command" "Variable")
1457 funcname keys))
1458 (princ funcdoc)
1459 (terpri)
1460 (setq start end))
1461 (princ (substitute-command-keys (substring str start))))
1462 (print-help-return-message)))
1463
1464(defun py-describe-mode ()
1465 "Dump long form of Python-mode docs."
1466 (interactive)
1467 (py-dump-help-string "Major mode for editing Python files.
1468Knows about Python indentation, tokens, comments and continuation lines.
1469Paragraphs are separated by blank lines only.
1470
1471Major sections below begin with the string `@'; specific function and
1472variable docs begin with `->'.
1473
1474@EXECUTING PYTHON CODE
1475
1476\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1477\\[py-execute-region]\tsends the current region
1478\\[py-shell]\tstarts a Python interpreter window; this will be used by
1479\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1480%c:py-execute-buffer
1481%c:py-execute-region
1482%c:py-shell
1483
1484@VARIABLES
1485
1486py-indent-offset\tindentation increment
1487py-block-comment-prefix\tcomment string used by py-comment-region
1488
1489py-python-command\tshell command to invoke Python interpreter
1490py-scroll-process-buffer\talways scroll Python process buffer
1491py-temp-directory\tdirectory used for temp files (if needed)
1492
1493py-beep-if-tab-change\tring the bell if tab-width is changed
1494%v:py-indent-offset
1495%v:py-block-comment-prefix
1496%v:py-python-command
1497%v:py-scroll-process-buffer
1498%v:py-temp-directory
1499%v:py-beep-if-tab-change
1500
1501@KINDS OF LINES
1502
1503Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001504preceding line ends with a backslash that's not part of a comment, or
1505the paren/bracket/brace nesting level at the start of the line is
1506non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001507
1508An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001509possibly blanks or tabs), a `comment line' (leftmost non-blank
1510character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001511
1512Comment Lines
1513
1514Although all comment lines are treated alike by Python, Python mode
1515recognizes two kinds that act differently with respect to indentation.
1516
1517An `indenting comment line' is a comment line with a blank, tab or
1518nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001519treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001520indenting comment line will be indented like the comment line. All
1521other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001522following the initial `#') are `non-indenting comment lines', and
1523their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001524
1525Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001526whenever possible. Non-indenting comment lines are useful in cases
1527like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001528
1529\ta = b # a very wordy single-line comment that ends up being
1530\t #... continued onto another line
1531
1532\tif a == b:
1533##\t\tprint 'panic!' # old code we've `commented out'
1534\t\treturn a
1535
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001536Since the `#...' and `##' comment lines have a non-whitespace
1537character following the initial `#', Python mode ignores them when
1538computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001539
1540Continuation Lines and Statements
1541
1542The Python-mode commands generally work on statements instead of on
1543individual lines, where a `statement' is a comment or blank line, or a
1544code line and all of its following continuation lines (if any)
1545considered as a single logical unit. The commands in this mode
1546generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547statement containing point, even if point happens to be in the middle
1548of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001549
1550
1551@INDENTATION
1552
1553Primarily for entering new code:
1554\t\\[indent-for-tab-command]\t indent line appropriately
1555\t\\[py-newline-and-indent]\t insert newline, then indent
1556\t\\[py-delete-char]\t reduce indentation, or delete single character
1557
1558Primarily for reindenting existing code:
1559\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1560\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1561
1562\t\\[py-indent-region]\t reindent region to match its context
1563\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1564\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1565
1566Unlike most programming languages, Python uses indentation, and only
1567indentation, to specify block structure. Hence the indentation supplied
1568automatically by Python-mode is just an educated guess: only you know
1569the block structure you intend, so only you can supply correct
1570indentation.
1571
1572The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1573the indentation of preceding statements. E.g., assuming
1574py-indent-offset is 4, after you enter
1575\tif a > 0: \\[py-newline-and-indent]
1576the cursor will be moved to the position of the `_' (_ is not a
1577character in the file, it's just used here to indicate the location of
1578the cursor):
1579\tif a > 0:
1580\t _
1581If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1582to
1583\tif a > 0:
1584\t c = d
1585\t _
1586Python-mode cannot know whether that's what you intended, or whether
1587\tif a > 0:
1588\t c = d
1589\t_
1590was your intent. In general, Python-mode either reproduces the
1591indentation of the (closest code or indenting-comment) preceding
1592statement, or adds an extra py-indent-offset blanks if the preceding
1593statement has `:' as its last significant (non-whitespace and non-
1594comment) character. If the suggested indentation is too much, use
1595\\[py-delete-char] to reduce it.
1596
1597Continuation lines are given extra indentation. If you don't like the
1598suggested indentation, change it to something you do like, and Python-
1599mode will strive to indent later lines of the statement in the same way.
1600
1601If a line is a continuation line by virtue of being in an unclosed
1602paren/bracket/brace structure (`list', for short), the suggested
1603indentation depends on whether the current line contains the first item
1604in the list. If it does, it's indented py-indent-offset columns beyond
1605the indentation of the line containing the open bracket. If you don't
1606like that, change it by hand. The remaining items in the list will mimic
1607whatever indentation you give to the first item.
1608
1609If a line is a continuation line because the line preceding it ends with
1610a backslash, the third and following lines of the statement inherit their
1611indentation from the line preceding them. The indentation of the second
1612line in the statement depends on the form of the first (base) line: if
1613the base line is an assignment statement with anything more interesting
1614than the backslash following the leftmost assigning `=', the second line
1615is indented two columns beyond that `='. Else it's indented to two
1616columns beyond the leftmost solid chunk of non-whitespace characters on
1617the base line.
1618
1619Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1620repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1621structure you intend.
1622%c:indent-for-tab-command
1623%c:py-newline-and-indent
1624%c:py-delete-char
1625
1626
1627The next function may be handy when editing code you didn't write:
1628%c:py-guess-indent-offset
1629
1630
1631The remaining `indent' functions apply to a region of Python code. They
1632assume the block structure (equals indentation, in Python) of the region
1633is correct, and alter the indentation in various ways while preserving
1634the block structure:
1635%c:py-indent-region
1636%c:py-shift-region-left
1637%c:py-shift-region-right
1638
1639@MARKING & MANIPULATING REGIONS OF CODE
1640
1641\\[py-mark-block]\t mark block of lines
1642\\[mark-python-def-or-class]\t mark smallest enclosing def
1643\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1644\\[py-comment-region]\t comment out region of code
1645\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1646%c:py-mark-block
1647%c:mark-python-def-or-class
1648%c:py-comment-region
1649
1650@MOVING POINT
1651
1652\\[py-previous-statement]\t move to statement preceding point
1653\\[py-next-statement]\t move to statement following point
1654\\[py-goto-block-up]\t move up to start of current block
1655\\[beginning-of-python-def-or-class]\t move to start of def
1656\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1657\\[end-of-python-def-or-class]\t move to end of def
1658\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1659
1660The first two move to one statement beyond the statement that contains
1661point. A numeric prefix argument tells them to move that many
1662statements instead. Blank lines, comment lines, and continuation lines
1663do not count as `statements' for these commands. So, e.g., you can go
1664to the first code statement in a file by entering
1665\t\\[beginning-of-buffer]\t to move to the top of the file
1666\t\\[py-next-statement]\t to skip over initial comments and blank lines
1667Or do `\\[py-previous-statement]' with a huge prefix argument.
1668%c:py-previous-statement
1669%c:py-next-statement
1670%c:py-goto-block-up
1671%c:beginning-of-python-def-or-class
1672%c:end-of-python-def-or-class
1673
1674@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1675
1676`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1677
1678`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1679overall class and def structure of a module.
1680
1681`\\[back-to-indentation]' moves point to a line's first non-blank character.
1682
1683`\\[indent-relative]' is handy for creating odd indentation.
1684
1685@OTHER EMACS HINTS
1686
1687If you don't like the default value of a variable, change its value to
1688whatever you do like by putting a `setq' line in your .emacs file.
1689E.g., to set the indentation increment to 4, put this line in your
1690.emacs:
1691\t(setq py-indent-offset 4)
1692To see the value of a variable, do `\\[describe-variable]' and enter the variable
1693name at the prompt.
1694
1695When entering a key sequence like `C-c C-n', it is not necessary to
1696release the CONTROL key after doing the `C-c' part -- it suffices to
1697press the CONTROL key, press and release `c' (while still holding down
1698CONTROL), press and release `n' (while still holding down CONTROL), &
1699then release CONTROL.
1700
1701Entering Python mode calls with no arguments the value of the variable
1702`python-mode-hook', if that value exists and is not nil; for backward
1703compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1704the Elisp manual for details.
1705
1706Obscure: When python-mode is first loaded, it looks for all bindings
1707to newline-and-indent in the global keymap, and shadows them with
1708local bindings to py-newline-and-indent."))
1709
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001710
1711;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001712(defvar py-parse-state-re
1713 (concat
1714 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1715 "\\|"
1716 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001717
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718;; returns the parse state at point (see parse-partial-sexp docs)
1719(defun py-parse-state ()
1720 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00001721 (let ((here (point))
1722 pps done)
1723 (while (not done)
1724 ;; back up to the first preceding line (if any; else start of
1725 ;; buffer) that begins with a popular Python keyword, or a
1726 ;; non- whitespace and non-comment character. These are good
1727 ;; places to start parsing to see whether where we started is
1728 ;; at a non-zero nesting level. It may be slow for people who
1729 ;; write huge code blocks or huge lists ... tough beans.
1730 (re-search-backward py-parse-state-re nil 'move)
1731 (beginning-of-line)
1732 (save-excursion
1733 (setq pps (parse-partial-sexp (point) here)))
1734 ;; make sure we don't land inside a triple-quoted string
1735 (setq done (or (not (nth 3 pps)) (bobp))))
1736 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001737
1738;; if point is at a non-zero nesting level, returns the number of the
1739;; character that opens the smallest enclosing unclosed list; else
1740;; returns nil.
1741(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001742 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001743 (if (zerop (car status))
1744 nil ; not in a nest
1745 (car (cdr status))))) ; char# of open bracket
1746
1747;; t iff preceding line ends with backslash that's not in a comment
1748(defun py-backslash-continuation-line-p ()
1749 (save-excursion
1750 (beginning-of-line)
1751 (and
1752 ;; use a cheap test first to avoid the regexp if possible
1753 ;; use 'eq' because char-after may return nil
1754 (eq (char-after (- (point) 2)) ?\\ )
1755 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757 (looking-at py-continued-re))))
1758
1759;; t iff current line is a continuation line
1760(defun py-continuation-line-p ()
1761 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001762 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001763 (or (py-backslash-continuation-line-p)
1764 (py-nesting-level))))
1765
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001766;; go to initial line of current statement; usually this is the line
1767;; we're on, but if we're on the 2nd or following lines of a
1768;; continuation block, we need to go up to the first line of the
1769;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001770;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001771;; Tricky: We want to avoid quadratic-time behavior for long continued
1772;; blocks, whether of the backslash or open-bracket varieties, or a
1773;; mix of the two. The following manages to do that in the usual
1774;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001775(defun py-goto-initial-line ()
1776 (let ( open-bracket-pos )
1777 (while (py-continuation-line-p)
1778 (beginning-of-line)
1779 (if (py-backslash-continuation-line-p)
1780 (while (py-backslash-continuation-line-p)
1781 (forward-line -1))
1782 ;; else zip out of nested brackets/braces/parens
1783 (while (setq open-bracket-pos (py-nesting-level))
1784 (goto-char open-bracket-pos)))))
1785 (beginning-of-line))
1786
1787;; go to point right beyond final line of current statement; usually
1788;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789;; statement we need to skip over the continuation lines. Tricky:
1790;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791(defun py-goto-beyond-final-line ()
1792 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001793 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001794 (while (and (py-continuation-line-p)
1795 (not (eobp)))
1796 ;; skip over the backslash flavor
1797 (while (and (py-backslash-continuation-line-p)
1798 (not (eobp)))
1799 (forward-line 1))
1800 ;; if in nest, zip to the end of the nest
1801 (setq state (py-parse-state))
1802 (if (and (not (zerop (car state)))
1803 (not (eobp)))
1804 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001805 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001806 ;; the 3rd argument should be plain 0
1807 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1808 nil state)
1809 (forward-line 1))))))
1810
1811;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001812;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813(defun py-statement-opens-block-p ()
1814 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815 (let ((start (point))
1816 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1817 (searching t)
1818 (answer nil)
1819 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820 (goto-char start)
1821 (while searching
1822 ;; look for a colon with nothing after it except whitespace, and
1823 ;; maybe a comment
1824 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1825 finish t)
1826 (if (eq (point) finish) ; note: no `else' clause; just
1827 ; keep searching if we're not at
1828 ; the end yet
1829 ;; sure looks like it opens a block -- but it might
1830 ;; be in a comment
1831 (progn
1832 (setq searching nil) ; search is done either way
1833 (setq state (parse-partial-sexp start
1834 (match-beginning 0)))
1835 (setq answer (not (nth 4 state)))))
1836 ;; search failed: couldn't find another interesting colon
1837 (setq searching nil)))
1838 answer)))
1839
1840;; go to point right beyond final line of block begun by the current
1841;; line. This is the same as where py-goto-beyond-final-line goes
1842;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844(defun py-goto-beyond-block ()
1845 (if (py-statement-opens-block-p)
1846 (py-mark-block nil 'just-move)
1847 (py-goto-beyond-final-line)))
1848
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849;; go to start of first statement (not blank or comment or
1850;; continuation line) at or preceding point. returns t if there is
1851;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001852(defun py-goto-statement-at-or-above ()
1853 (py-goto-initial-line)
1854 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001855 ;; skip back over blank & comment lines
1856 ;; note: will skip a blank or comment line that happens to be
1857 ;; a continuation line too
1858 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1859 (progn (py-goto-initial-line) t)
1860 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001861 t))
1862
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863;; go to start of first statement (not blank or comment or
1864;; continuation line) following the statement containing point returns
1865;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866(defun py-goto-statement-below ()
1867 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001868 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001869 (py-goto-beyond-final-line)
1870 (while (and
1871 (looking-at py-blank-or-comment-re)
1872 (not (eobp)))
1873 (forward-line 1))
1874 (if (eobp)
1875 (progn (goto-char start) nil)
1876 t)))
1877
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878;; go to start of statement, at or preceding point, starting with
1879;; keyword KEY. Skips blank lines and non-indenting comments upward
1880;; first. If that statement starts with KEY, done, else go back to
1881;; first enclosing block starting with KEY. If successful, leaves
1882;; point at the start of the KEY line & returns t. Else leaves point
1883;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884(defun py-go-up-tree-to-keyword (key)
1885 ;; skip blanks and non-indenting #
1886 (py-goto-initial-line)
1887 (while (and
1888 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1889 (zerop (forward-line -1))) ; go back
1890 nil)
1891 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892 (let* ((re (concat "[ \t]*" key "\\b"))
1893 (case-fold-search nil) ; let* so looking-at sees this
1894 (found (looking-at re))
1895 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896 (while (not (or found dead))
1897 (condition-case nil ; in case no enclosing block
1898 (py-goto-block-up 'no-mark)
1899 (error (setq dead t)))
1900 (or dead (setq found (looking-at re))))
1901 (beginning-of-line)
1902 found))
1903
1904;; return string in buffer from start of indentation to end of line;
1905;; prefix "..." if leading whitespace was skipped
1906(defun py-suck-up-leading-text ()
1907 (save-excursion
1908 (back-to-indentation)
1909 (concat
1910 (if (bolp) "" "...")
1911 (buffer-substring (point) (progn (end-of-line) (point))))))
1912
1913;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1914;; as a Lisp symbol; return nil if none
1915(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001916 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1918 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1919 nil)))
1920
1921(defun py-make-temp-name ()
1922 (make-temp-name
1923 (concat (file-name-as-directory py-temp-directory) "python")))
1924
1925(defun py-delete-file-silently (fname)
1926 (condition-case nil
1927 (delete-file fname)
1928 (error nil)))
1929
1930(defun py-kill-emacs-hook ()
1931 ;; delete our temp files
1932 (while py-file-queue
1933 (py-delete-file-silently (car py-file-queue))
1934 (setq py-file-queue (cdr py-file-queue)))
1935 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1936 ;; run the hook we inherited, if any
1937 (and py-inherited-kill-emacs-hook
1938 (funcall py-inherited-kill-emacs-hook))))
1939
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940;; make PROCESS's buffer visible, append STRING to it, and force
1941;; display; also make shell-mode believe the user typed this string,
1942;; so that kill-output-from-shell and show-output-from-shell work
1943;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001944(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945 (let ((cbuf (current-buffer))
1946 (pbuf (process-buffer process))
1947 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948 (set-buffer pbuf)
1949 (goto-char (point-max))
1950 (move-marker (process-mark process) (point))
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001951 (if (not (or py-this-is-emacs-19-p
1952 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001953 (move-marker last-input-start (point))) ; muck w/ shell-mode
1954 (funcall (process-filter process) process string)
Barry Warsaw4dba7e21995-07-05 23:01:43 +00001955 (if (not (or py-this-is-emacs-19-p
1956 py-this-is-lucid-emacs-p))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001957 (move-marker last-input-end (point))) ; muck w/ shell-mode
1958 (set-buffer cbuf))
1959 (sit-for 0))
1960
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001961(defun py-keep-region-active ()
1962 ;; do whatever is necessary to keep the region active in XEmacs.
1963 ;; Ignore byte-compiler warnings you might see. Also note that
1964 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1965 ;; require us to take explicit action.
1966 (and (boundp 'zmacs-region-stays)
1967 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968
1969
Barry Warsaw850437a1995-03-08 21:50:28 +00001970(defconst py-version "$Revision$"
1971 "`python-mode' version number.")
Barry Warsawfec75d61995-07-05 23:26:15 +00001972(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00001973 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974
Barry Warsaw850437a1995-03-08 21:50:28 +00001975(defun py-version ()
1976 "Echo the current version of `python-mode' in the minibuffer."
1977 (interactive)
1978 (message "Using `python-mode' version %s" py-version)
1979 (py-keep-region-active))
1980
1981;; only works under Emacs 19
1982;(eval-when-compile
1983; (require 'reporter))
1984
1985(defun py-submit-bug-report (enhancement-p)
1986 "Submit via mail a bug report on `python-mode'.
1987With \\[universal-argument] just submit an enhancement request."
1988 (interactive
1989 (list (not (y-or-n-p
1990 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001991 (let ((reporter-prompt-for-summary-p (if enhancement-p
1992 "(Very) brief summary: "
1993 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001994 (require 'reporter)
1995 (reporter-submit-bug-report
1996 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001997 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001998 ;; varlist
1999 (if enhancement-p nil
2000 '(py-python-command
2001 py-indent-offset
2002 py-block-comment-prefix
2003 py-scroll-process-buffer
2004 py-temp-directory
2005 py-beep-if-tab-change))
2006 nil ;pre-hooks
2007 nil ;post-hooks
2008 "Dear Barry,") ;salutation
2009 (if enhancement-p nil
2010 (set-mark (point))
2011 (insert
2012"Please replace this text with a sufficiently large code sample\n\
2013and an exact recipe so that I can reproduce your problem. Failure\n\
2014to do so may mean a greater delay in fixing your bug.\n\n")
2015 (exchange-point-and-mark)
2016 (py-keep-region-active))))
2017
2018
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002019;; arrange to kill temp files when Emacs exists
2020(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2021 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2022 ;; have to trust that other people are as respectful of our hook
2023 ;; fiddling as we are of theirs
2024 (if (boundp 'py-inherited-kill-emacs-hook)
2025 ;; we were loaded before -- trust others not to have screwed us
2026 ;; in the meantime (no choice, really)
2027 nil
2028 ;; else arrange for our hook to run theirs
2029 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2030 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2031
2032
2033
2034(provide 'python-mode)
2035;;; python-mode.el ends here