blob: a40bb27c2c8be79c0e7408f8966f1122fc27981c [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
5;; Author: 1995 Barry A. Warsaw <bwarsaw@cnri.reston.va.us>
6;; 1992-1994 Tim Peters <tim@ksr.com>
7;; Maintainer: bwarsaw@cnri.reston.va.us
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$
11;; Keywords: python editing language major-mode
12
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 Warsawcfec3591995-03-10 15:58:16 +000024;; 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
28;; mode works exceedingly well.
29
30;; The following statements, placed in your .emacs file or
31;; site-init.el, will cause this file to be autoloaded, and
32;; python-mode invoked, when visiting .py files (assuming this file is
33;; in your load-path):
Barry Warsaw7ae77681994-12-12 20:38:05 +000034;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +000035;; (autoload 'python-mode "python-mode" "Python editing mode." t)
Barry Warsaw7ae77681994-12-12 20:38:05 +000036;; (setq auto-mode-alist
37;; (cons '("\\.py$" . python-mode) auto-mode-alist))
38
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000039;; Here's a brief list of recent additions/improvements:
40;;
41;; - Wrapping and indentation within triple quote strings should work
42;; properly now.
43;; - `Standard' bug reporting mechanism (use C-c C-b)
44;; - py-mark-block was moved to C-c C-m
45;; - C-c C-v shows you the python-mode version
46;; - a basic python-font-lock-keywords has been added for Emacs 19
47;; font-lock colorizations.
48;; - proper interaction with pending-del and del-sel modes.
49;; - New py-electric-colon (:) command for improved outdenting. Also
50;; py-indent-line (TAB) should handle outdented lines better.
Barry Warsaw1a6c82f1995-03-15 16:23:59 +000051;; - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000052
Barry Warsaw7b0f5681995-03-08 21:33:04 +000053;; Here's a brief to do list:
54;;
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000055;; - Better integration with gud-mode for debugging.
56;; - Rewrite according to GNU Emacs Lisp standards.
57;; - py-delete-char should obey numeric arguments.
58;; - even better support for outdenting. Guido suggests outdents of
59;; at least one level after a return, raise, break, or continue
60;; statement.
Barry Warsaw7a1f6f41995-05-08 21:36:20 +000061;; - de-electrify colon inside literals (e.g. comments and strings)
Barry Warsaw7ae77681994-12-12 20:38:05 +000062
Barry Warsaw7b0f5681995-03-08 21:33:04 +000063;; If you can think of more things you'd like to see, drop me a line.
64;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
65;;
66;; Note that I only test things on XEmacs (currently 19.11). If you
67;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
68;; patches.
Barry Warsaw7ae77681994-12-12 20:38:05 +000069
Barry Warsaw7b0f5681995-03-08 21:33:04 +000070;; LCD Archive Entry:
71;; python-mode|Barry A. Warsaw|bwarsaw@cnri.reston.va.us
72;; |Major mode for editing Python programs
73;; |$Date$|$Revision$|
Barry Warsaw7ae77681994-12-12 20:38:05 +000074
Barry Warsaw7b0f5681995-03-08 21:33:04 +000075;;; Code:
76
77
78;; user definable variables
79;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000080
81(defvar py-python-command "python"
82 "*Shell command used to start Python interpreter.")
83
84(defvar py-indent-offset 8 ; argue with Guido <grin>
85 "*Indentation increment.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000086Note that `\\[py-guess-indent-offset]' can usually guess a good value
87when you're editing someone else's Python code.")
Barry Warsaw7ae77681994-12-12 20:38:05 +000088
89(defvar py-block-comment-prefix "##"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000090 "*String used by `py-comment-region' to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +000091This should follow the convention for non-indenting comment lines so
92that the indentation commands won't get confused (i.e., the string
93should be of the form `#x...' where `x' is not a blank or a tab, and
94`...' is arbitrary).")
95
96(defvar py-scroll-process-buffer t
97 "*Scroll Python process buffer as output arrives.
98If nil, the Python process buffer acts, with respect to scrolling, like
99Shell-mode buffers normally act. This is surprisingly complicated and
100so won't be explained here; in fact, you can't get the whole story
101without studying the Emacs C code.
102
103If non-nil, the behavior is different in two respects (which are
104slightly inaccurate in the interest of brevity):
105
106 - If the buffer is in a window, and you left point at its end, the
107 window will scroll as new output arrives, and point will move to the
108 buffer's end, even if the window is not the selected window (that
109 being the one the cursor is in). The usual behavior for shell-mode
110 windows is not to scroll, and to leave point where it was, if the
111 buffer is in a window other than the selected window.
112
113 - If the buffer is not visible in any window, and you left point at
114 its end, the buffer will be popped into a window as soon as more
115 output arrives. This is handy if you have a long-running
116 computation and don't want to tie up screen area waiting for the
117 output. The usual behavior for a shell-mode buffer is to stay
118 invisible until you explicitly visit it.
119
120Note the `and if you left point at its end' clauses in both of the
121above: you can `turn off' the special behaviors while output is in
122progress, by visiting the Python buffer and moving point to anywhere
123besides the end. Then the buffer won't scroll, point will remain where
124you leave it, and if you hide the buffer it will stay hidden until you
125visit it again. You can enable and disable the special behaviors as
126often as you like, while output is in progress, by (respectively) moving
127point to, or away from, the end of the buffer.
128
129Warning: If you expect a large amount of output, you'll probably be
130happier setting this option to nil.
131
132Obscure: `End of buffer' above should really say `at or beyond the
133process mark', but if you know what that means you didn't need to be
134told <grin>.")
135
136(defvar py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000137 (let ((ok '(lambda (x)
138 (and x
139 (setq x (expand-file-name x)) ; always true
140 (file-directory-p x)
141 (file-writable-p x)
142 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000143 (or (funcall ok (getenv "TMPDIR"))
144 (funcall ok "/usr/tmp")
145 (funcall ok "/tmp")
146 (funcall ok ".")
147 (error
148 "Couldn't find a usable temp directory -- set py-temp-directory")))
149 "*Directory used for temp files created by a *Python* process.
150By default, the first directory from this list that exists and that you
151can write into: the value (if any) of the environment variable TMPDIR,
152/usr/tmp, /tmp, or the current directory.")
153
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000154(defvar py-beep-if-tab-change t
155 "*Ring the bell if tab-width is changed.
156If a comment of the form
157
158 \t# vi:set tabsize=<number>:
159
160is found before the first code line when the file is entered, and the
161current value of (the general Emacs variable) `tab-width' does not
162equal <number>, `tab-width' is set to <number>, a message saying so is
163displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
164the Emacs bell is also rung as a warning.")
165
Barry Warsaw4f005cf1995-03-08 22:02:44 +0000166(defvar python-font-lock-keywords
Barry Warsaw65bc7a71995-03-08 22:25:47 +0000167 (list
168 (cons
169 (concat
170 "\\<\\("
171 (mapconcat
172 'identity
173 '("access" "and" "break" "continue"
174 "del" "elif" "else" "except"
175 "exec" "finally" "for" "from"
176 "global" "if" "import" "in"
177 "is" "lambda" "not" "or"
178 "pass" "print" "raise" "return"
179 "try" "while" "def" "class"
180 )
181 "\\|")
182 "\\)\\>")
183 1)
184 ;; functions
185 '("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
186 ;; classes
187 '("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
188 )
Barry Warsawc723b751995-03-08 22:03:16 +0000189 "*Additional keywords to highlight `python-mode' buffers.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000190
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000191;; These are taken from XEmacs 19.12's font-lock.el file. I prefer
192;; these myself, but which do you think are better?
193;;
194;;(defconst python-font-lock-keywords
195;; (purecopy
196;; (list
197;; (cons (concat "\\b\\("
198;; (mapconcat 'identity
199;; '("access" "del" "from"
200;; "lambda" "return" "and"
201;; "elif" "global" "not"
202;; "try:" "break " "else:"
203;; "if" "or" "while"
204;; "except" "except:" "import"
205;; "pass" "continue" "finally:"
206;; "in" "print" "for"
207;; "is" "raise")
208;; "\\|")
209;; "\\)[ \n\t(]")
210;; 1)
211;; '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
212;; 1 font-lock-type-face)
213;; '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
214;; 1 font-lock-function-name-face)
215;; ))
216;; "Additional expressions to highlight in Python mode.")
217
218;; R Lindsay Todd <toddr@rpi.edu> suggests these changes to the
219;; original keywords, which wouldn't be necessary if we go with the
220;; XEmacs defaults, but which I agree makes sense without them.
221;;
222;; functions
223;; '("\\bdef\\s +\\(\\sw+\\)\\s *(" 1 font-lock-function-name-face)
224;; classes
225;; '("\\bclass\\s +\\(\\sw+\\)\\s *[(:]" 1 font-lock-type-face)
226
227
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000228
229;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
230;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
231
232;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
233;; seems to be the standard way of checking this.
234;; BAW - This is *not* the right solution. When at all possible,
235;; instead of testing for the version of Emacs, use feature tests.
236
237(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
238(setq py-this-is-emacs-19-p
239 (and
240 (not py-this-is-lucid-emacs-p)
241 (string-match "^19\\." emacs-version)))
242
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243;; have to bind py-file-queue before installing the kill-emacs hook
244(defvar py-file-queue nil
245 "Queue of Python temp files awaiting execution.
246Currently-active file is at the head of the list.")
247
248;; define a mode-specific abbrev table for those who use such things
249(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000250 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251(define-abbrev-table 'python-mode-abbrev-table nil)
252
Barry Warsaw7ae77681994-12-12 20:38:05 +0000253(defvar python-mode-hook nil
254 "*Hook called by `python-mode'.")
255
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000256;; in previous version of python-mode.el, the hook was incorrectly
257;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000258(and (fboundp 'make-obsolete-variable)
259 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
260
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000261(defvar py-mode-map ()
262 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000263
Barry Warsaw7ae77681994-12-12 20:38:05 +0000264(if py-mode-map
265 ()
266 (setq py-mode-map (make-sparse-keymap))
267
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000268 ;; shadow global bindings for newline-and-indent w/ the py- version.
269 ;; BAW - this is extremely bad form, but I'm not going to change it
270 ;; for now.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271 (mapcar (function (lambda (key)
272 (define-key
273 py-mode-map key 'py-newline-and-indent)))
274 (where-is-internal 'newline-and-indent))
275
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000276 ;; BAW - you could do it this way, but its not considered proper
277 ;; major-mode form.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000278 (mapcar (function
279 (lambda (x)
280 (define-key py-mode-map (car x) (cdr x))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000281 '((":" . py-electric-colon)
282 ("\C-c\C-c" . py-execute-buffer)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 ("\C-c|" . py-execute-region)
284 ("\C-c!" . py-shell)
285 ("\177" . py-delete-char)
286 ("\n" . py-newline-and-indent)
287 ("\C-c:" . py-guess-indent-offset)
288 ("\C-c\t" . py-indent-region)
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000289 ("\C-c\C-l" . py-outdent-left)
290 ("\C-c\C-r" . py-indent-right)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000291 ("\C-c<" . py-shift-region-left)
292 ("\C-c>" . py-shift-region-right)
293 ("\C-c\C-n" . py-next-statement)
294 ("\C-c\C-p" . py-previous-statement)
295 ("\C-c\C-u" . py-goto-block-up)
Barry Warsaw850437a1995-03-08 21:50:28 +0000296 ("\C-c\C-m" . py-mark-block)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000297 ("\C-c#" . py-comment-region)
298 ("\C-c?" . py-describe-mode)
299 ("\C-c\C-hm" . py-describe-mode)
300 ("\e\C-a" . beginning-of-python-def-or-class)
301 ("\e\C-e" . end-of-python-def-or-class)
Barry Warsaw850437a1995-03-08 21:50:28 +0000302 ( "\e\C-h" . mark-python-def-or-class)))
303 ;; should do all keybindings this way
304 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
305 (define-key py-mode-map "\C-c\C-v" 'py-version)
306 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000307
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000308(defvar py-mode-syntax-table nil
309 "Syntax table used in `python-mode' buffers.")
310
Barry Warsaw7ae77681994-12-12 20:38:05 +0000311(if py-mode-syntax-table
312 ()
313 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000314 ;; BAW - again, blech.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000315 (mapcar (function
316 (lambda (x) (modify-syntax-entry
317 (car x) (cdr x) py-mode-syntax-table)))
318 '(( ?\( . "()" ) ( ?\) . ")(" )
319 ( ?\[ . "(]" ) ( ?\] . ")[" )
320 ( ?\{ . "(}" ) ( ?\} . "){" )
321 ;; fix operator symbols misassigned in the std table
322 ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
323 ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
324 ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
325 ( ?\> . "." ) ( ?\| . "." )
326 ( ?\_ . "w" ) ; underscore is legit in names
327 ( ?\' . "\"") ; single quote is string quote
328 ( ?\" . "\"" ) ; double quote is string quote too
329 ( ?\` . "$") ; backquote is open and close paren
330 ( ?\# . "<") ; hash starts comment
331 ( ?\n . ">")))) ; newline ends comment
332
333(defconst py-stringlit-re
334 (concat
335 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
336 "\\|" ; or
337 "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000338 "Regexp matching a Python string literal.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000339
340;; this is tricky because a trailing backslash does not mean
341;; continuation if it's in a comment
342(defconst py-continued-re
343 (concat
344 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
345 "\\\\$")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000346 "Regexp matching Python lines that are continued via backslash.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000347
348(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000349 "Regexp matching blank or comment lines.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000350
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000351(defconst py-outdent-re
352 (concat "\\(" (mapconcat 'identity
353 '("else:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000354 "except\\(\\s +.*\\)?:"
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000355 "finally:"
356 "elif\\s +.*:")
357 "\\|")
358 "\\)")
359 "Regexp matching clauses to be outdented one level.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000360
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000361(defconst py-no-outdent-re
362 (concat "\\(" (mapconcat 'identity
Barry Warsaw464c94a1995-03-14 23:25:44 +0000363 '("try:"
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000364 "except\\(\\s +.*\\)?:"
365 "while\\s +.*:"
366 "for\\s +.*:"
367 "if\\s +.*:"
368 "elif\\s +.*:")
369 "\\|")
370 "\\)")
371 "Regexp matching lines to not outdent after.")
372
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000373
374;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000375(defun python-mode ()
376 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000377To submit a problem report, enter `\\[py-submit-bug-report]' from a
378`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
379documentation. To see what version of `python-mode' you are running,
380enter `\\[py-version]'.
381
382This mode knows about Python indentation, tokens, comments and
383continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000384
385COMMANDS
386\\{py-mode-map}
387VARIABLES
388
389py-indent-offset\tindentation increment
390py-block-comment-prefix\tcomment string used by py-comment-region
391py-python-command\tshell command to invoke Python interpreter
392py-scroll-process-buffer\talways scroll Python process buffer
393py-temp-directory\tdirectory used for temp files (if needed)
394py-beep-if-tab-change\tring the bell if tab-width is changed"
395 (interactive)
396 (kill-all-local-variables)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000397 (set-syntax-table py-mode-syntax-table)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000398 (setq major-mode 'python-mode
399 mode-name "Python"
400 local-abbrev-table python-mode-abbrev-table)
401 (use-local-map py-mode-map)
402 ;; BAW -- style...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000403 (mapcar (function (lambda (x)
404 (make-local-variable (car x))
405 (set (car x) (cdr x))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000406 '((paragraph-separate . "^[ \t]*$")
407 (paragraph-start . "^[ \t]*$")
408 (require-final-newline . t)
409 (comment-start . "# ")
410 (comment-start-skip . "# *")
411 (comment-column . 40)
412 (indent-region-function . py-indent-region)
413 (indent-line-function . py-indent-line)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000414 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000415 ;;
416 ;; not sure where the magic comment has to be; to save time
417 ;; searching for a rarity, we give up if it's not found prior to the
418 ;; first executable statement.
419 ;;
420 ;; BAW - on first glance, this seems like complete hackery. Why was
421 ;; this necessary, and is it still necessary?
422 (let ((case-fold-search nil)
423 (start (point))
424 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000425 (if (re-search-forward
426 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
427 (prog2 (py-next-statement 1) (point) (goto-char 1))
428 t)
429 (progn
430 (setq new-tab-width
431 (string-to-int
432 (buffer-substring (match-beginning 1) (match-end 1))))
433 (if (= tab-width new-tab-width)
434 nil
435 (setq tab-width new-tab-width)
436 (message "Caution: tab-width changed to %d" new-tab-width)
437 (if py-beep-if-tab-change (beep)))))
438 (goto-char start))
439
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000440 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000441 (if python-mode-hook
442 (run-hooks 'python-mode-hook)
443 (run-hooks 'py-mode-hook)))
444
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000445
Barry Warsawb91b7431995-03-14 15:55:20 +0000446;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000447(defun py-outdent-p ()
448 ;; returns non-nil if the current line should outdent one level
449 (save-excursion
450 (and (progn (back-to-indentation)
451 (looking-at py-outdent-re))
452 (progn (backward-to-indentation 1)
453 (while (or (looking-at py-blank-or-comment-re)
454 (bobp))
455 (backward-to-indentation 1))
456 (not (looking-at py-no-outdent-re)))
457 )))
458
459
Barry Warsawb91b7431995-03-14 15:55:20 +0000460(defun py-electric-colon (arg)
461 "Insert a colon.
462In certain cases the line is outdented appropriately. If a numeric
463argument is provided, that many colons are inserted non-electrically."
464 (interactive "P")
465 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000466 (save-excursion
467 (let ((here (point))
468 (outdent 0)
469 (indent (py-compute-indentation)))
470 (if (and (not arg)
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000471 (py-outdent-p)
Barry Warsaw3aca2a11995-03-20 18:32:14 +0000472 (= indent (save-excursion
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000473 (forward-line -1)
474 (py-compute-indentation)))
475 )
476 (setq outdent py-indent-offset))
Barry Warsawd865bc51995-03-15 18:23:16 +0000477 ;; Don't indent, only outdent. This assumes that any lines that
478 ;; are already outdented relative to py-compute-indentation were
479 ;; put there on purpose. Its highly annoying to have `:' indent
480 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
481 ;; there a better way to determine this???
Barry Warsawa6a714e1995-03-15 18:19:15 +0000482 (if (< (current-indentation) indent) nil
Barry Warsaw9b623b31995-03-14 23:59:07 +0000483 (goto-char here)
484 (beginning-of-line)
485 (delete-horizontal-space)
486 (indent-to (- indent outdent))
487 ))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000488
Barry Warsaw1a6c82f1995-03-15 16:23:59 +0000489(defun py-indent-right (arg)
490 "Indent the line by one `py-indent-offset' level.
491With numeric arg, indent by that many levels. You cannot indent
492farther right than the distance the line would be indented by
493\\[py-indent-line]."
494 (interactive "p")
495 (let ((col (current-indentation))
496 (want (* arg py-indent-offset))
497 (indent (py-compute-indentation))
498 (pos (- (point-max) (point)))
499 (bol (save-excursion (beginning-of-line) (point))))
500 (if (<= (+ col want) indent)
501 (progn
502 (beginning-of-line)
503 (delete-horizontal-space)
504 (indent-to (+ col want))
505 (if (> (- (point-max) pos) (point))
506 (goto-char (- (point-max) pos)))
507 ))))
508
509(defun py-outdent-left (arg)
510 "Outdent the line by one `py-indent-offset' level.
511With numeric arg, outdent by that many levels. You cannot outdent
512farther left than column zero."
513 (interactive "p")
514 (let ((col (current-indentation))
515 (want (* arg py-indent-offset))
516 (pos (- (point-max) (point)))
517 (bol (save-excursion (beginning-of-line) (point))))
518 (if (<= 0 (- col want))
519 (progn
520 (beginning-of-line)
521 (delete-horizontal-space)
522 (indent-to (- col want))
523 (if (> (- (point-max) pos) (point))
524 (goto-char (- (point-max) pos)))
525 ))))
526
Barry Warsawb91b7431995-03-14 15:55:20 +0000527
Barry Warsaw7ae77681994-12-12 20:38:05 +0000528;;; Functions that execute Python commands in a subprocess
Barry Warsaw7ae77681994-12-12 20:38:05 +0000529(defun py-shell ()
530 "Start an interactive Python interpreter in another window.
531This is like Shell mode, except that Python is running in the window
532instead of a shell. See the `Interactive Shell' and `Shell Mode'
533sections of the Emacs manual for details, especially for the key
534bindings active in the `*Python*' buffer.
535
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000536See the docs for variable `py-scroll-buffer' for info on scrolling
Barry Warsaw7ae77681994-12-12 20:38:05 +0000537behavior in the process window.
538
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000539Warning: Don't use an interactive Python if you change sys.ps1 or
540sys.ps2 from their default values, or if you're running code that
541prints `>>> ' or `... ' at the start of a line. `python-mode' can't
542distinguish your output from Python's output, and assumes that `>>> '
543at the start of a line is a prompt from Python. Similarly, the Emacs
544Shell mode code assumes that both `>>> ' and `... ' at the start of a
545line are Python prompts. Bad things can happen if you fool either
546mode.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000547
548Warning: If you do any editing *in* the process buffer *while* the
549buffer is accepting output from Python, do NOT attempt to `undo' the
550changes. Some of the output (nowhere near the parts you changed!) may
551be lost if you do. This appears to be an Emacs bug, an unfortunate
552interaction between undo and process filters; the same problem exists in
553non-Python process buffers using the default (Emacs-supplied) process
554filter."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000555 ;; BAW - should undo be disabled in the python process buffer, if
556 ;; this bug still exists?
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557 (interactive)
558 (if py-this-is-emacs-19-p
559 (progn
560 (require 'comint)
561 (switch-to-buffer-other-window
562 (make-comint "Python" py-python-command)))
563 (progn
564 (require 'shell)
565 (switch-to-buffer-other-window
Barry Warsaw6e98f331995-07-05 22:06:50 +0000566 (apply (if (boundp 'make-shell) 'make-shell 'make-comint)
567 "Python" py-python-command nil))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000568 (make-local-variable 'shell-prompt-pattern)
569 (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
570 (set-process-filter (get-buffer-process (current-buffer))
571 'py-process-filter)
572 (set-syntax-table py-mode-syntax-table))
573
574(defun py-execute-region (start end)
575 "Send the region between START and END to a Python interpreter.
576If there is a *Python* process it is used.
577
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000578Hint: If you want to execute part of a Python file several times
579\(e.g., perhaps you're developing a function and want to flesh it out
580a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
581the region of interest, and send the code to a *Python* process via
582`\\[py-execute-buffer]' instead.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000583
584Following are subtleties to note when using a *Python* process:
585
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000586If a *Python* process is used, the region is copied into a temporary
587file (in directory `py-temp-directory'), and an `execfile' command is
588sent to Python naming that file. If you send regions faster than
589Python can execute them, `python-mode' will save them into distinct
590temp files, and execute the next one in the queue the next time it
591sees a `>>> ' prompt from Python. Each time this happens, the process
592buffer is popped into a window (if it's not already in some window) so
593you can see it, and a comment of the form
Barry Warsaw7ae77681994-12-12 20:38:05 +0000594
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000595 \t## working on region in file <name> ...
Barry Warsaw7ae77681994-12-12 20:38:05 +0000596
597is inserted at the end.
598
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000599Caution: No more than 26 regions can be pending at any given time.
600This limit is (indirectly) inherited from libc's mktemp(3).
601`python-mode' does not try to protect you from exceeding the limit.
602It's extremely unlikely that you'll get anywhere close to the limit in
603practice, unless you're trying to be a jerk <grin>.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000604
605See the `\\[py-shell]' docs for additional warnings."
606 (interactive "r")
607 (or (< start end) (error "Region is empty"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000608 (let ((pyproc (get-process "Python"))
609 fname)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000610 (if (null pyproc)
611 (shell-command-on-region start end py-python-command)
612 ;; else feed it thru a temp file
613 (setq fname (py-make-temp-name))
614 (write-region start end fname nil 'no-msg)
615 (setq py-file-queue (append py-file-queue (list fname)))
616 (if (cdr py-file-queue)
617 (message "File %s queued for execution" fname)
618 ;; else
619 (py-execute-file pyproc fname)))))
620
621(defun py-execute-file (pyproc fname)
622 (py-append-to-process-buffer
623 pyproc
624 (format "## working on region in file %s ...\n" fname))
625 (process-send-string pyproc (format "execfile('%s')\n" fname)))
626
627(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000628 (let ((curbuf (current-buffer))
629 (pbuf (process-buffer pyproc))
630 (pmark (process-mark pyproc))
631 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000632
633 ;; make sure we switch to a different buffer at least once. if we
634 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000635 ;; window, and point is before the end, and lots of output is
636 ;; coming at a fast pace, then (a) simple cursor-movement commands
637 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
638 ;; to have a visible effect (the window just doesn't get updated,
639 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
640 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +0000641 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000642 ;; #b makes no sense to me at all. #a almost makes sense: unless
643 ;; we actually change buffers, set_buffer_internal in buffer.c
644 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
645 ;; seems to make the Emacs command loop reluctant to update the
646 ;; display. Perhaps the default process filter in process.c's
647 ;; read_process_output has update_mode_lines++ for a similar
648 ;; reason? beats me ...
649
650 ;; BAW - we want to check to see if this still applies
Barry Warsaw7ae77681994-12-12 20:38:05 +0000651 (if (eq curbuf pbuf) ; mysterious ugly hack
652 (set-buffer (get-buffer-create "*scratch*")))
653
654 (set-buffer pbuf)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000655 (let* ((start (point))
656 (goback (< start pmark))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000657 (goend (and (not goback) (= start (point-max))))
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000658 (buffer-read-only nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000659 (goto-char pmark)
660 (insert string)
661 (move-marker pmark (point))
662 (setq file-finished
663 (and py-file-queue
664 (equal ">>> "
665 (buffer-substring
666 (prog2 (beginning-of-line) (point)
667 (goto-char pmark))
668 (point)))))
669 (if goback (goto-char start)
670 ;; else
671 (if py-scroll-process-buffer
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000672 (let* ((pop-up-windows t)
673 (pwin (display-buffer pbuf)))
Barry Warsawe64bfee1995-07-05 22:27:23 +0000674 (set-window-point pwin (point)))))
675 (set-buffer curbuf)
676 (if file-finished
677 (progn
678 (py-delete-file-silently (car py-file-queue))
679 (setq py-file-queue (cdr py-file-queue))
680 (if py-file-queue
681 (py-execute-file pyproc (car py-file-queue)))))
682 (and goend
683 (progn (set-buffer pbuf)
684 (goto-char (point-max))))
685 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000686
687(defun py-execute-buffer ()
688 "Send the contents of the buffer to a Python interpreter.
689If there is a *Python* process buffer it is used. If a clipping
690restriction is in effect, only the accessible portion of the buffer is
691sent. A trailing newline will be supplied if needed.
692
693See the `\\[py-execute-region]' docs for an account of some subtleties."
694 (interactive)
695 (py-execute-region (point-min) (point-max)))
696
697
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000698
699;; Functions for Python style indentation
Barry Warsaw7ae77681994-12-12 20:38:05 +0000700(defun py-delete-char ()
701 "Reduce indentation or delete character.
702If point is at the leftmost column, deletes the preceding newline.
703
704Else if point is at the leftmost non-blank character of a line that is
705neither a continuation line nor a non-indenting comment line, or if
706point is at the end of a blank line, reduces the indentation to match
707that of the line that opened the current block of code. The line that
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000708opened the block is displayed in the echo area to help you keep track
709of where you are.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000710
711Else the preceding character is deleted, converting a tab to spaces if
712needed so that only a single column position is deleted."
713 (interactive "*")
714 (if (or (/= (current-indentation) (current-column))
715 (bolp)
716 (py-continuation-line-p)
717 (looking-at "#[^ \t\n]")) ; non-indenting #
718 (backward-delete-char-untabify 1)
719 ;; else indent the same as the colon line that opened the block
720
721 ;; force non-blank so py-goto-block-up doesn't ignore it
722 (insert-char ?* 1)
723 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000724 (let ((base-indent 0) ; indentation of base line
725 (base-text "") ; and text of base line
726 (base-found-p nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000727 (condition-case nil ; in case no enclosing block
728 (save-excursion
729 (py-goto-block-up 'no-mark)
730 (setq base-indent (current-indentation)
731 base-text (py-suck-up-leading-text)
732 base-found-p t))
733 (error nil))
734 (delete-char 1) ; toss the dummy character
735 (delete-horizontal-space)
736 (indent-to base-indent)
737 (if base-found-p
738 (message "Closes block: %s" base-text)))))
739
Barry Warsawfc8a01f1995-03-09 16:07:29 +0000740;; required for pending-del and delsel modes
741(put 'py-delete-char 'delete-selection 'supersede)
742(put 'py-delete-char 'pending-delete 'supersede)
743
Barry Warsaw7ae77681994-12-12 20:38:05 +0000744(defun py-indent-line ()
745 "Fix the indentation of the current line according to Python rules."
746 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000747 (let* ((ci (current-indentation))
748 (move-to-indentation-p (<= (current-column) ci))
Barry Warsawb86bbad1995-03-14 15:56:35 +0000749 (need (py-compute-indentation)))
Barry Warsaw4f009fb1995-03-14 20:53:08 +0000750 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000751 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +0000752 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000753 (if (/= ci need)
754 (save-excursion
755 (beginning-of-line)
756 (delete-horizontal-space)
757 (indent-to need)))
758 (if move-to-indentation-p (back-to-indentation))))
759
760(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000761 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000762This is just `strives to' because correct indentation can't be computed
763from scratch for Python code. In general, deletes the whitespace before
764point, inserts a newline, and takes an educated guess as to how you want
765the new line indented."
766 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000767 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000768 (if (< ci (current-column)) ; if point beyond indentation
769 (newline-and-indent)
770 ;; else try to act like newline-and-indent "normally" acts
771 (beginning-of-line)
772 (insert-char ?\n 1)
773 (move-to-column ci))))
774
775(defun py-compute-indentation ()
776 (save-excursion
777 (beginning-of-line)
778 (cond
779 ;; are we on a continuation line?
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000780 ((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))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000805
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000806 ;; 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))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000842
843 ;; not on a continuation line
844
845 ;; if at start of restriction, or on a non-indenting comment line,
846 ;; assume they intended whatever's there
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000847 ((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
848 (current-indentation))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000849
850 ;; else indentation based on that of the statement that precedes
851 ;; us; use the first line of that statement to establish the base,
852 ;; in case the user forced a non-std indentation for the
853 ;; continuation lines (if any)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000854 (t
855 ;; skip back over blank & non-indenting comment lines
856 ;; note: will skip a blank or non-indenting comment line that
857 ;; happens to be a continuation line too
858 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
859 nil 'move)
860 ;; if we landed inside a string, go to the beginning of that
861 ;; string. this handles triple quoted, multi-line spanning
862 ;; strings.
863 (let ((state (parse-partial-sexp
864 (save-excursion (beginning-of-python-def-or-class)
865 (point))
866 (point))))
867 (if (nth 3 state)
868 (goto-char (nth 2 state))))
869 (py-goto-initial-line)
870 (if (py-statement-opens-block-p)
871 (+ (current-indentation) py-indent-offset)
872 (current-indentation))))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000873
874(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000875 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000876By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000877`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +0000878Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000879`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +0000880their own buffer-local copy), both those currently existing and those
881created later in the Emacs session.
882
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000883Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000884There's no excuse for such foolishness, but sometimes you have to deal
885with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000886`py-indent-offset' to what it thinks it was when they created the
887mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000888
889Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000890looking for a line that opens a block of code. `py-indent-offset' is
891set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +0000892statement following it. If the search doesn't succeed going forward,
893it's tried again going backward."
894 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000895 (let (new-value
896 (start (point))
897 restart
898 (found nil)
899 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000900 (py-goto-initial-line)
901 (while (not (or found (eobp)))
902 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
903 (progn
904 (setq restart (point))
905 (py-goto-initial-line)
906 (if (py-statement-opens-block-p)
907 (setq found t)
908 (goto-char restart)))))
909 (if found
910 ()
911 (goto-char start)
912 (py-goto-initial-line)
913 (while (not (or found (bobp)))
914 (setq found
915 (and
916 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
917 (or (py-goto-initial-line) t) ; always true -- side effect
918 (py-statement-opens-block-p)))))
919 (setq colon-indent (current-indentation)
920 found (and found (zerop (py-next-statement 1)))
921 new-value (- (current-indentation) colon-indent))
922 (goto-char start)
923 (if found
924 (progn
925 (funcall (if global 'kill-local-variable 'make-local-variable)
926 'py-indent-offset)
927 (setq py-indent-offset new-value)
928 (message "%s value of py-indent-offset set to %d"
929 (if global "Global" "Local")
930 py-indent-offset))
931 (error "Sorry, couldn't guess a value for py-indent-offset"))))
932
933(defun py-shift-region (start end count)
934 (save-excursion
935 (goto-char end) (beginning-of-line) (setq end (point))
936 (goto-char start) (beginning-of-line) (setq start (point))
937 (indent-rigidly start end count)))
938
939(defun py-shift-region-left (start end &optional count)
940 "Shift region of Python code to the left.
941The lines from the line containing the start of the current region up
942to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000943shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000944
945If a prefix argument is given, the region is instead shifted by that
946many columns."
947 (interactive "*r\nP") ; region; raw prefix arg
948 (py-shift-region start end
949 (- (prefix-numeric-value
950 (or count py-indent-offset)))))
951
952(defun py-shift-region-right (start end &optional count)
953 "Shift region of Python code to the right.
954The lines from the line containing the start of the current region up
955to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000956shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000957
958If a prefix argument is given, the region is instead shifted by that
959many columns."
960 (interactive "*r\nP") ; region; raw prefix arg
961 (py-shift-region start end (prefix-numeric-value
962 (or count py-indent-offset))))
963
964(defun py-indent-region (start end &optional indent-offset)
965 "Reindent a region of Python code.
966The lines from the line containing the start of the current region up
967to (but not including) the line containing the end of the region are
968reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000969character in the first column, the first line is left alone and the
970rest of the region is reindented with respect to it. Else the entire
971region is reindented with respect to the (closest code or
972indenting-comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000973
974This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000975control structures are introduced or removed, or to reformat code
976using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977
978If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000979the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +0000980used.
981
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000982Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +0000983is called! This function does not compute proper indentation from
984scratch (that's impossible in Python), it merely adjusts the existing
985indentation to be correct in context.
986
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000987Warning: This function really has no idea what to do with
988non-indenting comment lines, and shifts them as if they were indenting
989comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000990
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000991Special cases: whitespace is deleted from blank lines; continuation
992lines are shifted by the same amount their initial line was shifted,
993in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +0000994initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000995 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +0000996 (save-excursion
997 (goto-char end) (beginning-of-line) (setq end (point-marker))
998 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000999 (let ((py-indent-offset (prefix-numeric-value
1000 (or indent-offset py-indent-offset)))
1001 (indents '(-1)) ; stack of active indent levels
1002 (target-column 0) ; column to which to indent
1003 (base-shifted-by 0) ; amount last base line was shifted
1004 (indent-base (if (looking-at "[ \t\n]")
1005 (py-compute-indentation)
1006 0))
1007 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008 (while (< (point) end)
1009 (setq ci (current-indentation))
1010 ;; figure out appropriate target column
1011 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012 ((or (eq (following-char) ?#) ; comment in column 1
1013 (looking-at "[ \t]*$")) ; entirely blank
1014 (setq target-column 0))
1015 ((py-continuation-line-p) ; shift relative to base line
1016 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001017 (t ; new base line
1018 (if (> ci (car indents)) ; going deeper; push it
1019 (setq indents (cons ci indents))
1020 ;; else we should have seen this indent before
1021 (setq indents (memq ci indents)) ; pop deeper indents
1022 (if (null indents)
1023 (error "Bad indentation in region, at line %d"
1024 (save-restriction
1025 (widen)
1026 (1+ (count-lines 1 (point)))))))
1027 (setq target-column (+ indent-base
1028 (* py-indent-offset
1029 (- (length indents) 2))))
1030 (setq base-shifted-by (- target-column ci))))
1031 ;; shift as needed
1032 (if (/= ci target-column)
1033 (progn
1034 (delete-horizontal-space)
1035 (indent-to target-column)))
1036 (forward-line 1))))
1037 (set-marker end nil))
1038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001039
1040;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041(defun py-previous-statement (count)
1042 "Go to the start of previous Python statement.
1043If the statement at point is the i'th Python statement, goes to the
1044start of statement i-COUNT. If there is no such statement, goes to the
1045first statement. Returns count of statements left to move.
1046`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001047 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001048 (if (< count 0) (py-next-statement (- count))
1049 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001050 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001051 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001052 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001053 (> count 0)
1054 (zerop (forward-line -1))
1055 (py-goto-statement-at-or-above))
1056 (setq count (1- count)))
1057 (if (> count 0) (goto-char start)))
1058 count))
1059
1060(defun py-next-statement (count)
1061 "Go to the start of next Python statement.
1062If the statement at point is the i'th Python statement, goes to the
1063start of statement i+COUNT. If there is no such statement, goes to the
1064last statement. Returns count of statements left to move. `Statements'
1065do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001066 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001067 (if (< count 0) (py-previous-statement (- count))
1068 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001069 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001071 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001072 (> count 0)
1073 (py-goto-statement-below))
1074 (setq count (1- count)))
1075 (if (> count 0) (goto-char start)))
1076 count))
1077
1078(defun py-goto-block-up (&optional nomark)
1079 "Move up to start of current block.
1080Go to the statement that starts the smallest enclosing block; roughly
1081speaking, this will be the closest preceding statement that ends with a
1082colon and is indented less than the statement you started on. If
1083successful, also sets the mark to the starting point.
1084
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085`\\[py-mark-block]' can be used afterward to mark the whole code
1086block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001087
1088If called from a program, the mark will not be set if optional argument
1089NOMARK is not nil."
1090 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001091 (let ((start (point))
1092 (found nil)
1093 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001094 (py-goto-initial-line)
1095 ;; if on blank or non-indenting comment line, use the preceding stmt
1096 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1097 (progn
1098 (py-goto-statement-at-or-above)
1099 (setq found (py-statement-opens-block-p))))
1100 ;; search back for colon line indented less
1101 (setq initial-indent (current-indentation))
1102 (if (zerop initial-indent)
1103 ;; force fast exit
1104 (goto-char (point-min)))
1105 (while (not (or found (bobp)))
1106 (setq found
1107 (and
1108 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1109 (or (py-goto-initial-line) t) ; always true -- side effect
1110 (< (current-indentation) initial-indent)
1111 (py-statement-opens-block-p))))
1112 (if found
1113 (progn
1114 (or nomark (push-mark start))
1115 (back-to-indentation))
1116 (goto-char start)
1117 (error "Enclosing block not found"))))
1118
1119(defun beginning-of-python-def-or-class (&optional class)
1120 "Move point to start of def (or class, with prefix arg).
1121
1122Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001123arg, looks for a `class' instead. The docs assume the `def' case;
1124just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001125
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001126If point is in a def statement already, and after the `d', simply
1127moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001128
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001129Else (point is not in a def statement, or at or before the `d' of a
1130def statement), searches for the closest preceding def statement, and
1131leaves point at its start. If no such statement can be found, leaves
1132point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001133
1134Returns t iff a def statement is found by these rules.
1135
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001136Note that doing this command repeatedly will take you closer to the
1137start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001138
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001139If you want to mark the current def/class, see
1140`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001141 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001142 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1143 (start-of-line (progn (beginning-of-line) (point)))
1144 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001145 (if (or (/= start-of-stmt start-of-line)
1146 (not at-or-before-p))
1147 (end-of-line)) ; OK to match on this line
1148 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001149 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
1151(defun end-of-python-def-or-class (&optional class)
1152 "Move point beyond end of def (or class, with prefix arg) body.
1153
1154By default, looks for an appropriate `def'. If you supply a prefix arg,
1155looks for a `class' instead. The docs assume the `def' case; just
1156substitute `class' for `def' for the other case.
1157
1158If point is in a def statement already, this is the def we use.
1159
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001160Else if the def found by `\\[beginning-of-python-def-or-class]'
1161contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001162
1163Else we search forward for the closest following def, and use that.
1164
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001165If a def can be found by these rules, point is moved to the start of
1166the line immediately following the def block, and the position of the
1167start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001168
1169Else point is moved to the end of the buffer, and nil is returned.
1170
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001171Note that doing this command repeatedly will take you closer to the
1172end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001173
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001174If you want to mark the current def/class, see
1175`\\[mark-python-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001176 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001177 (let ((start (progn (py-goto-initial-line) (point)))
1178 (which (if class "class" "def"))
1179 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001180 ;; move point to start of appropriate def/class
1181 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1182 (setq state 'at-beginning)
1183 ;; else see if beginning-of-python-def-or-class hits container
1184 (if (and (beginning-of-python-def-or-class class)
1185 (progn (py-goto-beyond-block)
1186 (> (point) start)))
1187 (setq state 'at-end)
1188 ;; else search forward
1189 (goto-char start)
1190 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1191 (progn (setq state 'at-beginning)
1192 (beginning-of-line)))))
1193 (cond
1194 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1195 ((eq state 'at-end) t)
1196 ((eq state 'not-found) nil)
1197 (t (error "internal error in end-of-python-def-or-class")))))
1198
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001199
1200;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001201(defun py-mark-block (&optional extend just-move)
1202 "Mark following block of lines. With prefix arg, mark structure.
1203Easier to use than explain. It sets the region to an `interesting'
1204block of succeeding lines. If point is on a blank line, it goes down to
1205the next non-blank line. That will be the start of the region. The end
1206of the region depends on the kind of line at the start:
1207
1208 - If a comment, the region will include all succeeding comment lines up
1209 to (but not including) the next non-comment line (if any).
1210
1211 - Else if a prefix arg is given, and the line begins one of these
1212 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001213
1214 if elif else try except finally for while def class
1215
Barry Warsaw7ae77681994-12-12 20:38:05 +00001216 the region will be set to the body of the structure, including
1217 following blocks that `belong' to it, but excluding trailing blank
1218 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001219 and all (if any) of the following `except' and `finally' blocks
1220 that belong to the `try' structure will be in the region. Ditto
1221 for if/elif/else, for/else and while/else structures, and (a bit
1222 degenerate, since they're always one-block structures) def and
1223 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001224
1225 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001226 block (see list above), and the block is not a `one-liner' (i.e.,
1227 the statement ends with a colon, not with code), the region will
1228 include all succeeding lines up to (but not including) the next
1229 code statement (if any) that's indented no more than the starting
1230 line, except that trailing blank and comment lines are excluded.
1231 E.g., if the starting line begins a multi-statement `def'
1232 structure, the region will be set to the full function definition,
1233 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001234
1235 - Else the region will include all succeeding lines up to (but not
1236 including) the next blank line, or code or indenting-comment line
1237 indented strictly less than the starting line. Trailing indenting
1238 comment lines are included in this case, but not trailing blank
1239 lines.
1240
1241A msg identifying the location of the mark is displayed in the echo
1242area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1243
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001244If called from a program, optional argument EXTEND plays the role of
1245the prefix arg, and if optional argument JUST-MOVE is not nil, just
1246moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001247 (interactive "P") ; raw prefix arg
1248 (py-goto-initial-line)
1249 ;; skip over blank lines
1250 (while (and
1251 (looking-at "[ \t]*$") ; while blank line
1252 (not (eobp))) ; & somewhere to go
1253 (forward-line 1))
1254 (if (eobp)
1255 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001256 (let ((initial-pos (point))
1257 (initial-indent (current-indentation))
1258 last-pos ; position of last stmt in region
1259 (followers
1260 '((if elif else) (elif elif else) (else)
1261 (try except finally) (except except) (finally)
1262 (for else) (while else)
1263 (def) (class) ) )
1264 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001265
1266 (cond
1267 ;; if comment line, suck up the following comment lines
1268 ((looking-at "[ \t]*#")
1269 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1270 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1271 (setq last-pos (point)))
1272
1273 ;; else if line is a block line and EXTEND given, suck up
1274 ;; the whole structure
1275 ((and extend
1276 (setq first-symbol (py-suck-up-first-keyword) )
1277 (assq first-symbol followers))
1278 (while (and
1279 (or (py-goto-beyond-block) t) ; side effect
1280 (forward-line -1) ; side effect
1281 (setq last-pos (point)) ; side effect
1282 (py-goto-statement-below)
1283 (= (current-indentation) initial-indent)
1284 (setq next-symbol (py-suck-up-first-keyword))
1285 (memq next-symbol (cdr (assq first-symbol followers))))
1286 (setq first-symbol next-symbol)))
1287
1288 ;; else if line *opens* a block, search for next stmt indented <=
1289 ((py-statement-opens-block-p)
1290 (while (and
1291 (setq last-pos (point)) ; always true -- side effect
1292 (py-goto-statement-below)
1293 (> (current-indentation) initial-indent))
1294 nil))
1295
1296 ;; else plain code line; stop at next blank line, or stmt or
1297 ;; indenting comment line indented <
1298 (t
1299 (while (and
1300 (setq last-pos (point)) ; always true -- side effect
1301 (or (py-goto-beyond-final-line) t)
1302 (not (looking-at "[ \t]*$")) ; stop at blank line
1303 (or
1304 (>= (current-indentation) initial-indent)
1305 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
1306 nil)))
1307
1308 ;; skip to end of last stmt
1309 (goto-char last-pos)
1310 (py-goto-beyond-final-line)
1311
1312 ;; set mark & display
1313 (if just-move
1314 () ; just return
1315 (push-mark (point) 'no-msg)
1316 (forward-line -1)
1317 (message "Mark set after: %s" (py-suck-up-leading-text))
1318 (goto-char initial-pos))))
1319
1320(defun mark-python-def-or-class (&optional class)
1321 "Set region to body of def (or class, with prefix arg) enclosing point.
1322Pushes the current mark, then point, on the mark ring (all language
1323modes do this, but although it's handy it's never documented ...).
1324
1325In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001326hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
1327`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001328
1329And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001330Turned out that was more confusing than useful: the `goto start' and
1331`goto end' commands are usually used to search through a file, and
1332people expect them to act a lot like `search backward' and `search
1333forward' string-search commands. But because Python `def' and `class'
1334can nest to arbitrary levels, finding the smallest def containing
1335point cannot be done via a simple backward search: the def containing
1336point may not be the closest preceding def, or even the closest
1337preceding def that's indented less. The fancy algorithm required is
1338appropriate for the usual uses of this `mark' command, but not for the
1339`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001341So the def marked by this command may not be the one either of the
1342`goto' commands find: If point is on a blank or non-indenting comment
1343line, moves back to start of the closest preceding code statement or
1344indenting comment line. If this is a `def' statement, that's the def
1345we use. Else searches for the smallest enclosing `def' block and uses
1346that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001347
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001348When an enclosing def is found: The mark is left immediately beyond
1349the last line of the def block. Point is left at the start of the
1350def, except that: if the def is preceded by a number of comment lines
1351followed by (at most) one optional blank line, point is left at the
1352start of the comments; else if the def is preceded by a blank line,
1353point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001354
1355The intent is to mark the containing def/class and its associated
1356documentation, to make moving and duplicating functions and classes
1357pleasant."
1358 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001359 (let ((start (point))
1360 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361 (push-mark start)
1362 (if (not (py-go-up-tree-to-keyword which))
1363 (progn (goto-char start)
1364 (error "Enclosing %s not found" which))
1365 ;; else enclosing def/class found
1366 (setq start (point))
1367 (py-goto-beyond-block)
1368 (push-mark (point))
1369 (goto-char start)
1370 (if (zerop (forward-line -1)) ; if there is a preceding line
1371 (progn
1372 (if (looking-at "[ \t]*$") ; it's blank
1373 (setq start (point)) ; so reset start point
1374 (goto-char start)) ; else try again
1375 (if (zerop (forward-line -1))
1376 (if (looking-at "[ \t]*#") ; a comment
1377 ;; look back for non-comment line
1378 ;; tricky: note that the regexp matches a blank
1379 ;; line, cuz \n is in the 2nd character class
1380 (and
1381 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
1382 (forward-line 1))
1383 ;; no comment, so go back
1384 (goto-char start))))))))
1385
1386(defun py-comment-region (start end &optional uncomment-p)
1387 "Comment out region of code; with prefix arg, uncomment region.
1388The lines from the line containing the start of the current region up
1389to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001390commented out, by inserting the string `py-block-comment-prefix' at
1391the start of each line. With a prefix arg, removes
1392`py-block-comment-prefix' from the start of each line instead."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393 (interactive "*r\nP") ; region; raw prefix arg
1394 (goto-char end) (beginning-of-line) (setq end (point))
1395 (goto-char start) (beginning-of-line) (setq start (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001396 (let ((prefix-len (length py-block-comment-prefix)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001397 (save-excursion
1398 (save-restriction
1399 (narrow-to-region start end)
1400 (while (not (eobp))
1401 (if uncomment-p
1402 (and (string= py-block-comment-prefix
1403 (buffer-substring
1404 (point) (+ (point) prefix-len)))
1405 (delete-char prefix-len))
1406 (insert py-block-comment-prefix))
1407 (forward-line 1))))))
1408
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001409
1410;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001411
1412;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001413;; plus lines of the form ^[vc]:name$ to suck variable & command docs
1414;; out of the right places, along with the keys they're on & current
1415;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00001416(defun py-dump-help-string (str)
1417 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001418 (let ((locals (buffer-local-variables))
1419 funckind funcname func funcdoc
1420 (start 0) mstart end
1421 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001422 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
1423 (setq mstart (match-beginning 0) end (match-end 0)
1424 funckind (substring str (match-beginning 1) (match-end 1))
1425 funcname (substring str (match-beginning 2) (match-end 2))
1426 func (intern funcname))
1427 (princ (substitute-command-keys (substring str start mstart)))
1428 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001429 ((equal funckind "c") ; command
1430 (setq funcdoc (documentation func)
1431 keys (concat
1432 "Key(s): "
1433 (mapconcat 'key-description
1434 (where-is-internal func py-mode-map)
1435 ", "))))
1436 ((equal funckind "v") ; variable
1437 (setq funcdoc (substitute-command-keys
1438 (get func 'variable-documentation))
1439 keys (if (assq func locals)
1440 (concat
1441 "Local/Global values: "
1442 (prin1-to-string (symbol-value func))
1443 " / "
1444 (prin1-to-string (default-value func)))
1445 (concat
1446 "Value: "
1447 (prin1-to-string (symbol-value func))))))
1448 (t ; unexpected
1449 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001450 (princ (format "\n-> %s:\t%s\t%s\n\n"
1451 (if (equal funckind "c") "Command" "Variable")
1452 funcname keys))
1453 (princ funcdoc)
1454 (terpri)
1455 (setq start end))
1456 (princ (substitute-command-keys (substring str start))))
1457 (print-help-return-message)))
1458
1459(defun py-describe-mode ()
1460 "Dump long form of Python-mode docs."
1461 (interactive)
1462 (py-dump-help-string "Major mode for editing Python files.
1463Knows about Python indentation, tokens, comments and continuation lines.
1464Paragraphs are separated by blank lines only.
1465
1466Major sections below begin with the string `@'; specific function and
1467variable docs begin with `->'.
1468
1469@EXECUTING PYTHON CODE
1470
1471\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
1472\\[py-execute-region]\tsends the current region
1473\\[py-shell]\tstarts a Python interpreter window; this will be used by
1474\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
1475%c:py-execute-buffer
1476%c:py-execute-region
1477%c:py-shell
1478
1479@VARIABLES
1480
1481py-indent-offset\tindentation increment
1482py-block-comment-prefix\tcomment string used by py-comment-region
1483
1484py-python-command\tshell command to invoke Python interpreter
1485py-scroll-process-buffer\talways scroll Python process buffer
1486py-temp-directory\tdirectory used for temp files (if needed)
1487
1488py-beep-if-tab-change\tring the bell if tab-width is changed
1489%v:py-indent-offset
1490%v:py-block-comment-prefix
1491%v:py-python-command
1492%v:py-scroll-process-buffer
1493%v:py-temp-directory
1494%v:py-beep-if-tab-change
1495
1496@KINDS OF LINES
1497
1498Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001499preceding line ends with a backslash that's not part of a comment, or
1500the paren/bracket/brace nesting level at the start of the line is
1501non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001502
1503An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001504possibly blanks or tabs), a `comment line' (leftmost non-blank
1505character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001506
1507Comment Lines
1508
1509Although all comment lines are treated alike by Python, Python mode
1510recognizes two kinds that act differently with respect to indentation.
1511
1512An `indenting comment line' is a comment line with a blank, tab or
1513nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001514treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00001515indenting comment line will be indented like the comment line. All
1516other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001517following the initial `#') are `non-indenting comment lines', and
1518their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001519
1520Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521whenever possible. Non-indenting comment lines are useful in cases
1522like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00001523
1524\ta = b # a very wordy single-line comment that ends up being
1525\t #... continued onto another line
1526
1527\tif a == b:
1528##\t\tprint 'panic!' # old code we've `commented out'
1529\t\treturn a
1530
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001531Since the `#...' and `##' comment lines have a non-whitespace
1532character following the initial `#', Python mode ignores them when
1533computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001534
1535Continuation Lines and Statements
1536
1537The Python-mode commands generally work on statements instead of on
1538individual lines, where a `statement' is a comment or blank line, or a
1539code line and all of its following continuation lines (if any)
1540considered as a single logical unit. The commands in this mode
1541generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542statement containing point, even if point happens to be in the middle
1543of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001544
1545
1546@INDENTATION
1547
1548Primarily for entering new code:
1549\t\\[indent-for-tab-command]\t indent line appropriately
1550\t\\[py-newline-and-indent]\t insert newline, then indent
1551\t\\[py-delete-char]\t reduce indentation, or delete single character
1552
1553Primarily for reindenting existing code:
1554\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
1555\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
1556
1557\t\\[py-indent-region]\t reindent region to match its context
1558\t\\[py-shift-region-left]\t shift region left by py-indent-offset
1559\t\\[py-shift-region-right]\t shift region right by py-indent-offset
1560
1561Unlike most programming languages, Python uses indentation, and only
1562indentation, to specify block structure. Hence the indentation supplied
1563automatically by Python-mode is just an educated guess: only you know
1564the block structure you intend, so only you can supply correct
1565indentation.
1566
1567The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
1568the indentation of preceding statements. E.g., assuming
1569py-indent-offset is 4, after you enter
1570\tif a > 0: \\[py-newline-and-indent]
1571the cursor will be moved to the position of the `_' (_ is not a
1572character in the file, it's just used here to indicate the location of
1573the cursor):
1574\tif a > 0:
1575\t _
1576If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
1577to
1578\tif a > 0:
1579\t c = d
1580\t _
1581Python-mode cannot know whether that's what you intended, or whether
1582\tif a > 0:
1583\t c = d
1584\t_
1585was your intent. In general, Python-mode either reproduces the
1586indentation of the (closest code or indenting-comment) preceding
1587statement, or adds an extra py-indent-offset blanks if the preceding
1588statement has `:' as its last significant (non-whitespace and non-
1589comment) character. If the suggested indentation is too much, use
1590\\[py-delete-char] to reduce it.
1591
1592Continuation lines are given extra indentation. If you don't like the
1593suggested indentation, change it to something you do like, and Python-
1594mode will strive to indent later lines of the statement in the same way.
1595
1596If a line is a continuation line by virtue of being in an unclosed
1597paren/bracket/brace structure (`list', for short), the suggested
1598indentation depends on whether the current line contains the first item
1599in the list. If it does, it's indented py-indent-offset columns beyond
1600the indentation of the line containing the open bracket. If you don't
1601like that, change it by hand. The remaining items in the list will mimic
1602whatever indentation you give to the first item.
1603
1604If a line is a continuation line because the line preceding it ends with
1605a backslash, the third and following lines of the statement inherit their
1606indentation from the line preceding them. The indentation of the second
1607line in the statement depends on the form of the first (base) line: if
1608the base line is an assignment statement with anything more interesting
1609than the backslash following the leftmost assigning `=', the second line
1610is indented two columns beyond that `='. Else it's indented to two
1611columns beyond the leftmost solid chunk of non-whitespace characters on
1612the base line.
1613
1614Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
1615repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
1616structure you intend.
1617%c:indent-for-tab-command
1618%c:py-newline-and-indent
1619%c:py-delete-char
1620
1621
1622The next function may be handy when editing code you didn't write:
1623%c:py-guess-indent-offset
1624
1625
1626The remaining `indent' functions apply to a region of Python code. They
1627assume the block structure (equals indentation, in Python) of the region
1628is correct, and alter the indentation in various ways while preserving
1629the block structure:
1630%c:py-indent-region
1631%c:py-shift-region-left
1632%c:py-shift-region-right
1633
1634@MARKING & MANIPULATING REGIONS OF CODE
1635
1636\\[py-mark-block]\t mark block of lines
1637\\[mark-python-def-or-class]\t mark smallest enclosing def
1638\\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
1639\\[py-comment-region]\t comment out region of code
1640\\[universal-argument] \\[py-comment-region]\t uncomment region of code
1641%c:py-mark-block
1642%c:mark-python-def-or-class
1643%c:py-comment-region
1644
1645@MOVING POINT
1646
1647\\[py-previous-statement]\t move to statement preceding point
1648\\[py-next-statement]\t move to statement following point
1649\\[py-goto-block-up]\t move up to start of current block
1650\\[beginning-of-python-def-or-class]\t move to start of def
1651\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
1652\\[end-of-python-def-or-class]\t move to end of def
1653\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
1654
1655The first two move to one statement beyond the statement that contains
1656point. A numeric prefix argument tells them to move that many
1657statements instead. Blank lines, comment lines, and continuation lines
1658do not count as `statements' for these commands. So, e.g., you can go
1659to the first code statement in a file by entering
1660\t\\[beginning-of-buffer]\t to move to the top of the file
1661\t\\[py-next-statement]\t to skip over initial comments and blank lines
1662Or do `\\[py-previous-statement]' with a huge prefix argument.
1663%c:py-previous-statement
1664%c:py-next-statement
1665%c:py-goto-block-up
1666%c:beginning-of-python-def-or-class
1667%c:end-of-python-def-or-class
1668
1669@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
1670
1671`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
1672
1673`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
1674overall class and def structure of a module.
1675
1676`\\[back-to-indentation]' moves point to a line's first non-blank character.
1677
1678`\\[indent-relative]' is handy for creating odd indentation.
1679
1680@OTHER EMACS HINTS
1681
1682If you don't like the default value of a variable, change its value to
1683whatever you do like by putting a `setq' line in your .emacs file.
1684E.g., to set the indentation increment to 4, put this line in your
1685.emacs:
1686\t(setq py-indent-offset 4)
1687To see the value of a variable, do `\\[describe-variable]' and enter the variable
1688name at the prompt.
1689
1690When entering a key sequence like `C-c C-n', it is not necessary to
1691release the CONTROL key after doing the `C-c' part -- it suffices to
1692press the CONTROL key, press and release `c' (while still holding down
1693CONTROL), press and release `n' (while still holding down CONTROL), &
1694then release CONTROL.
1695
1696Entering Python mode calls with no arguments the value of the variable
1697`python-mode-hook', if that value exists and is not nil; for backward
1698compatibility it also tries `py-mode-hook'; see the `Hooks' section of
1699the Elisp manual for details.
1700
1701Obscure: When python-mode is first loaded, it looks for all bindings
1702to newline-and-indent in the global keymap, and shadows them with
1703local bindings to py-newline-and-indent."))
1704
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001705
1706;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001707(defvar py-parse-state-re
1708 (concat
1709 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
1710 "\\|"
1711 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713;; returns the parse state at point (see parse-partial-sexp docs)
1714(defun py-parse-state ()
1715 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001716 (let ((here (point)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001717 ;; back up to the first preceding line (if any; else start of
1718 ;; buffer) that begins with a popular Python keyword, or a non-
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001719 ;; whitespace and non-comment character. These are good places
1720 ;; to start parsing to see whether where we started is at a
1721 ;; non-zero nesting level. It may be slow for people who write
1722 ;; huge code blocks or huge lists ... tough beans.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723 (re-search-backward py-parse-state-re nil 'move)
1724 (beginning-of-line)
1725 (parse-partial-sexp (point) here))))
1726
1727;; if point is at a non-zero nesting level, returns the number of the
1728;; character that opens the smallest enclosing unclosed list; else
1729;; returns nil.
1730(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001731 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001732 (if (zerop (car status))
1733 nil ; not in a nest
1734 (car (cdr status))))) ; char# of open bracket
1735
1736;; t iff preceding line ends with backslash that's not in a comment
1737(defun py-backslash-continuation-line-p ()
1738 (save-excursion
1739 (beginning-of-line)
1740 (and
1741 ;; use a cheap test first to avoid the regexp if possible
1742 ;; use 'eq' because char-after may return nil
1743 (eq (char-after (- (point) 2)) ?\\ )
1744 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001745 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746 (looking-at py-continued-re))))
1747
1748;; t iff current line is a continuation line
1749(defun py-continuation-line-p ()
1750 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001752 (or (py-backslash-continuation-line-p)
1753 (py-nesting-level))))
1754
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001755;; go to initial line of current statement; usually this is the line
1756;; we're on, but if we're on the 2nd or following lines of a
1757;; continuation block, we need to go up to the first line of the
1758;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001759;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001760;; Tricky: We want to avoid quadratic-time behavior for long continued
1761;; blocks, whether of the backslash or open-bracket varieties, or a
1762;; mix of the two. The following manages to do that in the usual
1763;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764(defun py-goto-initial-line ()
1765 (let ( open-bracket-pos )
1766 (while (py-continuation-line-p)
1767 (beginning-of-line)
1768 (if (py-backslash-continuation-line-p)
1769 (while (py-backslash-continuation-line-p)
1770 (forward-line -1))
1771 ;; else zip out of nested brackets/braces/parens
1772 (while (setq open-bracket-pos (py-nesting-level))
1773 (goto-char open-bracket-pos)))))
1774 (beginning-of-line))
1775
1776;; go to point right beyond final line of current statement; usually
1777;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001778;; statement we need to skip over the continuation lines. Tricky:
1779;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001780(defun py-goto-beyond-final-line ()
1781 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001782 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001783 (while (and (py-continuation-line-p)
1784 (not (eobp)))
1785 ;; skip over the backslash flavor
1786 (while (and (py-backslash-continuation-line-p)
1787 (not (eobp)))
1788 (forward-line 1))
1789 ;; if in nest, zip to the end of the nest
1790 (setq state (py-parse-state))
1791 (if (and (not (zerop (car state)))
1792 (not (eobp)))
1793 (progn
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794 ;; BUG ALERT: I could swear, from reading the docs, that
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795 ;; the 3rd argument should be plain 0
1796 (parse-partial-sexp (point) (point-max) (- 0 (car state))
1797 nil state)
1798 (forward-line 1))))))
1799
1800;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001801;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00001802(defun py-statement-opens-block-p ()
1803 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001804 (let ((start (point))
1805 (finish (progn (py-goto-beyond-final-line) (1- (point))))
1806 (searching t)
1807 (answer nil)
1808 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001809 (goto-char start)
1810 (while searching
1811 ;; look for a colon with nothing after it except whitespace, and
1812 ;; maybe a comment
1813 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
1814 finish t)
1815 (if (eq (point) finish) ; note: no `else' clause; just
1816 ; keep searching if we're not at
1817 ; the end yet
1818 ;; sure looks like it opens a block -- but it might
1819 ;; be in a comment
1820 (progn
1821 (setq searching nil) ; search is done either way
1822 (setq state (parse-partial-sexp start
1823 (match-beginning 0)))
1824 (setq answer (not (nth 4 state)))))
1825 ;; search failed: couldn't find another interesting colon
1826 (setq searching nil)))
1827 answer)))
1828
1829;; go to point right beyond final line of block begun by the current
1830;; line. This is the same as where py-goto-beyond-final-line goes
1831;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001832;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00001833(defun py-goto-beyond-block ()
1834 (if (py-statement-opens-block-p)
1835 (py-mark-block nil 'just-move)
1836 (py-goto-beyond-final-line)))
1837
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001838;; go to start of first statement (not blank or comment or
1839;; continuation line) at or preceding point. returns t if there is
1840;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001841(defun py-goto-statement-at-or-above ()
1842 (py-goto-initial-line)
1843 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001844 ;; skip back over blank & comment lines
1845 ;; note: will skip a blank or comment line that happens to be
1846 ;; a continuation line too
1847 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
1848 (progn (py-goto-initial-line) t)
1849 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850 t))
1851
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852;; go to start of first statement (not blank or comment or
1853;; continuation line) following the statement containing point returns
1854;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855(defun py-goto-statement-below ()
1856 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858 (py-goto-beyond-final-line)
1859 (while (and
1860 (looking-at py-blank-or-comment-re)
1861 (not (eobp)))
1862 (forward-line 1))
1863 (if (eobp)
1864 (progn (goto-char start) nil)
1865 t)))
1866
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001867;; go to start of statement, at or preceding point, starting with
1868;; keyword KEY. Skips blank lines and non-indenting comments upward
1869;; first. If that statement starts with KEY, done, else go back to
1870;; first enclosing block starting with KEY. If successful, leaves
1871;; point at the start of the KEY line & returns t. Else leaves point
1872;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001873(defun py-go-up-tree-to-keyword (key)
1874 ;; skip blanks and non-indenting #
1875 (py-goto-initial-line)
1876 (while (and
1877 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1878 (zerop (forward-line -1))) ; go back
1879 nil)
1880 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001881 (let* ((re (concat "[ \t]*" key "\\b"))
1882 (case-fold-search nil) ; let* so looking-at sees this
1883 (found (looking-at re))
1884 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885 (while (not (or found dead))
1886 (condition-case nil ; in case no enclosing block
1887 (py-goto-block-up 'no-mark)
1888 (error (setq dead t)))
1889 (or dead (setq found (looking-at re))))
1890 (beginning-of-line)
1891 found))
1892
1893;; return string in buffer from start of indentation to end of line;
1894;; prefix "..." if leading whitespace was skipped
1895(defun py-suck-up-leading-text ()
1896 (save-excursion
1897 (back-to-indentation)
1898 (concat
1899 (if (bolp) "" "...")
1900 (buffer-substring (point) (progn (end-of-line) (point))))))
1901
1902;; assuming point at bolp, return first keyword ([a-z]+) on the line,
1903;; as a Lisp symbol; return nil if none
1904(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001905 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001906 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
1907 (intern (buffer-substring (match-beginning 1) (match-end 1)))
1908 nil)))
1909
1910(defun py-make-temp-name ()
1911 (make-temp-name
1912 (concat (file-name-as-directory py-temp-directory) "python")))
1913
1914(defun py-delete-file-silently (fname)
1915 (condition-case nil
1916 (delete-file fname)
1917 (error nil)))
1918
1919(defun py-kill-emacs-hook ()
1920 ;; delete our temp files
1921 (while py-file-queue
1922 (py-delete-file-silently (car py-file-queue))
1923 (setq py-file-queue (cdr py-file-queue)))
1924 (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
1925 ;; run the hook we inherited, if any
1926 (and py-inherited-kill-emacs-hook
1927 (funcall py-inherited-kill-emacs-hook))))
1928
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929;; make PROCESS's buffer visible, append STRING to it, and force
1930;; display; also make shell-mode believe the user typed this string,
1931;; so that kill-output-from-shell and show-output-from-shell work
1932;; "right"
Barry Warsaw7ae77681994-12-12 20:38:05 +00001933(defun py-append-to-process-buffer (process string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001934 (let ((cbuf (current-buffer))
1935 (pbuf (process-buffer process))
1936 (py-scroll-process-buffer t))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937 (set-buffer pbuf)
1938 (goto-char (point-max))
1939 (move-marker (process-mark process) (point))
1940 (if (not py-this-is-emacs-19-p)
1941 (move-marker last-input-start (point))) ; muck w/ shell-mode
1942 (funcall (process-filter process) process string)
1943 (if (not py-this-is-emacs-19-p)
1944 (move-marker last-input-end (point))) ; muck w/ shell-mode
1945 (set-buffer cbuf))
1946 (sit-for 0))
1947
Barry Warsaw74d9cc51995-03-08 22:05:16 +00001948(defun py-keep-region-active ()
1949 ;; do whatever is necessary to keep the region active in XEmacs.
1950 ;; Ignore byte-compiler warnings you might see. Also note that
1951 ;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
1952 ;; require us to take explicit action.
1953 (and (boundp 'zmacs-region-stays)
1954 (setq zmacs-region-stays t)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001955
1956
Barry Warsaw850437a1995-03-08 21:50:28 +00001957(defconst py-version "$Revision$"
1958 "`python-mode' version number.")
1959(defconst py-help-address "bwarsaw@cnri.reston.va.us"
1960 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961
Barry Warsaw850437a1995-03-08 21:50:28 +00001962(defun py-version ()
1963 "Echo the current version of `python-mode' in the minibuffer."
1964 (interactive)
1965 (message "Using `python-mode' version %s" py-version)
1966 (py-keep-region-active))
1967
1968;; only works under Emacs 19
1969;(eval-when-compile
1970; (require 'reporter))
1971
1972(defun py-submit-bug-report (enhancement-p)
1973 "Submit via mail a bug report on `python-mode'.
1974With \\[universal-argument] just submit an enhancement request."
1975 (interactive
1976 (list (not (y-or-n-p
1977 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001978 (let ((reporter-prompt-for-summary-p (if enhancement-p
1979 "(Very) brief summary: "
1980 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00001981 (require 'reporter)
1982 (reporter-submit-bug-report
1983 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00001984 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00001985 ;; varlist
1986 (if enhancement-p nil
1987 '(py-python-command
1988 py-indent-offset
1989 py-block-comment-prefix
1990 py-scroll-process-buffer
1991 py-temp-directory
1992 py-beep-if-tab-change))
1993 nil ;pre-hooks
1994 nil ;post-hooks
1995 "Dear Barry,") ;salutation
1996 (if enhancement-p nil
1997 (set-mark (point))
1998 (insert
1999"Please replace this text with a sufficiently large code sample\n\
2000and an exact recipe so that I can reproduce your problem. Failure\n\
2001to do so may mean a greater delay in fixing your bug.\n\n")
2002 (exchange-point-and-mark)
2003 (py-keep-region-active))))
2004
2005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002006;; arrange to kill temp files when Emacs exists
2007(if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
2008 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
2009 ;; have to trust that other people are as respectful of our hook
2010 ;; fiddling as we are of theirs
2011 (if (boundp 'py-inherited-kill-emacs-hook)
2012 ;; we were loaded before -- trust others not to have screwed us
2013 ;; in the meantime (no choice, really)
2014 nil
2015 ;; else arrange for our hook to run theirs
2016 (setq py-inherited-kill-emacs-hook kill-emacs-hook)
2017 (setq kill-emacs-hook 'py-kill-emacs-hook)))
2018
2019
2020
2021(provide 'python-mode)
2022;;; python-mode.el ends here