comparison .elisp/python-mode.el @ 19:b5d75594b356

Add support for the ipython-mode stuff and remove vestigial pymacs code.
author Augie Fackler <durin42@gmail.com>
date Mon, 08 Dec 2008 10:58:06 -0600
parents
children 014e745b2d04
comparison
equal deleted inserted replaced
18:30467b2328cb 19:b5d75594b356
1 ;;; python-mode.el --- Major mode for editing Python programs
2
3 ;; Copyright (C) 1992,1993,1994 Tim Peters
4
5 ;; Author: 2003-2004 http://sf.net/projects/python-mode
6 ;; 1995-2002 Barry A. Warsaw
7 ;; 1992-1994 Tim Peters
8 ;; Maintainer: python-mode@python.org
9 ;; Created: Feb 1992
10 ;; Keywords: python languages oop
11
12 (defconst py-version "$Revision: 4.75 $"
13 "`python-mode' version number.")
14
15 ;; This software is provided as-is, without express or implied
16 ;; warranty. Permission to use, copy, modify, distribute or sell this
17 ;; software, without fee, for any purpose and by any individual or
18 ;; organization, is hereby granted, provided that the above copyright
19 ;; notice and this paragraph appear in all copies.
20
21 ;;; Commentary:
22
23 ;; This is a major mode for editing Python programs. It was developed by Tim
24 ;; Peters after an original idea by Michael A. Guravage. Tim subsequently
25 ;; left the net and in 1995, Barry Warsaw inherited the mode. Tim's now back
26 ;; but disavows all responsibility for the mode. In fact, we suspect he
27 ;; doesn't even use Emacs any more. In 2003, python-mode.el was moved to its
28 ;; own SourceForge project apart from the Python project, and now is
29 ;; maintained by the volunteers at the python-mode@python.org mailing list.
30
31 ;; pdbtrack support contributed by Ken Manheimer, April 2001. Skip Montanaro
32 ;; has also contributed significantly to python-mode's development.
33
34 ;; Please use the SourceForge Python project to submit bugs or
35 ;; patches:
36 ;;
37 ;; http://sourceforge.net/projects/python
38
39 ;; INSTALLATION:
40
41 ;; To install, just drop this file into a directory on your load-path and
42 ;; byte-compile it. To set up Emacs to automatically edit files ending in
43 ;; ".py" using python-mode add the following to your ~/.emacs file (GNU
44 ;; Emacs) or ~/.xemacs/init.el file (XEmacs):
45 ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
46 ;; (setq interpreter-mode-alist (cons '("python" . python-mode)
47 ;; interpreter-mode-alist))
48 ;; (autoload 'python-mode "python-mode" "Python editing mode." t)
49 ;;
50 ;; In XEmacs syntax highlighting should be enabled automatically. In GNU
51 ;; Emacs you may have to add these lines to your ~/.emacs file:
52 ;; (global-font-lock-mode t)
53 ;; (setq font-lock-maximum-decoration t)
54
55 ;; FOR MORE INFORMATION:
56
57 ;; There is some information on python-mode.el at
58
59 ;; http://www.python.org/emacs/python-mode/
60 ;;
61 ;; It does contain links to other packages that you might find useful,
62 ;; such as pdb interfaces, OO-Browser links, etc.
63
64 ;; BUG REPORTING:
65
66 ;; As mentioned above, please use the SourceForge Python project for
67 ;; submitting bug reports or patches. The old recommendation, to use
68 ;; C-c C-b will still work, but those reports have a higher chance of
69 ;; getting buried in my mailbox. Please include a complete, but
70 ;; concise code sample and a recipe for reproducing the bug. Send
71 ;; suggestions and other comments to python-mode@python.org.
72
73 ;; When in a Python mode buffer, do a C-h m for more help. It's
74 ;; doubtful that a texinfo manual would be very useful, but if you
75 ;; want to contribute one, I'll certainly accept it!
76
77 ;;; Code:
78
79 (require 'comint)
80 (require 'custom)
81 (require 'cl)
82 (require 'compile)
83 (require 'ansi-color)
84
85
86 ;; user definable variables
87 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
88
89 (defgroup python nil
90 "Support for the Python programming language, <http://www.python.org/>"
91 :group 'languages
92 :prefix "py-")
93
94 (defcustom py-tab-always-indent t
95 "*Non-nil means TAB in Python mode should always reindent the current line,
96 regardless of where in the line point is when the TAB command is used."
97 :type 'boolean
98 :group 'python)
99
100 (defcustom py-python-command "python"
101 "*Shell command used to start Python interpreter."
102 :type 'string
103 :group 'python)
104
105 (make-obsolete-variable 'py-jpython-command 'py-jython-command)
106 (defcustom py-jython-command "jython"
107 "*Shell command used to start the Jython interpreter."
108 :type 'string
109 :group 'python
110 :tag "Jython Command")
111
112 (defcustom py-default-interpreter 'cpython
113 "*Which Python interpreter is used by default.
114 The value for this variable can be either `cpython' or `jython'.
115
116 When the value is `cpython', the variables `py-python-command' and
117 `py-python-command-args' are consulted to determine the interpreter
118 and arguments to use.
119
120 When the value is `jython', the variables `py-jython-command' and
121 `py-jython-command-args' are consulted to determine the interpreter
122 and arguments to use.
123
124 Note that this variable is consulted only the first time that a Python
125 mode buffer is visited during an Emacs session. After that, use
126 \\[py-toggle-shells] to change the interpreter shell."
127 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
128 (const :tag "Jython" jython))
129 :group 'python)
130
131 (defcustom py-python-command-args '("-i")
132 "*List of string arguments to be used when starting a Python shell."
133 :type '(repeat string)
134 :group 'python)
135
136 (make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args)
137 (defcustom py-jython-command-args '("-i")
138 "*List of string arguments to be used when starting a Jython shell."
139 :type '(repeat string)
140 :group 'python
141 :tag "Jython Command Args")
142
143 (defcustom py-indent-offset 4
144 "*Amount of offset per level of indentation.
145 `\\[py-guess-indent-offset]' can usually guess a good value when
146 you're editing someone else's Python code."
147 :type 'integer
148 :group 'python)
149
150 (defcustom py-continuation-offset 4
151 "*Additional amount of offset to give for some continuation lines.
152 Continuation lines are those that immediately follow a backslash
153 terminated line. Only those continuation lines for a block opening
154 statement are given this extra offset."
155 :type 'integer
156 :group 'python)
157
158 (defcustom py-smart-indentation t
159 "*Should `python-mode' try to automagically set some indentation variables?
160 When this variable is non-nil, two things happen when a buffer is set
161 to `python-mode':
162
163 1. `py-indent-offset' is guessed from existing code in the buffer.
164 Only guessed values between 2 and 8 are considered. If a valid
165 guess can't be made (perhaps because you are visiting a new
166 file), then the value in `py-indent-offset' is used.
167
168 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
169 equal `tab-width' (`indent-tabs-mode' is never turned on by
170 Python mode). This means that for newly written code, tabs are
171 only inserted in indentation if one tab is one indentation
172 level, otherwise only spaces are used.
173
174 Note that both these settings occur *after* `python-mode-hook' is run,
175 so if you want to defeat the automagic configuration, you must also
176 set `py-smart-indentation' to nil in your `python-mode-hook'."
177 :type 'boolean
178 :group 'python)
179
180 (defcustom py-align-multiline-strings-p t
181 "*Flag describing how multi-line triple quoted strings are aligned.
182 When this flag is non-nil, continuation lines are lined up under the
183 preceding line's indentation. When this flag is nil, continuation
184 lines are aligned to column zero."
185 :type '(choice (const :tag "Align under preceding line" t)
186 (const :tag "Align to column zero" nil))
187 :group 'python)
188
189 (defcustom py-block-comment-prefix "##"
190 "*String used by \\[comment-region] to comment out a block of code.
191 This should follow the convention for non-indenting comment lines so
192 that the indentation commands won't get confused (i.e., the string
193 should be of the form `#x...' where `x' is not a blank or a tab, and
194 `...' is arbitrary). However, this string should not end in whitespace."
195 :type 'string
196 :group 'python)
197
198 (defcustom py-honor-comment-indentation t
199 "*Controls how comment lines influence subsequent indentation.
200
201 When nil, all comment lines are skipped for indentation purposes, and
202 if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
203
204 When t, lines that begin with a single `#' are a hint to subsequent
205 line indentation. If the previous line is such a comment line (as
206 opposed to one that starts with `py-block-comment-prefix'), then its
207 indentation is used as a hint for this line's indentation. Lines that
208 begin with `py-block-comment-prefix' are ignored for indentation
209 purposes.
210
211 When not nil or t, comment lines that begin with a single `#' are used
212 as indentation hints, unless the comment character is in column zero."
213 :type '(choice
214 (const :tag "Skip all comment lines (fast)" nil)
215 (const :tag "Single # `sets' indentation for next line" t)
216 (const :tag "Single # `sets' indentation except at column zero"
217 other)
218 )
219 :group 'python)
220
221 (defcustom py-temp-directory
222 (let ((ok '(lambda (x)
223 (and x
224 (setq x (expand-file-name x)) ; always true
225 (file-directory-p x)
226 (file-writable-p x)
227 x))))
228 (or (funcall ok (getenv "TMPDIR"))
229 (funcall ok "/usr/tmp")
230 (funcall ok "/tmp")
231 (funcall ok "/var/tmp")
232 (funcall ok ".")
233 (error
234 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
235 "*Directory used for temporary files created by a *Python* process.
236 By default, the first directory from this list that exists and that you
237 can write into: the value (if any) of the environment variable TMPDIR,
238 /usr/tmp, /tmp, /var/tmp, or the current directory."
239 :type 'string
240 :group 'python)
241
242 (defcustom py-beep-if-tab-change t
243 "*Ring the bell if `tab-width' is changed.
244 If a comment of the form
245
246 \t# vi:set tabsize=<number>:
247
248 is found before the first code line when the file is entered, and the
249 current value of (the general Emacs variable) `tab-width' does not
250 equal <number>, `tab-width' is set to <number>, a message saying so is
251 displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
252 the Emacs bell is also rung as a warning."
253 :type 'boolean
254 :group 'python)
255
256 (defcustom py-jump-on-exception t
257 "*Jump to innermost exception frame in *Python Output* buffer.
258 When this variable is non-nil and an exception occurs when running
259 Python code synchronously in a subprocess, jump immediately to the
260 source code of the innermost traceback frame."
261 :type 'boolean
262 :group 'python)
263
264 (defcustom py-ask-about-save t
265 "If not nil, ask about which buffers to save before executing some code.
266 Otherwise, all modified buffers are saved without asking."
267 :type 'boolean
268 :group 'python)
269
270 (defcustom py-backspace-function 'backward-delete-char-untabify
271 "*Function called by `py-electric-backspace' when deleting backwards."
272 :type 'function
273 :group 'python)
274
275 (defcustom py-delete-function 'delete-char
276 "*Function called by `py-electric-delete' when deleting forwards."
277 :type 'function
278 :group 'python)
279
280 (defcustom py-imenu-show-method-args-p nil
281 "*Controls echoing of arguments of functions & methods in the Imenu buffer.
282 When non-nil, arguments are printed."
283 :type 'boolean
284 :group 'python)
285 (make-variable-buffer-local 'py-indent-offset)
286
287 (defcustom py-pdbtrack-do-tracking-p t
288 "*Controls whether the pdbtrack feature is enabled or not.
289 When non-nil, pdbtrack is enabled in all comint-based buffers,
290 e.g. shell buffers and the *Python* buffer. When using pdb to debug a
291 Python program, pdbtrack notices the pdb prompt and displays the
292 source file and line that the program is stopped at, much the same way
293 as gud-mode does for debugging C programs with gdb."
294 :type 'boolean
295 :group 'python)
296 (make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
297
298 (defcustom py-pdbtrack-minor-mode-string " PDB"
299 "*String to use in the minor mode list when pdbtrack is enabled."
300 :type 'string
301 :group 'python)
302
303 (defcustom py-import-check-point-max
304 20000
305 "Maximum number of characters to search for a Java-ish import statement.
306 When `python-mode' tries to calculate the shell to use (either a
307 CPython or a Jython shell), it looks at the so-called `shebang' line
308 -- i.e. #! line. If that's not available, it looks at some of the
309 file heading imports to see if they look Java-like."
310 :type 'integer
311 :group 'python
312 )
313
314 (make-obsolete-variable 'py-jpython-packages 'py-jython-packages)
315 (defcustom py-jython-packages
316 '("java" "javax" "org" "com")
317 "Imported packages that imply `jython-mode'."
318 :type '(repeat string)
319 :group 'python)
320
321 ;; Not customizable
322 (defvar py-master-file nil
323 "If non-nil, execute the named file instead of the buffer's file.
324 The intent is to allow you to set this variable in the file's local
325 variable section, e.g.:
326
327 # Local Variables:
328 # py-master-file: \"master.py\"
329 # End:
330
331 so that typing \\[py-execute-buffer] in that buffer executes the named
332 master file instead of the buffer's file. If the file name has a
333 relative path, the value of variable `default-directory' for the
334 buffer is prepended to come up with a file name.")
335 (make-variable-buffer-local 'py-master-file)
336
337 (defcustom py-pychecker-command "pychecker"
338 "*Shell command used to run Pychecker."
339 :type 'string
340 :group 'python
341 :tag "Pychecker Command")
342
343 (defcustom py-pychecker-command-args '("--stdlib")
344 "*List of string arguments to be passed to pychecker."
345 :type '(repeat string)
346 :group 'python
347 :tag "Pychecker Command Args")
348
349 (defvar py-shell-alist
350 '(("jython" . 'jython)
351 ("python" . 'cpython))
352 "*Alist of interpreters and python shells. Used by `py-choose-shell'
353 to select the appropriate python interpreter mode for a file.")
354
355 (defcustom py-shell-input-prompt-1-regexp "^>>> "
356 "*A regular expression to match the input prompt of the shell."
357 :type 'string
358 :group 'python)
359
360 (defcustom py-shell-input-prompt-2-regexp "^[.][.][.] "
361 "*A regular expression to match the input prompt of the shell after the
362 first line of input."
363 :type 'string
364 :group 'python)
365
366 (defcustom py-shell-switch-buffers-on-execute t
367 "*Controls switching to the Python buffer where commands are
368 executed. When non-nil the buffer switches to the Python buffer, if
369 not no switching occurs."
370 :type 'boolean
371 :group 'python)
372
373
374 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
375 ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
376
377 (defvar py-line-number-offset 0
378 "When an exception occurs as a result of py-execute-region, a
379 subsequent py-up-exception needs the line number where the region
380 started, in order to jump to the correct file line. This variable is
381 set in py-execute-region and used in py-jump-to-exception.")
382
383 (defconst py-emacs-features
384 (let (features)
385 features)
386 "A list of features extant in the Emacs you are using.
387 There are many flavors of Emacs out there, with different levels of
388 support for features needed by `python-mode'.")
389
390 ;; Face for None, True, False, self, and Ellipsis
391 (defvar py-pseudo-keyword-face 'py-pseudo-keyword-face
392 "Face for pseudo keywords in Python mode, like self, True, False, Ellipsis.")
393 (make-face 'py-pseudo-keyword-face)
394
395 ;; PEP 318 decorators
396 (defvar py-decorators-face 'py-decorators-face
397 "Face method decorators.")
398 (make-face 'py-decorators-face)
399
400 ;; Face for builtins
401 (defvar py-builtins-face 'py-builtins-face
402 "Face for builtins like TypeError, object, open, and exec.")
403 (make-face 'py-builtins-face)
404
405 (defun py-font-lock-mode-hook ()
406 (or (face-differs-from-default-p 'py-pseudo-keyword-face)
407 (copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face))
408 (or (face-differs-from-default-p 'py-builtins-face)
409 (copy-face 'font-lock-keyword-face 'py-builtins-face))
410 (or (face-differs-from-default-p 'py-decorators-face)
411 (copy-face 'py-pseudo-keyword-face 'py-decorators-face))
412 )
413 (add-hook 'font-lock-mode-hook 'py-font-lock-mode-hook)
414
415 (defvar python-font-lock-keywords
416 (let ((kw1 (mapconcat 'identity
417 '("and" "assert" "break" "class"
418 "continue" "def" "del" "elif"
419 "else" "except" "exec" "for"
420 "from" "global" "if" "import"
421 "in" "is" "lambda" "not"
422 "or" "pass" "print" "raise"
423 "return" "while" "yield"
424 )
425 "\\|"))
426 (kw2 (mapconcat 'identity
427 '("else:" "except:" "finally:" "try:")
428 "\\|"))
429 (kw3 (mapconcat 'identity
430 ;; Don't include True, False, None, or
431 ;; Ellipsis in this list, since they are
432 ;; already defined as pseudo keywords.
433 '("__debug__"
434 "__import__" "__name__" "abs" "apply" "basestring"
435 "bool" "buffer" "callable" "chr" "classmethod"
436 "cmp" "coerce" "compile" "complex" "copyright"
437 "delattr" "dict" "dir" "divmod"
438 "enumerate" "eval" "execfile" "exit" "file"
439 "filter" "float" "getattr" "globals" "hasattr"
440 "hash" "hex" "id" "input" "int" "intern"
441 "isinstance" "issubclass" "iter" "len" "license"
442 "list" "locals" "long" "map" "max" "min" "object"
443 "oct" "open" "ord" "pow" "property" "range"
444 "raw_input" "reduce" "reload" "repr" "round"
445 "setattr" "slice" "staticmethod" "str" "sum"
446 "super" "tuple" "type" "unichr" "unicode" "vars"
447 "xrange" "zip")
448 "\\|"))
449 (kw4 (mapconcat 'identity
450 ;; Exceptions and warnings
451 '("ArithmeticError" "AssertionError"
452 "AttributeError" "DeprecationWarning" "EOFError"
453 "EnvironmentError" "Exception"
454 "FloatingPointError" "FutureWarning" "IOError"
455 "ImportError" "IndentationError" "IndexError"
456 "KeyError" "KeyboardInterrupt" "LookupError"
457 "MemoryError" "NameError" "NotImplemented"
458 "NotImplementedError" "OSError" "OverflowError"
459 "OverflowWarning" "PendingDeprecationWarning"
460 "ReferenceError" "RuntimeError" "RuntimeWarning"
461 "StandardError" "StopIteration" "SyntaxError"
462 "SyntaxWarning" "SystemError" "SystemExit"
463 "TabError" "TypeError" "UnboundLocalError"
464 "UnicodeDecodeError" "UnicodeEncodeError"
465 "UnicodeError" "UnicodeTranslateError"
466 "UserWarning" "ValueError" "Warning"
467 "ZeroDivisionError")
468 "\\|"))
469 )
470 (list
471 '("^[ \t]*\\(@.+\\)" 1 'py-decorators-face)
472 ;; keywords
473 (cons (concat "\\<\\(" kw1 "\\)\\>[ \n\t(]") 1)
474 ;; builtins when they don't appear as object attributes
475 (list (concat "\\([^. \t]\\|^\\)[ \t]*\\<\\(" kw3 "\\)\\>[ \n\t(]") 2
476 'py-builtins-face)
477 ;; block introducing keywords with immediately following colons.
478 ;; Yes "except" is in both lists.
479 (cons (concat "\\<\\(" kw2 "\\)[ \n\t(]") 1)
480 ;; Exceptions
481 (list (concat "\\<\\(" kw4 "\\)[ \n\t:,(]") 1 'py-builtins-face)
482 ;; `as' but only in "import foo as bar"
483 '("[ \t]*\\(\\<from\\>.*\\)?\\<import\\>.*\\<\\(as\\)\\>" . 2)
484
485 ;; classes
486 '("\\<class[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" 1 font-lock-type-face)
487 ;; functions
488 '("\\<def[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
489 1 font-lock-function-name-face)
490 ;; pseudo-keywords
491 '("\\<\\(self\\|None\\|True\\|False\\|Ellipsis\\)\\>"
492 1 py-pseudo-keyword-face)
493 ))
494 "Additional expressions to highlight in Python mode.")
495 (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
496
497 ;; have to bind py-file-queue before installing the kill-emacs-hook
498 (defvar py-file-queue nil
499 "Queue of Python temp files awaiting execution.
500 Currently-active file is at the head of the list.")
501
502 (defvar py-pdbtrack-is-tracking-p nil)
503
504 (defvar py-pychecker-history nil)
505
506
507
508 ;; Constants
509
510 (defconst py-stringlit-re
511 (concat
512 ;; These fail if backslash-quote ends the string (not worth
513 ;; fixing?). They precede the short versions so that the first two
514 ;; quotes don't look like an empty short string.
515 ;;
516 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
517 ;; with potential embedded single quotes
518 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
519 "\\|"
520 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
521 ;; with potential embedded double quotes
522 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
523 "\\|"
524 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
525 "\\|" ; or
526 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
527 )
528 "Regular expression matching a Python string literal.")
529
530 (defconst py-continued-re
531 ;; This is tricky because a trailing backslash does not mean
532 ;; continuation if it's in a comment
533 (concat
534 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
535 "\\\\$")
536 "Regular expression matching Python backslash continuation lines.")
537
538 (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
539 "Regular expression matching a blank or comment line.")
540
541 (defconst py-outdent-re
542 (concat "\\(" (mapconcat 'identity
543 '("else:"
544 "except\\(\\s +.*\\)?:"
545 "finally:"
546 "elif\\s +.*:")
547 "\\|")
548 "\\)")
549 "Regular expression matching statements to be dedented one level.")
550
551 (defconst py-block-closing-keywords-re
552 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
553 "Regular expression matching keywords which typically close a block.")
554
555 (defconst py-no-outdent-re
556 (concat
557 "\\("
558 (mapconcat 'identity
559 (list "try:"
560 "except\\(\\s +.*\\)?:"
561 "while\\s +.*:"
562 "for\\s +.*:"
563 "if\\s +.*:"
564 "elif\\s +.*:"
565 (concat py-block-closing-keywords-re "[ \t\n]")
566 )
567 "\\|")
568 "\\)")
569 "Regular expression matching lines not to dedent after.")
570
571 (defvar py-traceback-line-re
572 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
573 "Regular expression that describes tracebacks.")
574
575 ;; pdbtrack constants
576 (defconst py-pdbtrack-stack-entry-regexp
577 ; "^> \\([^(]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
578 "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
579 "Regular expression pdbtrack uses to find a stack trace entry.")
580
581 (defconst py-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
582 "Regular expression pdbtrack uses to recognize a pdb prompt.")
583
584 (defconst py-pdbtrack-track-range 10000
585 "Max number of characters from end of buffer to search for stack entry.")
586
587
588
589 ;; Major mode boilerplate
590
591 ;; define a mode-specific abbrev table for those who use such things
592 (defvar python-mode-abbrev-table nil
593 "Abbrev table in use in `python-mode' buffers.")
594 (define-abbrev-table 'python-mode-abbrev-table nil)
595
596 (defvar python-mode-hook nil
597 "*Hook called by `python-mode'.")
598
599 (make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook)
600 (defvar jython-mode-hook nil
601 "*Hook called by `jython-mode'. `jython-mode' also calls
602 `python-mode-hook'.")
603
604 (defvar py-shell-hook nil
605 "*Hook called by `py-shell'.")
606
607 ;; In previous version of python-mode.el, the hook was incorrectly
608 ;; called py-mode-hook, and was not defvar'd. Deprecate its use.
609 (and (fboundp 'make-obsolete-variable)
610 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
611
612 (defvar py-mode-map ()
613 "Keymap used in `python-mode' buffers.")
614 (if py-mode-map
615 nil
616 (setq py-mode-map (make-sparse-keymap))
617 ;; electric keys
618 (define-key py-mode-map ":" 'py-electric-colon)
619 ;; indentation level modifiers
620 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
621 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
622 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
623 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
624 ;; subprocess commands
625 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
626 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
627 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
628 (define-key py-mode-map "\C-c|" 'py-execute-region)
629 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
630 (define-key py-mode-map "\C-c!" 'py-shell)
631 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
632 ;; Caution! Enter here at your own risk. We are trying to support
633 ;; several behaviors and it gets disgusting. :-( This logic ripped
634 ;; largely from CC Mode.
635 ;;
636 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
637 ;; backwards deletion behavior to DEL, which both Delete and
638 ;; Backspace get translated to. There's no way to separate this
639 ;; behavior in a clean way, so deal with it! Besides, it's been
640 ;; this way since the dawn of time.
641 (if (not (boundp 'delete-key-deletes-forward))
642 (define-key py-mode-map "\177" 'py-electric-backspace)
643 ;; However, XEmacs 20 actually achieved enlightenment. It is
644 ;; possible to sanely define both backward and forward deletion
645 ;; behavior under X separately (TTYs are forever beyond hope, but
646 ;; who cares? XEmacs 20 does the right thing with these too).
647 (define-key py-mode-map [delete] 'py-electric-delete)
648 (define-key py-mode-map [backspace] 'py-electric-backspace))
649 ;; Separate M-BS from C-M-h. The former should remain
650 ;; backward-kill-word.
651 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
652 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
653 ;; Miscellaneous
654 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
655 (define-key py-mode-map "\C-c\t" 'py-indent-region)
656 (define-key py-mode-map "\C-c\C-d" 'py-pdbtrack-toggle-stack-tracking)
657 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
658 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
659 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
660 (define-key py-mode-map "\C-c#" 'py-comment-region)
661 (define-key py-mode-map "\C-c?" 'py-describe-mode)
662 (define-key py-mode-map "\C-c\C-h" 'py-help-at-point)
663 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
664 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
665 (define-key py-mode-map "\C-c-" 'py-up-exception)
666 (define-key py-mode-map "\C-c=" 'py-down-exception)
667 ;; stuff that is `standard' but doesn't interface well with
668 ;; python-mode, which forces us to rebind to special commands
669 (define-key py-mode-map "\C-xnd" 'py-narrow-to-defun)
670 ;; information
671 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
672 (define-key py-mode-map "\C-c\C-v" 'py-version)
673 (define-key py-mode-map "\C-c\C-w" 'py-pychecker-run)
674 ;; shadow global bindings for newline-and-indent w/ the py- version.
675 ;; BAW - this is extremely bad form, but I'm not going to change it
676 ;; for now.
677 (mapcar #'(lambda (key)
678 (define-key py-mode-map key 'py-newline-and-indent))
679 (where-is-internal 'newline-and-indent))
680 ;; Force RET to be py-newline-and-indent even if it didn't get
681 ;; mapped by the above code. motivation: Emacs' default binding for
682 ;; RET is `newline' and C-j is `newline-and-indent'. Most Pythoneers
683 ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
684 ;; dislike this are probably knowledgeable enough to do a rebind.
685 ;; However, we do *not* change C-j since many Emacsers have already
686 ;; swapped RET and C-j and they don't want C-j bound to `newline' to
687 ;; change.
688 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
689 )
690
691 (defvar py-mode-output-map nil
692 "Keymap used in *Python Output* buffers.")
693 (if py-mode-output-map
694 nil
695 (setq py-mode-output-map (make-sparse-keymap))
696 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
697 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
698 ;; TBD: Disable all self-inserting keys. This is bogus, we should
699 ;; really implement this as *Python Output* buffer being read-only
700 (mapcar #' (lambda (key)
701 (define-key py-mode-output-map key
702 #'(lambda () (interactive) (beep))))
703 (where-is-internal 'self-insert-command))
704 )
705
706 (defvar py-shell-map nil
707 "Keymap used in *Python* shell buffers.")
708 (if py-shell-map
709 nil
710 (setq py-shell-map (copy-keymap comint-mode-map))
711 (define-key py-shell-map [tab] 'tab-to-tab-stop)
712 (define-key py-shell-map "\C-c-" 'py-up-exception)
713 (define-key py-shell-map "\C-c=" 'py-down-exception)
714 )
715
716 (defvar py-mode-syntax-table nil
717 "Syntax table used in `python-mode' buffers.")
718 (when (not py-mode-syntax-table)
719 (setq py-mode-syntax-table (make-syntax-table))
720 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
721 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
722 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
723 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
724 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
725 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
726 ;; Add operator symbols misassigned in the std table
727 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
728 (modify-syntax-entry ?\% "." py-mode-syntax-table)
729 (modify-syntax-entry ?\& "." py-mode-syntax-table)
730 (modify-syntax-entry ?\* "." py-mode-syntax-table)
731 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
732 (modify-syntax-entry ?\- "." py-mode-syntax-table)
733 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
734 (modify-syntax-entry ?\< "." py-mode-syntax-table)
735 (modify-syntax-entry ?\= "." py-mode-syntax-table)
736 (modify-syntax-entry ?\> "." py-mode-syntax-table)
737 (modify-syntax-entry ?\| "." py-mode-syntax-table)
738 ;; For historical reasons, underscore is word class instead of
739 ;; symbol class. GNU conventions say it should be symbol class, but
740 ;; there's a natural conflict between what major mode authors want
741 ;; and what users expect from `forward-word' and `backward-word'.
742 ;; Guido and I have hashed this out and have decided to keep
743 ;; underscore in word class. If you're tempted to change it, try
744 ;; binding M-f and M-b to py-forward-into-nomenclature and
745 ;; py-backward-into-nomenclature instead. This doesn't help in all
746 ;; situations where you'd want the different behavior
747 ;; (e.g. backward-kill-word).
748 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
749 ;; Both single quote and double quote are string delimiters
750 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
751 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
752 ;; backquote is open and close paren
753 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
754 ;; comment delimiters
755 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
756 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
757 )
758
759 ;; An auxiliary syntax table which places underscore and dot in the
760 ;; symbol class for simplicity
761 (defvar py-dotted-expression-syntax-table nil
762 "Syntax table used to identify Python dotted expressions.")
763 (when (not py-dotted-expression-syntax-table)
764 (setq py-dotted-expression-syntax-table
765 (copy-syntax-table py-mode-syntax-table))
766 (modify-syntax-entry ?_ "_" py-dotted-expression-syntax-table)
767 (modify-syntax-entry ?. "_" py-dotted-expression-syntax-table))
768
769
770
771 ;; Utilities
772 (defmacro py-safe (&rest body)
773 "Safely execute BODY, return nil if an error occurred."
774 (` (condition-case nil
775 (progn (,@ body))
776 (error nil))))
777
778 (defsubst py-keep-region-active ()
779 "Keep the region active in XEmacs."
780 ;; Ignore byte-compiler warnings you might see. Also note that
781 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
782 ;; to take explicit action.
783 (and (boundp 'zmacs-region-stays)
784 (setq zmacs-region-stays t)))
785
786 (defsubst py-point (position)
787 "Returns the value of point at certain commonly referenced POSITIONs.
788 POSITION can be one of the following symbols:
789
790 bol -- beginning of line
791 eol -- end of line
792 bod -- beginning of def or class
793 eod -- end of def or class
794 bob -- beginning of buffer
795 eob -- end of buffer
796 boi -- back to indentation
797 bos -- beginning of statement
798
799 This function does not modify point or mark."
800 (let ((here (point)))
801 (cond
802 ((eq position 'bol) (beginning-of-line))
803 ((eq position 'eol) (end-of-line))
804 ((eq position 'bod) (py-beginning-of-def-or-class 'either))
805 ((eq position 'eod) (py-end-of-def-or-class 'either))
806 ;; Kind of funny, I know, but useful for py-up-exception.
807 ((eq position 'bob) (beginning-of-buffer))
808 ((eq position 'eob) (end-of-buffer))
809 ((eq position 'boi) (back-to-indentation))
810 ((eq position 'bos) (py-goto-initial-line))
811 (t (error "Unknown buffer position requested: %s" position))
812 )
813 (prog1
814 (point)
815 (goto-char here))))
816
817 (defsubst py-highlight-line (from to file line)
818 (cond
819 ((fboundp 'make-extent)
820 ;; XEmacs
821 (let ((e (make-extent from to)))
822 (set-extent-property e 'mouse-face 'highlight)
823 (set-extent-property e 'py-exc-info (cons file line))
824 (set-extent-property e 'keymap py-mode-output-map)))
825 (t
826 ;; Emacs -- Please port this!
827 )
828 ))
829
830 (defun py-in-literal (&optional lim)
831 "Return non-nil if point is in a Python literal (a comment or string).
832 Optional argument LIM indicates the beginning of the containing form,
833 i.e. the limit on how far back to scan."
834 ;; This is the version used for non-XEmacs, which has a nicer
835 ;; interface.
836 ;;
837 ;; WARNING: Watch out for infinite recursion.
838 (let* ((lim (or lim (py-point 'bod)))
839 (state (parse-partial-sexp lim (point))))
840 (cond
841 ((nth 3 state) 'string)
842 ((nth 4 state) 'comment)
843 (t nil))))
844
845 ;; XEmacs has a built-in function that should make this much quicker.
846 ;; In this case, lim is ignored
847 (defun py-fast-in-literal (&optional lim)
848 "Fast version of `py-in-literal', used only by XEmacs.
849 Optional LIM is ignored."
850 ;; don't have to worry about context == 'block-comment
851 (buffer-syntactic-context))
852
853 (if (fboundp 'buffer-syntactic-context)
854 (defalias 'py-in-literal 'py-fast-in-literal))
855
856
857
858 ;; Menu definitions, only relevent if you have the easymenu.el package
859 ;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
860 (defvar py-menu nil
861 "Menu for Python Mode.
862 This menu will get created automatically if you have the `easymenu'
863 package. Note that the latest X/Emacs releases contain this package.")
864
865 (and (py-safe (require 'easymenu) t)
866 (easy-menu-define
867 py-menu py-mode-map "Python Mode menu"
868 '("Python"
869 ["Comment Out Region" py-comment-region (mark)]
870 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
871 "-"
872 ["Mark current block" py-mark-block t]
873 ["Mark current def" py-mark-def-or-class t]
874 ["Mark current class" (py-mark-def-or-class t) t]
875 "-"
876 ["Shift region left" py-shift-region-left (mark)]
877 ["Shift region right" py-shift-region-right (mark)]
878 "-"
879 ["Import/reload file" py-execute-import-or-reload t]
880 ["Execute buffer" py-execute-buffer t]
881 ["Execute region" py-execute-region (mark)]
882 ["Execute def or class" py-execute-def-or-class (mark)]
883 ["Execute string" py-execute-string t]
884 ["Start interpreter..." py-shell t]
885 "-"
886 ["Go to start of block" py-goto-block-up t]
887 ["Go to start of class" (py-beginning-of-def-or-class t) t]
888 ["Move to end of class" (py-end-of-def-or-class t) t]
889 ["Move to start of def" py-beginning-of-def-or-class t]
890 ["Move to end of def" py-end-of-def-or-class t]
891 "-"
892 ["Describe mode" py-describe-mode t]
893 )))
894
895
896
897 ;; Imenu definitions
898 (defvar py-imenu-class-regexp
899 (concat ; <<classes>>
900 "\\(" ;
901 "^[ \t]*" ; newline and maybe whitespace
902 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
903 ; possibly multiple superclasses
904 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
905 "[ \t]*:" ; and the final :
906 "\\)" ; >>classes<<
907 )
908 "Regexp for Python classes for use with the Imenu package."
909 )
910
911 (defvar py-imenu-method-regexp
912 (concat ; <<methods and functions>>
913 "\\(" ;
914 "^[ \t]*" ; new line and maybe whitespace
915 "\\(def[ \t]+" ; function definitions start with def
916 "\\([a-zA-Z0-9_]+\\)" ; name is here
917 ; function arguments...
918 ;; "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
919 "[ \t]*(\\([^:#]*\\))"
920 "\\)" ; end of def
921 "[ \t]*:" ; and then the :
922 "\\)" ; >>methods and functions<<
923 )
924 "Regexp for Python methods/functions for use with the Imenu package."
925 )
926
927 (defvar py-imenu-method-no-arg-parens '(2 8)
928 "Indices into groups of the Python regexp for use with Imenu.
929
930 Using these values will result in smaller Imenu lists, as arguments to
931 functions are not listed.
932
933 See the variable `py-imenu-show-method-args-p' for more
934 information.")
935
936 (defvar py-imenu-method-arg-parens '(2 7)
937 "Indices into groups of the Python regexp for use with imenu.
938 Using these values will result in large Imenu lists, as arguments to
939 functions are listed.
940
941 See the variable `py-imenu-show-method-args-p' for more
942 information.")
943
944 ;; Note that in this format, this variable can still be used with the
945 ;; imenu--generic-function. Otherwise, there is no real reason to have
946 ;; it.
947 (defvar py-imenu-generic-expression
948 (cons
949 (concat
950 py-imenu-class-regexp
951 "\\|" ; or...
952 py-imenu-method-regexp
953 )
954 py-imenu-method-no-arg-parens)
955 "Generic Python expression which may be used directly with Imenu.
956 Used by setting the variable `imenu-generic-expression' to this value.
957 Also, see the function \\[py-imenu-create-index] for a better
958 alternative for finding the index.")
959
960 ;; These next two variables are used when searching for the Python
961 ;; class/definitions. Just saving some time in accessing the
962 ;; generic-python-expression, really.
963 (defvar py-imenu-generic-regexp nil)
964 (defvar py-imenu-generic-parens nil)
965
966
967 (defun py-imenu-create-index-function ()
968 "Python interface function for the Imenu package.
969 Finds all Python classes and functions/methods. Calls function
970 \\[py-imenu-create-index-engine]. See that function for the details
971 of how this works."
972 (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
973 py-imenu-generic-parens (if py-imenu-show-method-args-p
974 py-imenu-method-arg-parens
975 py-imenu-method-no-arg-parens))
976 (goto-char (point-min))
977 ;; Warning: When the buffer has no classes or functions, this will
978 ;; return nil, which seems proper according to the Imenu API, but
979 ;; causes an error in the XEmacs port of Imenu. Sigh.
980 (py-imenu-create-index-engine nil))
981
982 (defun py-imenu-create-index-engine (&optional start-indent)
983 "Function for finding Imenu definitions in Python.
984
985 Finds all definitions (classes, methods, or functions) in a Python
986 file for the Imenu package.
987
988 Returns a possibly nested alist of the form
989
990 (INDEX-NAME . INDEX-POSITION)
991
992 The second element of the alist may be an alist, producing a nested
993 list as in
994
995 (INDEX-NAME . INDEX-ALIST)
996
997 This function should not be called directly, as it calls itself
998 recursively and requires some setup. Rather this is the engine for
999 the function \\[py-imenu-create-index-function].
1000
1001 It works recursively by looking for all definitions at the current
1002 indention level. When it finds one, it adds it to the alist. If it
1003 finds a definition at a greater indentation level, it removes the
1004 previous definition from the alist. In its place it adds all
1005 definitions found at the next indentation level. When it finds a
1006 definition that is less indented then the current level, it returns
1007 the alist it has created thus far.
1008
1009 The optional argument START-INDENT indicates the starting indentation
1010 at which to continue looking for Python classes, methods, or
1011 functions. If this is not supplied, the function uses the indentation
1012 of the first definition found."
1013 (let (index-alist
1014 sub-method-alist
1015 looking-p
1016 def-name prev-name
1017 cur-indent def-pos
1018 (class-paren (first py-imenu-generic-parens))
1019 (def-paren (second py-imenu-generic-parens)))
1020 (setq looking-p
1021 (re-search-forward py-imenu-generic-regexp (point-max) t))
1022 (while looking-p
1023 (save-excursion
1024 ;; used to set def-name to this value but generic-extract-name
1025 ;; is new to imenu-1.14. this way it still works with
1026 ;; imenu-1.11
1027 ;;(imenu--generic-extract-name py-imenu-generic-parens))
1028 (let ((cur-paren (if (match-beginning class-paren)
1029 class-paren def-paren)))
1030 (setq def-name
1031 (buffer-substring-no-properties (match-beginning cur-paren)
1032 (match-end cur-paren))))
1033 (save-match-data
1034 (py-beginning-of-def-or-class 'either))
1035 (beginning-of-line)
1036 (setq cur-indent (current-indentation)))
1037 ;; HACK: want to go to the next correct definition location. We
1038 ;; explicitly list them here but it would be better to have them
1039 ;; in a list.
1040 (setq def-pos
1041 (or (match-beginning class-paren)
1042 (match-beginning def-paren)))
1043 ;; if we don't have a starting indent level, take this one
1044 (or start-indent
1045 (setq start-indent cur-indent))
1046 ;; if we don't have class name yet, take this one
1047 (or prev-name
1048 (setq prev-name def-name))
1049 ;; what level is the next definition on? must be same, deeper
1050 ;; or shallower indentation
1051 (cond
1052 ;; Skip code in comments and strings
1053 ((py-in-literal))
1054 ;; at the same indent level, add it to the list...
1055 ((= start-indent cur-indent)
1056 (push (cons def-name def-pos) index-alist))
1057 ;; deeper indented expression, recurse
1058 ((< start-indent cur-indent)
1059 ;; the point is currently on the expression we're supposed to
1060 ;; start on, so go back to the last expression. The recursive
1061 ;; call will find this place again and add it to the correct
1062 ;; list
1063 (re-search-backward py-imenu-generic-regexp (point-min) 'move)
1064 (setq sub-method-alist (py-imenu-create-index-engine cur-indent))
1065 (if sub-method-alist
1066 ;; we put the last element on the index-alist on the start
1067 ;; of the submethod alist so the user can still get to it.
1068 (let ((save-elmt (pop index-alist)))
1069 (push (cons prev-name
1070 (cons save-elmt sub-method-alist))
1071 index-alist))))
1072 ;; found less indented expression, we're done.
1073 (t
1074 (setq looking-p nil)
1075 (re-search-backward py-imenu-generic-regexp (point-min) t)))
1076 ;; end-cond
1077 (setq prev-name def-name)
1078 (and looking-p
1079 (setq looking-p
1080 (re-search-forward py-imenu-generic-regexp
1081 (point-max) 'move))))
1082 (nreverse index-alist)))
1083
1084
1085
1086 (defun py-choose-shell-by-shebang ()
1087 "Choose CPython or Jython mode by looking at #! on the first line.
1088 Returns the appropriate mode function.
1089 Used by `py-choose-shell', and similar to but distinct from
1090 `set-auto-mode', though it uses `auto-mode-interpreter-regexp' (if available)."
1091 ;; look for an interpreter specified in the first line
1092 ;; similar to set-auto-mode (files.el)
1093 (let* ((re (if (boundp 'auto-mode-interpreter-regexp)
1094 auto-mode-interpreter-regexp
1095 ;; stolen from Emacs 21.2
1096 "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1097 (interpreter (save-excursion
1098 (goto-char (point-min))
1099 (if (looking-at re)
1100 (match-string 2)
1101 "")))
1102 elt)
1103 ;; Map interpreter name to a mode.
1104 (setq elt (assoc (file-name-nondirectory interpreter)
1105 py-shell-alist))
1106 (and elt (caddr elt))))
1107
1108
1109
1110 (defun py-choose-shell-by-import ()
1111 "Choose CPython or Jython mode based imports.
1112 If a file imports any packages in `py-jython-packages', within
1113 `py-import-check-point-max' characters from the start of the file,
1114 return `jython', otherwise return nil."
1115 (let (mode)
1116 (save-excursion
1117 (goto-char (point-min))
1118 (while (and (not mode)
1119 (search-forward-regexp
1120 "^\\(\\(from\\)\\|\\(import\\)\\) \\([^ \t\n.]+\\)"
1121 py-import-check-point-max t))
1122 (setq mode (and (member (match-string 4) py-jython-packages)
1123 'jython
1124 ))))
1125 mode))
1126
1127
1128 (defun py-choose-shell ()
1129 "Choose CPython or Jython mode. Returns the appropriate mode function.
1130 This does the following:
1131 - look for an interpreter with `py-choose-shell-by-shebang'
1132 - examine imports using `py-choose-shell-by-import'
1133 - default to the variable `py-default-interpreter'"
1134 (interactive)
1135 (or (py-choose-shell-by-shebang)
1136 (py-choose-shell-by-import)
1137 py-default-interpreter
1138 ; 'cpython ;; don't use to py-default-interpreter, because default
1139 ; ;; is only way to choose CPython
1140 ))
1141
1142
1143 ;;;###autoload
1144 (defun python-mode ()
1145 "Major mode for editing Python files.
1146 To submit a problem report, enter `\\[py-submit-bug-report]' from a
1147 `python-mode' buffer. Do `\\[py-describe-mode]' for detailed
1148 documentation. To see what version of `python-mode' you are running,
1149 enter `\\[py-version]'.
1150
1151 This mode knows about Python indentation, tokens, comments and
1152 continuation lines. Paragraphs are separated by blank lines only.
1153
1154 COMMANDS
1155 \\{py-mode-map}
1156 VARIABLES
1157
1158 py-indent-offset\t\tindentation increment
1159 py-block-comment-prefix\t\tcomment string used by `comment-region'
1160 py-python-command\t\tshell command to invoke Python interpreter
1161 py-temp-directory\t\tdirectory used for temp files (if needed)
1162 py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
1163 (interactive)
1164 ;; set up local variables
1165 (kill-all-local-variables)
1166 (make-local-variable 'font-lock-defaults)
1167 (make-local-variable 'paragraph-separate)
1168 (make-local-variable 'paragraph-start)
1169 (make-local-variable 'require-final-newline)
1170 (make-local-variable 'comment-start)
1171 (make-local-variable 'comment-end)
1172 (make-local-variable 'comment-start-skip)
1173 (make-local-variable 'comment-column)
1174 (make-local-variable 'comment-indent-function)
1175 (make-local-variable 'indent-region-function)
1176 (make-local-variable 'indent-line-function)
1177 (make-local-variable 'add-log-current-defun-function)
1178 (make-local-variable 'fill-paragraph-function)
1179 ;;
1180 (set-syntax-table py-mode-syntax-table)
1181 (setq major-mode 'python-mode
1182 mode-name "Python"
1183 local-abbrev-table python-mode-abbrev-table
1184 font-lock-defaults '(python-font-lock-keywords)
1185 paragraph-separate "^[ \t]*$"
1186 paragraph-start "^[ \t]*$"
1187 require-final-newline t
1188 comment-start "# "
1189 comment-end ""
1190 comment-start-skip "# *"
1191 comment-column 40
1192 comment-indent-function 'py-comment-indent-function
1193 indent-region-function 'py-indent-region
1194 indent-line-function 'py-indent-line
1195 ;; tell add-log.el how to find the current function/method/variable
1196 add-log-current-defun-function 'py-current-defun
1197
1198 fill-paragraph-function 'py-fill-paragraph
1199 )
1200 (use-local-map py-mode-map)
1201 ;; add the menu
1202 (if py-menu
1203 (easy-menu-add py-menu))
1204 ;; Emacs 19 requires this
1205 (if (boundp 'comment-multi-line)
1206 (setq comment-multi-line nil))
1207 ;; Install Imenu if available
1208 (when (py-safe (require 'imenu))
1209 (setq imenu-create-index-function #'py-imenu-create-index-function)
1210 (setq imenu-generic-expression py-imenu-generic-expression)
1211 (if (fboundp 'imenu-add-to-menubar)
1212 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1213 )
1214 ;; Run the mode hook. Note that py-mode-hook is deprecated.
1215 (if python-mode-hook
1216 (run-hooks 'python-mode-hook)
1217 (run-hooks 'py-mode-hook))
1218 ;; Now do the automagical guessing
1219 (if py-smart-indentation
1220 (let ((offset py-indent-offset))
1221 ;; It's okay if this fails to guess a good value
1222 (if (and (py-safe (py-guess-indent-offset))
1223 (<= py-indent-offset 8)
1224 (>= py-indent-offset 2))
1225 (setq offset py-indent-offset))
1226 (setq py-indent-offset offset)
1227 ;; Only turn indent-tabs-mode off if tab-width !=
1228 ;; py-indent-offset. Never turn it on, because the user must
1229 ;; have explicitly turned it off.
1230 (if (/= tab-width py-indent-offset)
1231 (setq indent-tabs-mode nil))
1232 ))
1233 ;; Set the default shell if not already set
1234 (when (null py-which-shell)
1235 (py-toggle-shells (py-choose-shell))))
1236
1237
1238 (make-obsolete 'jpython-mode 'jython-mode)
1239 (defun jython-mode ()
1240 "Major mode for editing Jython/Jython files.
1241 This is a simple wrapper around `python-mode'.
1242 It runs `jython-mode-hook' then calls `python-mode.'
1243 It is added to `interpreter-mode-alist' and `py-choose-shell'.
1244 "
1245 (interactive)
1246 (python-mode)
1247 (py-toggle-shells 'jython)
1248 (when jython-mode-hook
1249 (run-hooks 'jython-mode-hook)))
1250
1251
1252 ;; It's handy to add recognition of Python files to the
1253 ;; interpreter-mode-alist and to auto-mode-alist. With the former, we
1254 ;; can specify different `derived-modes' based on the #! line, but
1255 ;; with the latter, we can't. So we just won't add them if they're
1256 ;; already added.
1257 ;;;###autoload
1258 (let ((modes '(("jython" . jython-mode)
1259 ("python" . python-mode))))
1260 (while modes
1261 (when (not (assoc (car modes) interpreter-mode-alist))
1262 (push (car modes) interpreter-mode-alist))
1263 (setq modes (cdr modes))))
1264 ;;;###autoload
1265 (when (not (or (rassq 'python-mode auto-mode-alist)
1266 (rassq 'jython-mode auto-mode-alist)))
1267 (push '("\\.py$" . python-mode) auto-mode-alist))
1268
1269
1270
1271 ;; electric characters
1272 (defun py-outdent-p ()
1273 "Returns non-nil if the current line should dedent one level."
1274 (save-excursion
1275 (and (progn (back-to-indentation)
1276 (looking-at py-outdent-re))
1277 ;; short circuit infloop on illegal construct
1278 (not (bobp))
1279 (progn (forward-line -1)
1280 (py-goto-initial-line)
1281 (back-to-indentation)
1282 (while (or (looking-at py-blank-or-comment-re)
1283 (bobp))
1284 (backward-to-indentation 1))
1285 (not (looking-at py-no-outdent-re)))
1286 )))
1287
1288 (defun py-electric-colon (arg)
1289 "Insert a colon.
1290 In certain cases the line is dedented appropriately. If a numeric
1291 argument ARG is provided, that many colons are inserted
1292 non-electrically. Electric behavior is inhibited inside a string or
1293 comment."
1294 (interactive "*P")
1295 (self-insert-command (prefix-numeric-value arg))
1296 ;; are we in a string or comment?
1297 (if (save-excursion
1298 (let ((pps (parse-partial-sexp (save-excursion
1299 (py-beginning-of-def-or-class)
1300 (point))
1301 (point))))
1302 (not (or (nth 3 pps) (nth 4 pps)))))
1303 (save-excursion
1304 (let ((here (point))
1305 (outdent 0)
1306 (indent (py-compute-indentation t)))
1307 (if (and (not arg)
1308 (py-outdent-p)
1309 (= indent (save-excursion
1310 (py-next-statement -1)
1311 (py-compute-indentation t)))
1312 )
1313 (setq outdent py-indent-offset))
1314 ;; Don't indent, only dedent. This assumes that any lines
1315 ;; that are already dedented relative to
1316 ;; py-compute-indentation were put there on purpose. It's
1317 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1318 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1319 ;; determine this???
1320 (if (< (current-indentation) indent) nil
1321 (goto-char here)
1322 (beginning-of-line)
1323 (delete-horizontal-space)
1324 (indent-to (- indent outdent))
1325 )))))
1326
1327
1328 ;; Python subprocess utilities and filters
1329 (defun py-execute-file (proc filename)
1330 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1331 Make that process's buffer visible and force display. Also make
1332 comint believe the user typed this string so that
1333 `kill-output-from-shell' does The Right Thing."
1334 (let ((curbuf (current-buffer))
1335 (procbuf (process-buffer proc))
1336 ; (comint-scroll-to-bottom-on-output t)
1337 (msg (format "## working on region in file %s...\n" filename))
1338 ;; add some comment, so that we can filter it out of history
1339 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
1340 (unwind-protect
1341 (save-excursion
1342 (set-buffer procbuf)
1343 (goto-char (point-max))
1344 (move-marker (process-mark proc) (point))
1345 (funcall (process-filter proc) proc msg))
1346 (set-buffer curbuf))
1347 (process-send-string proc cmd)))
1348
1349 (defun py-comint-output-filter-function (string)
1350 "Watch output for Python prompt and exec next file waiting in queue.
1351 This function is appropriate for `comint-output-filter-functions'."
1352 ;;remove ansi terminal escape sequences from string, not sure why they are
1353 ;;still around...
1354 (setq string (ansi-color-filter-apply string))
1355 (when (and (string-match py-shell-input-prompt-1-regexp string)
1356 py-file-queue)
1357 (if py-shell-switch-buffers-on-execute
1358 (pop-to-buffer (current-buffer)))
1359 (py-safe (delete-file (car py-file-queue)))
1360 (setq py-file-queue (cdr py-file-queue))
1361 (if py-file-queue
1362 (let ((pyproc (get-buffer-process (current-buffer))))
1363 (py-execute-file pyproc (car py-file-queue))))
1364 ))
1365
1366 (defun py-pdbtrack-overlay-arrow (activation)
1367 "Activate or de arrow at beginning-of-line in current buffer."
1368 ;; This was derived/simplified from edebug-overlay-arrow
1369 (cond (activation
1370 (setq overlay-arrow-position (make-marker))
1371 (setq overlay-arrow-string "=>")
1372 (set-marker overlay-arrow-position (py-point 'bol) (current-buffer))
1373 (setq py-pdbtrack-is-tracking-p t))
1374 (overlay-arrow-position
1375 (setq overlay-arrow-position nil)
1376 (setq py-pdbtrack-is-tracking-p nil))
1377 ))
1378
1379 (defun py-pdbtrack-track-stack-file (text)
1380 "Show the file indicated by the pdb stack entry line, in a separate window.
1381
1382 Activity is disabled if the buffer-local variable
1383 `py-pdbtrack-do-tracking-p' is nil.
1384
1385 We depend on the pdb input prompt matching `py-pdbtrack-input-prompt'
1386 at the beginning of the line.
1387
1388 If the traceback target file path is invalid, we look for the most
1389 recently visited python-mode buffer which either has the name of the
1390 current function \(or class) or which defines the function \(or
1391 class). This is to provide for remote scripts, eg, Zope's 'Script
1392 (Python)' - put a _copy_ of the script in a buffer named for the
1393 script, and set to python-mode, and pdbtrack will find it.)"
1394 ;; Instead of trying to piece things together from partial text
1395 ;; (which can be almost useless depending on Emacs version), we
1396 ;; monitor to the point where we have the next pdb prompt, and then
1397 ;; check all text from comint-last-input-end to process-mark.
1398 ;;
1399 ;; Also, we're very conservative about clearing the overlay arrow,
1400 ;; to minimize residue. This means, for instance, that executing
1401 ;; other pdb commands wipe out the highlight. You can always do a
1402 ;; 'where' (aka 'w') command to reveal the overlay arrow.
1403 (let* ((origbuf (current-buffer))
1404 (currproc (get-buffer-process origbuf)))
1405
1406 (if (not (and currproc py-pdbtrack-do-tracking-p))
1407 (py-pdbtrack-overlay-arrow nil)
1408
1409 (let* ((procmark (process-mark currproc))
1410 (block (buffer-substring (max comint-last-input-end
1411 (- procmark
1412 py-pdbtrack-track-range))
1413 procmark))
1414 target target_fname target_lineno target_buffer)
1415
1416 (if (not (string-match (concat py-pdbtrack-input-prompt "$") block))
1417 (py-pdbtrack-overlay-arrow nil)
1418
1419 (setq target (py-pdbtrack-get-source-buffer block))
1420
1421 (if (stringp target)
1422 (message "pdbtrack: %s" target)
1423
1424 (setq target_lineno (car target))
1425 (setq target_buffer (cadr target))
1426 (setq target_fname (buffer-file-name target_buffer))
1427 (switch-to-buffer-other-window target_buffer)
1428 (goto-line target_lineno)
1429 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
1430 (py-pdbtrack-overlay-arrow t)
1431 (pop-to-buffer origbuf t)
1432
1433 )))))
1434 )
1435
1436 (defun py-pdbtrack-get-source-buffer (block)
1437 "Return line number and buffer of code indicated by block's traceback text.
1438
1439 We look first to visit the file indicated in the trace.
1440
1441 Failing that, we look for the most recently visited python-mode buffer
1442 with the same name or having the named function.
1443
1444 If we're unable find the source code we return a string describing the
1445 problem as best as we can determine."
1446
1447 (if (not (string-match py-pdbtrack-stack-entry-regexp block))
1448
1449 "Traceback cue not found"
1450
1451 (let* ((filename (match-string 1 block))
1452 (lineno (string-to-int (match-string 2 block)))
1453 (funcname (match-string 3 block))
1454 funcbuffer)
1455
1456 (cond ((file-exists-p filename)
1457 (list lineno (find-file-noselect filename)))
1458
1459 ((setq funcbuffer (py-pdbtrack-grub-for-buffer funcname lineno))
1460 (if (string-match "/Script (Python)$" filename)
1461 ;; Add in number of lines for leading '##' comments:
1462 (setq lineno
1463 (+ lineno
1464 (save-excursion
1465 (set-buffer funcbuffer)
1466 (count-lines
1467 (point-min)
1468 (max (point-min)
1469 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
1470 (buffer-substring (point-min)
1471 (point-max)))
1472 ))))))
1473 (list lineno funcbuffer))
1474
1475 ((= (elt filename 0) ?\<)
1476 (format "(Non-file source: '%s')" filename))
1477
1478 (t (format "Not found: %s(), %s" funcname filename)))
1479 )
1480 )
1481 )
1482
1483 (defun py-pdbtrack-grub-for-buffer (funcname lineno)
1484 "Find most recent buffer itself named or having function funcname.
1485
1486 We walk the buffer-list history for python-mode buffers that are
1487 named for funcname or define a function funcname."
1488 (let ((buffers (buffer-list))
1489 buf
1490 got)
1491 (while (and buffers (not got))
1492 (setq buf (car buffers)
1493 buffers (cdr buffers))
1494 (if (and (save-excursion (set-buffer buf)
1495 (string= major-mode "python-mode"))
1496 (or (string-match funcname (buffer-name buf))
1497 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
1498 funcname "\\s-*(")
1499 (save-excursion
1500 (set-buffer buf)
1501 (buffer-substring (point-min)
1502 (point-max))))))
1503 (setq got buf)))
1504 got))
1505
1506 (defun py-postprocess-output-buffer (buf)
1507 "Highlight exceptions found in BUF.
1508 If an exception occurred return t, otherwise return nil. BUF must exist."
1509 (let (line file bol err-p)
1510 (save-excursion
1511 (set-buffer buf)
1512 (beginning-of-buffer)
1513 (while (re-search-forward py-traceback-line-re nil t)
1514 (setq file (match-string 1)
1515 line (string-to-int (match-string 2))
1516 bol (py-point 'bol))
1517 (py-highlight-line bol (py-point 'eol) file line)))
1518 (when (and py-jump-on-exception line)
1519 (beep)
1520 (py-jump-to-exception file line)
1521 (setq err-p t))
1522 err-p))
1523
1524
1525
1526 ;;; Subprocess commands
1527
1528 ;; only used when (memq 'broken-temp-names py-emacs-features)
1529 (defvar py-serial-number 0)
1530 (defvar py-exception-buffer nil)
1531 (defconst py-output-buffer "*Python Output*")
1532 (make-variable-buffer-local 'py-output-buffer)
1533
1534 ;; for toggling between CPython and Jython
1535 (defvar py-which-shell nil)
1536 (defvar py-which-args py-python-command-args)
1537 (defvar py-which-bufname "Python")
1538 (make-variable-buffer-local 'py-which-shell)
1539 (make-variable-buffer-local 'py-which-args)
1540 (make-variable-buffer-local 'py-which-bufname)
1541
1542 (defun py-toggle-shells (arg)
1543 "Toggles between the CPython and Jython shells.
1544
1545 With positive argument ARG (interactively \\[universal-argument]),
1546 uses the CPython shell, with negative ARG uses the Jython shell, and
1547 with a zero argument, toggles the shell.
1548
1549 Programmatically, ARG can also be one of the symbols `cpython' or
1550 `jython', equivalent to positive arg and negative arg respectively."
1551 (interactive "P")
1552 ;; default is to toggle
1553 (if (null arg)
1554 (setq arg 0))
1555 ;; preprocess arg
1556 (cond
1557 ((equal arg 0)
1558 ;; toggle
1559 (if (string-equal py-which-bufname "Python")
1560 (setq arg -1)
1561 (setq arg 1)))
1562 ((equal arg 'cpython) (setq arg 1))
1563 ((equal arg 'jython) (setq arg -1)))
1564 (let (msg)
1565 (cond
1566 ((< 0 arg)
1567 ;; set to CPython
1568 (setq py-which-shell py-python-command
1569 py-which-args py-python-command-args
1570 py-which-bufname "Python"
1571 msg "CPython")
1572 (if (string-equal py-which-bufname "Jython")
1573 (setq mode-name "Python")))
1574 ((> 0 arg)
1575 (setq py-which-shell py-jython-command
1576 py-which-args py-jython-command-args
1577 py-which-bufname "Jython"
1578 msg "Jython")
1579 (if (string-equal py-which-bufname "Python")
1580 (setq mode-name "Jython")))
1581 )
1582 (message "Using the %s shell" msg)
1583 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
1584
1585 ;;;###autoload
1586 (defun py-shell (&optional argprompt)
1587 "Start an interactive Python interpreter in another window.
1588 This is like Shell mode, except that Python is running in the window
1589 instead of a shell. See the `Interactive Shell' and `Shell Mode'
1590 sections of the Emacs manual for details, especially for the key
1591 bindings active in the `*Python*' buffer.
1592
1593 With optional \\[universal-argument], the user is prompted for the
1594 flags to pass to the Python interpreter. This has no effect when this
1595 command is used to switch to an existing process, only when a new
1596 process is started. If you use this, you will probably want to ensure
1597 that the current arguments are retained (they will be included in the
1598 prompt). This argument is ignored when this function is called
1599 programmatically, or when running in Emacs 19.34 or older.
1600
1601 Note: You can toggle between using the CPython interpreter and the
1602 Jython interpreter by hitting \\[py-toggle-shells]. This toggles
1603 buffer local variables which control whether all your subshell
1604 interactions happen to the `*Jython*' or `*Python*' buffers (the
1605 latter is the name used for the CPython buffer).
1606
1607 Warning: Don't use an interactive Python if you change sys.ps1 or
1608 sys.ps2 from their default values, or if you're running code that
1609 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1610 distinguish your output from Python's output, and assumes that `>>> '
1611 at the start of a line is a prompt from Python. Similarly, the Emacs
1612 Shell mode code assumes that both `>>> ' and `... ' at the start of a
1613 line are Python prompts. Bad things can happen if you fool either
1614 mode.
1615
1616 Warning: If you do any editing *in* the process buffer *while* the
1617 buffer is accepting output from Python, do NOT attempt to `undo' the
1618 changes. Some of the output (nowhere near the parts you changed!) may
1619 be lost if you do. This appears to be an Emacs bug, an unfortunate
1620 interaction between undo and process filters; the same problem exists in
1621 non-Python process buffers using the default (Emacs-supplied) process
1622 filter."
1623 (interactive "P")
1624 ;; Set the default shell if not already set
1625 (when (null py-which-shell)
1626 (py-toggle-shells py-default-interpreter))
1627 (let ((args py-which-args))
1628 (when (and argprompt
1629 (interactive-p)
1630 (fboundp 'split-string))
1631 ;; TBD: Perhaps force "-i" in the final list?
1632 (setq args (split-string
1633 (read-string (concat py-which-bufname
1634 " arguments: ")
1635 (concat
1636 (mapconcat 'identity py-which-args " ") " ")
1637 ))))
1638 (if (not (equal (buffer-name) "*Python*"))
1639 (switch-to-buffer-other-window
1640 (apply 'make-comint py-which-bufname py-which-shell nil args))
1641 (apply 'make-comint py-which-bufname py-which-shell nil args))
1642 (make-local-variable 'comint-prompt-regexp)
1643 (setq comint-prompt-regexp (concat py-shell-input-prompt-1-regexp "\\|"
1644 py-shell-input-prompt-2-regexp "\\|"
1645 "^([Pp]db) "))
1646 (add-hook 'comint-output-filter-functions
1647 'py-comint-output-filter-function)
1648 ;; pdbtrack
1649 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
1650 (setq py-pdbtrack-do-tracking-p t)
1651 (set-syntax-table py-mode-syntax-table)
1652 (use-local-map py-shell-map)
1653 (run-hooks 'py-shell-hook)
1654 ))
1655
1656 (defun py-clear-queue ()
1657 "Clear the queue of temporary files waiting to execute."
1658 (interactive)
1659 (let ((n (length py-file-queue)))
1660 (mapcar 'delete-file py-file-queue)
1661 (setq py-file-queue nil)
1662 (message "%d pending files de-queued." n)))
1663
1664
1665 (defun py-execute-region (start end &optional async)
1666 "Execute the region in a Python interpreter.
1667
1668 The region is first copied into a temporary file (in the directory
1669 `py-temp-directory'). If there is no Python interpreter shell
1670 running, this file is executed synchronously using
1671 `shell-command-on-region'. If the program is long running, use
1672 \\[universal-argument] to run the command asynchronously in its own
1673 buffer.
1674
1675 When this function is used programmatically, arguments START and END
1676 specify the region to execute, and optional third argument ASYNC, if
1677 non-nil, specifies to run the command asynchronously in its own
1678 buffer.
1679
1680 If the Python interpreter shell is running, the region is execfile()'d
1681 in that shell. If you try to execute regions too quickly,
1682 `python-mode' will queue them up and execute them one at a time when
1683 it sees a `>>> ' prompt from Python. Each time this happens, the
1684 process buffer is popped into a window (if it's not already in some
1685 window) so you can see it, and a comment of the form
1686
1687 \t## working on region in file <name>...
1688
1689 is inserted at the end. See also the command `py-clear-queue'."
1690 (interactive "r\nP")
1691 ;; Skip ahead to the first non-blank line
1692 (let* ((proc (get-process py-which-bufname))
1693 (temp (if (memq 'broken-temp-names py-emacs-features)
1694 (let
1695 ((sn py-serial-number)
1696 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1697 (setq py-serial-number (1+ py-serial-number))
1698 (if pid
1699 (format "python-%d-%d" sn pid)
1700 (format "python-%d" sn)))
1701 (make-temp-name "python-")))
1702 (file (concat (expand-file-name temp py-temp-directory) ".py"))
1703 (cur (current-buffer))
1704 (buf (get-buffer-create file))
1705 shell)
1706 ;; Write the contents of the buffer, watching out for indented regions.
1707 (save-excursion
1708 (goto-char start)
1709 (beginning-of-line)
1710 (while (and (looking-at "\\s *$")
1711 (< (point) end))
1712 (forward-line 1))
1713 (setq start (point))
1714 (or (< start end)
1715 (error "Region is empty"))
1716 (setq py-line-number-offset (count-lines 1 start))
1717 (let ((needs-if (/= (py-point 'bol) (py-point 'boi))))
1718 (set-buffer buf)
1719 (python-mode)
1720 (when needs-if
1721 (insert "if 1:\n")
1722 (setq py-line-number-offset (- py-line-number-offset 1)))
1723 (insert-buffer-substring cur start end)
1724 ;; Set the shell either to the #! line command, or to the
1725 ;; py-which-shell buffer local variable.
1726 (setq shell (or (py-choose-shell-by-shebang)
1727 (py-choose-shell-by-import)
1728 py-which-shell))))
1729 (cond
1730 ;; always run the code in its own asynchronous subprocess
1731 (async
1732 ;; User explicitly wants this to run in its own async subprocess
1733 (save-excursion
1734 (set-buffer buf)
1735 (write-region (point-min) (point-max) file nil 'nomsg))
1736 (let* ((buf (generate-new-buffer-name py-output-buffer))
1737 ;; TBD: a horrible hack, but why create new Custom variables?
1738 (arg (if (string-equal py-which-bufname "Python")
1739 "-u" "")))
1740 (start-process py-which-bufname buf shell arg file)
1741 (pop-to-buffer buf)
1742 (py-postprocess-output-buffer buf)
1743 ;; TBD: clean up the temporary file!
1744 ))
1745 ;; if the Python interpreter shell is running, queue it up for
1746 ;; execution there.
1747 (proc
1748 ;; use the existing python shell
1749 (save-excursion
1750 (set-buffer buf)
1751 (write-region (point-min) (point-max) file nil 'nomsg))
1752 (if (not py-file-queue)
1753 (py-execute-file proc file)
1754 (message "File %s queued for execution" file))
1755 (setq py-file-queue (append py-file-queue (list file)))
1756 (setq py-exception-buffer (cons file (current-buffer))))
1757 (t
1758 ;; TBD: a horrible hack, but why create new Custom variables?
1759 (let ((cmd (concat py-which-shell (if (string-equal py-which-bufname
1760 "Jython")
1761 " -" ""))))
1762 ;; otherwise either run it synchronously in a subprocess
1763 (save-excursion
1764 (set-buffer buf)
1765 (shell-command-on-region (point-min) (point-max)
1766 cmd py-output-buffer))
1767 ;; shell-command-on-region kills the output buffer if it never
1768 ;; existed and there's no output from the command
1769 (if (not (get-buffer py-output-buffer))
1770 (message "No output.")
1771 (setq py-exception-buffer (current-buffer))
1772 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1773 (pop-to-buffer py-output-buffer)
1774 (if err-p
1775 (pop-to-buffer py-exception-buffer)))
1776 ))
1777 ))
1778 ;; Clean up after ourselves.
1779 (kill-buffer buf)))
1780
1781
1782 ;; Code execution commands
1783 (defun py-execute-buffer (&optional async)
1784 "Send the contents of the buffer to a Python interpreter.
1785 If the file local variable `py-master-file' is non-nil, execute the
1786 named file instead of the buffer's file.
1787
1788 If there is a *Python* process buffer it is used. If a clipping
1789 restriction is in effect, only the accessible portion of the buffer is
1790 sent. A trailing newline will be supplied if needed.
1791
1792 See the `\\[py-execute-region]' docs for an account of some
1793 subtleties, including the use of the optional ASYNC argument."
1794 (interactive "P")
1795 (let ((old-buffer (current-buffer)))
1796 (if py-master-file
1797 (let* ((filename (expand-file-name py-master-file))
1798 (buffer (or (get-file-buffer filename)
1799 (find-file-noselect filename))))
1800 (set-buffer buffer)))
1801 (py-execute-region (point-min) (point-max) async)
1802 (pop-to-buffer old-buffer)))
1803
1804 (defun py-execute-import-or-reload (&optional async)
1805 "Import the current buffer's file in a Python interpreter.
1806
1807 If the file has already been imported, then do reload instead to get
1808 the latest version.
1809
1810 If the file's name does not end in \".py\", then do execfile instead.
1811
1812 If the current buffer is not visiting a file, do `py-execute-buffer'
1813 instead.
1814
1815 If the file local variable `py-master-file' is non-nil, import or
1816 reload the named file instead of the buffer's file. The file may be
1817 saved based on the value of `py-execute-import-or-reload-save-p'.
1818
1819 See the `\\[py-execute-region]' docs for an account of some
1820 subtleties, including the use of the optional ASYNC argument.
1821
1822 This may be preferable to `\\[py-execute-buffer]' because:
1823
1824 - Definitions stay in their module rather than appearing at top
1825 level, where they would clutter the global namespace and not affect
1826 uses of qualified names (MODULE.NAME).
1827
1828 - The Python debugger gets line number information about the functions."
1829 (interactive "P")
1830 ;; Check file local variable py-master-file
1831 (if py-master-file
1832 (let* ((filename (expand-file-name py-master-file))
1833 (buffer (or (get-file-buffer filename)
1834 (find-file-noselect filename))))
1835 (set-buffer buffer)))
1836 (let ((file (buffer-file-name (current-buffer))))
1837 (if file
1838 (progn
1839 ;; Maybe save some buffers
1840 (save-some-buffers (not py-ask-about-save) nil)
1841 (py-execute-string
1842 (if (string-match "\\.py$" file)
1843 (let ((f (file-name-sans-extension
1844 (file-name-nondirectory file))))
1845 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1846 f f f))
1847 (format "execfile(r'%s')\n" file))
1848 async))
1849 ;; else
1850 (py-execute-buffer async))))
1851
1852
1853 (defun py-execute-def-or-class (&optional async)
1854 "Send the current function or class definition to a Python interpreter.
1855
1856 If there is a *Python* process buffer it is used.
1857
1858 See the `\\[py-execute-region]' docs for an account of some
1859 subtleties, including the use of the optional ASYNC argument."
1860 (interactive "P")
1861 (save-excursion
1862 (py-mark-def-or-class)
1863 ;; mark is before point
1864 (py-execute-region (mark) (point) async)))
1865
1866
1867 (defun py-execute-string (string &optional async)
1868 "Send the argument STRING to a Python interpreter.
1869
1870 If there is a *Python* process buffer it is used.
1871
1872 See the `\\[py-execute-region]' docs for an account of some
1873 subtleties, including the use of the optional ASYNC argument."
1874 (interactive "sExecute Python command: ")
1875 (save-excursion
1876 (set-buffer (get-buffer-create
1877 (generate-new-buffer-name " *Python Command*")))
1878 (insert string)
1879 (py-execute-region (point-min) (point-max) async)))
1880
1881
1882
1883 (defun py-jump-to-exception (file line)
1884 "Jump to the Python code in FILE at LINE."
1885 (let ((buffer (cond ((string-equal file "<stdin>")
1886 (if (consp py-exception-buffer)
1887 (cdr py-exception-buffer)
1888 py-exception-buffer))
1889 ((and (consp py-exception-buffer)
1890 (string-equal file (car py-exception-buffer)))
1891 (cdr py-exception-buffer))
1892 ((py-safe (find-file-noselect file)))
1893 ;; could not figure out what file the exception
1894 ;; is pointing to, so prompt for it
1895 (t (find-file (read-file-name "Exception file: "
1896 nil
1897 file t))))))
1898 ;; Fiddle about with line number
1899 (setq line (+ py-line-number-offset line))
1900
1901 (pop-to-buffer buffer)
1902 ;; Force Python mode
1903 (if (not (eq major-mode 'python-mode))
1904 (python-mode))
1905 (goto-line line)
1906 (message "Jumping to exception in file %s on line %d" file line)))
1907
1908 (defun py-mouseto-exception (event)
1909 "Jump to the code which caused the Python exception at EVENT.
1910 EVENT is usually a mouse click."
1911 (interactive "e")
1912 (cond
1913 ((fboundp 'event-point)
1914 ;; XEmacs
1915 (let* ((point (event-point event))
1916 (buffer (event-buffer event))
1917 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1918 (info (and e (extent-property e 'py-exc-info))))
1919 (message "Event point: %d, info: %s" point info)
1920 (and info
1921 (py-jump-to-exception (car info) (cdr info)))
1922 ))
1923 ;; Emacs -- Please port this!
1924 ))
1925
1926 (defun py-goto-exception ()
1927 "Go to the line indicated by the traceback."
1928 (interactive)
1929 (let (file line)
1930 (save-excursion
1931 (beginning-of-line)
1932 (if (looking-at py-traceback-line-re)
1933 (setq file (match-string 1)
1934 line (string-to-int (match-string 2)))))
1935 (if (not file)
1936 (error "Not on a traceback line"))
1937 (py-jump-to-exception file line)))
1938
1939 (defun py-find-next-exception (start buffer searchdir errwhere)
1940 "Find the next Python exception and jump to the code that caused it.
1941 START is the buffer position in BUFFER from which to begin searching
1942 for an exception. SEARCHDIR is a function, either
1943 `re-search-backward' or `re-search-forward' indicating the direction
1944 to search. ERRWHERE is used in an error message if the limit (top or
1945 bottom) of the trackback stack is encountered."
1946 (let (file line)
1947 (save-excursion
1948 (set-buffer buffer)
1949 (goto-char (py-point start))
1950 (if (funcall searchdir py-traceback-line-re nil t)
1951 (setq file (match-string 1)
1952 line (string-to-int (match-string 2)))))
1953 (if (and file line)
1954 (py-jump-to-exception file line)
1955 (error "%s of traceback" errwhere))))
1956
1957 (defun py-down-exception (&optional bottom)
1958 "Go to the next line down in the traceback.
1959 With \\[univeral-argument] (programmatically, optional argument
1960 BOTTOM), jump to the bottom (innermost) exception in the exception
1961 stack."
1962 (interactive "P")
1963 (let* ((proc (get-process "Python"))
1964 (buffer (if proc "*Python*" py-output-buffer)))
1965 (if bottom
1966 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1967 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1968
1969 (defun py-up-exception (&optional top)
1970 "Go to the previous line up in the traceback.
1971 With \\[universal-argument] (programmatically, optional argument TOP)
1972 jump to the top (outermost) exception in the exception stack."
1973 (interactive "P")
1974 (let* ((proc (get-process "Python"))
1975 (buffer (if proc "*Python*" py-output-buffer)))
1976 (if top
1977 (py-find-next-exception 'bob buffer 're-search-forward "Top")
1978 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
1979
1980
1981 ;; Electric deletion
1982 (defun py-electric-backspace (arg)
1983 "Delete preceding character or levels of indentation.
1984 Deletion is performed by calling the function in `py-backspace-function'
1985 with a single argument (the number of characters to delete).
1986
1987 If point is at the leftmost column, delete the preceding newline.
1988
1989 Otherwise, if point is at the leftmost non-whitespace character of a
1990 line that is neither a continuation line nor a non-indenting comment
1991 line, or if point is at the end of a blank line, this command reduces
1992 the indentation to match that of the line that opened the current
1993 block of code. The line that opened the block is displayed in the
1994 echo area to help you keep track of where you are. With
1995 \\[universal-argument] dedents that many blocks (but not past column
1996 zero).
1997
1998 Otherwise the preceding character is deleted, converting a tab to
1999 spaces if needed so that only a single column position is deleted.
2000 \\[universal-argument] specifies how many characters to delete;
2001 default is 1.
2002
2003 When used programmatically, argument ARG specifies the number of
2004 blocks to dedent, or the number of characters to delete, as indicated
2005 above."
2006 (interactive "*p")
2007 (if (or (/= (current-indentation) (current-column))
2008 (bolp)
2009 (py-continuation-line-p)
2010 ; (not py-honor-comment-indentation)
2011 ; (looking-at "#[^ \t\n]") ; non-indenting #
2012 )
2013 (funcall py-backspace-function arg)
2014 ;; else indent the same as the colon line that opened the block
2015 ;; force non-blank so py-goto-block-up doesn't ignore it
2016 (insert-char ?* 1)
2017 (backward-char)
2018 (let ((base-indent 0) ; indentation of base line
2019 (base-text "") ; and text of base line
2020 (base-found-p nil))
2021 (save-excursion
2022 (while (< 0 arg)
2023 (condition-case nil ; in case no enclosing block
2024 (progn
2025 (py-goto-block-up 'no-mark)
2026 (setq base-indent (current-indentation)
2027 base-text (py-suck-up-leading-text)
2028 base-found-p t))
2029 (error nil))
2030 (setq arg (1- arg))))
2031 (delete-char 1) ; toss the dummy character
2032 (delete-horizontal-space)
2033 (indent-to base-indent)
2034 (if base-found-p
2035 (message "Closes block: %s" base-text)))))
2036
2037
2038 (defun py-electric-delete (arg)
2039 "Delete preceding or following character or levels of whitespace.
2040
2041 The behavior of this function depends on the variable
2042 `delete-key-deletes-forward'. If this variable is nil (or does not
2043 exist, as in older Emacsen and non-XEmacs versions), then this
2044 function behaves identically to \\[c-electric-backspace].
2045
2046 If `delete-key-deletes-forward' is non-nil and is supported in your
2047 Emacs, then deletion occurs in the forward direction, by calling the
2048 function in `py-delete-function'.
2049
2050 \\[universal-argument] (programmatically, argument ARG) specifies the
2051 number of characters to delete (default is 1)."
2052 (interactive "*p")
2053 (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
2054 (delete-forward-p))
2055 (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
2056 delete-key-deletes-forward))
2057 (funcall py-delete-function arg)
2058 (py-electric-backspace arg)))
2059
2060 ;; required for pending-del and delsel modes
2061 (put 'py-electric-colon 'delete-selection t) ;delsel
2062 (put 'py-electric-colon 'pending-delete t) ;pending-del
2063 (put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
2064 (put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
2065 (put 'py-electric-delete 'delete-selection 'supersede) ;delsel
2066 (put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
2067
2068
2069
2070 (defun py-indent-line (&optional arg)
2071 "Fix the indentation of the current line according to Python rules.
2072 With \\[universal-argument] (programmatically, the optional argument
2073 ARG non-nil), ignore dedenting rules for block closing statements
2074 (e.g. return, raise, break, continue, pass)
2075
2076 This function is normally bound to `indent-line-function' so
2077 \\[indent-for-tab-command] will call it."
2078 (interactive "P")
2079 (let* ((ci (current-indentation))
2080 (move-to-indentation-p (<= (current-column) ci))
2081 (need (py-compute-indentation (not arg)))
2082 (cc (current-column)))
2083 ;; dedent out a level if previous command was the same unless we're in
2084 ;; column 1
2085 (if (and (equal last-command this-command)
2086 (/= cc 0))
2087 (progn
2088 (beginning-of-line)
2089 (delete-horizontal-space)
2090 (indent-to (* (/ (- cc 1) py-indent-offset) py-indent-offset)))
2091 (progn
2092 ;; see if we need to dedent
2093 (if (py-outdent-p)
2094 (setq need (- need py-indent-offset)))
2095 (if (or py-tab-always-indent
2096 move-to-indentation-p)
2097 (progn (if (/= ci need)
2098 (save-excursion
2099 (beginning-of-line)
2100 (delete-horizontal-space)
2101 (indent-to need)))
2102 (if move-to-indentation-p (back-to-indentation)))
2103 (insert-tab))))))
2104
2105 (defun py-newline-and-indent ()
2106 "Strives to act like the Emacs `newline-and-indent'.
2107 This is just `strives to' because correct indentation can't be computed
2108 from scratch for Python code. In general, deletes the whitespace before
2109 point, inserts a newline, and takes an educated guess as to how you want
2110 the new line indented."
2111 (interactive)
2112 (let ((ci (current-indentation)))
2113 (if (< ci (current-column)) ; if point beyond indentation
2114 (newline-and-indent)
2115 ;; else try to act like newline-and-indent "normally" acts
2116 (beginning-of-line)
2117 (insert-char ?\n 1)
2118 (move-to-column ci))))
2119
2120 (defun py-compute-indentation (honor-block-close-p)
2121 "Compute Python indentation.
2122 When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
2123 `raise', `break', `continue', and `pass' force one level of
2124 dedenting."
2125 (save-excursion
2126 (beginning-of-line)
2127 (let* ((bod (py-point 'bod))
2128 (pps (parse-partial-sexp bod (point)))
2129 (boipps (parse-partial-sexp bod (py-point 'boi)))
2130 placeholder)
2131 (cond
2132 ;; are we inside a multi-line string or comment?
2133 ((or (and (nth 3 pps) (nth 3 boipps))
2134 (and (nth 4 pps) (nth 4 boipps)))
2135 (save-excursion
2136 (if (not py-align-multiline-strings-p) 0
2137 ;; skip back over blank & non-indenting comment lines
2138 ;; note: will skip a blank or non-indenting comment line
2139 ;; that happens to be a continuation line too
2140 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
2141 (back-to-indentation)
2142 (current-column))))
2143 ;; are we on a continuation line?
2144 ((py-continuation-line-p)
2145 (let ((startpos (point))
2146 (open-bracket-pos (py-nesting-level))
2147 endpos searching found state)
2148 (if open-bracket-pos
2149 (progn
2150 ;; align with first item in list; else a normal
2151 ;; indent beyond the line with the open bracket
2152 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
2153 ;; is the first list item on the same line?
2154 (skip-chars-forward " \t")
2155 (if (null (memq (following-char) '(?\n ?# ?\\)))
2156 ; yes, so line up with it
2157 (current-column)
2158 ;; first list item on another line, or doesn't exist yet
2159 (forward-line 1)
2160 (while (and (< (point) startpos)
2161 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
2162 (forward-line 1))
2163 (if (and (< (point) startpos)
2164 (/= startpos
2165 (save-excursion
2166 (goto-char (1+ open-bracket-pos))
2167 (forward-comment (point-max))
2168 (point))))
2169 ;; again mimic the first list item
2170 (current-indentation)
2171 ;; else they're about to enter the first item
2172 (goto-char open-bracket-pos)
2173 (setq placeholder (point))
2174 (py-goto-initial-line)
2175 (py-goto-beginning-of-tqs
2176 (save-excursion (nth 3 (parse-partial-sexp
2177 placeholder (point)))))
2178 (+ (current-indentation) py-indent-offset))))
2179
2180 ;; else on backslash continuation line
2181 (forward-line -1)
2182 (if (py-continuation-line-p) ; on at least 3rd line in block
2183 (current-indentation) ; so just continue the pattern
2184 ;; else started on 2nd line in block, so indent more.
2185 ;; if base line is an assignment with a start on a RHS,
2186 ;; indent to 2 beyond the leftmost "="; else skip first
2187 ;; chunk of non-whitespace characters on base line, + 1 more
2188 ;; column
2189 (end-of-line)
2190 (setq endpos (point)
2191 searching t)
2192 (back-to-indentation)
2193 (setq startpos (point))
2194 ;; look at all "=" from left to right, stopping at first
2195 ;; one not nested in a list or string
2196 (while searching
2197 (skip-chars-forward "^=" endpos)
2198 (if (= (point) endpos)
2199 (setq searching nil)
2200 (forward-char 1)
2201 (setq state (parse-partial-sexp startpos (point)))
2202 (if (and (zerop (car state)) ; not in a bracket
2203 (null (nth 3 state))) ; & not in a string
2204 (progn
2205 (setq searching nil) ; done searching in any case
2206 (setq found
2207 (not (or
2208 (eq (following-char) ?=)
2209 (memq (char-after (- (point) 2))
2210 '(?< ?> ?!)))))))))
2211 (if (or (not found) ; not an assignment
2212 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
2213 (progn
2214 (goto-char startpos)
2215 (skip-chars-forward "^ \t\n")))
2216 ;; if this is a continuation for a block opening
2217 ;; statement, add some extra offset.
2218 (+ (current-column) (if (py-statement-opens-block-p)
2219 py-continuation-offset 0)
2220 1)
2221 ))))
2222
2223 ;; not on a continuation line
2224 ((bobp) (current-indentation))
2225
2226 ;; Dfn: "Indenting comment line". A line containing only a
2227 ;; comment, but which is treated like a statement for
2228 ;; indentation calculation purposes. Such lines are only
2229 ;; treated specially by the mode; they are not treated
2230 ;; specially by the Python interpreter.
2231
2232 ;; The rules for indenting comment lines are a line where:
2233 ;; - the first non-whitespace character is `#', and
2234 ;; - the character following the `#' is whitespace, and
2235 ;; - the line is dedented with respect to (i.e. to the left
2236 ;; of) the indentation of the preceding non-blank line.
2237
2238 ;; The first non-blank line following an indenting comment
2239 ;; line is given the same amount of indentation as the
2240 ;; indenting comment line.
2241
2242 ;; All other comment-only lines are ignored for indentation
2243 ;; purposes.
2244
2245 ;; Are we looking at a comment-only line which is *not* an
2246 ;; indenting comment line? If so, we assume that it's been
2247 ;; placed at the desired indentation, so leave it alone.
2248 ;; Indenting comment lines are aligned as statements down
2249 ;; below.
2250 ((and (looking-at "[ \t]*#[^ \t\n]")
2251 ;; NOTE: this test will not be performed in older Emacsen
2252 (fboundp 'forward-comment)
2253 (<= (current-indentation)
2254 (save-excursion
2255 (forward-comment (- (point-max)))
2256 (current-indentation))))
2257 (current-indentation))
2258
2259 ;; else indentation based on that of the statement that
2260 ;; precedes us; use the first line of that statement to
2261 ;; establish the base, in case the user forced a non-std
2262 ;; indentation for the continuation lines (if any)
2263 (t
2264 ;; skip back over blank & non-indenting comment lines note:
2265 ;; will skip a blank or non-indenting comment line that
2266 ;; happens to be a continuation line too. use fast Emacs 19
2267 ;; function if it's there.
2268 (if (and (eq py-honor-comment-indentation nil)
2269 (fboundp 'forward-comment))
2270 (forward-comment (- (point-max)))
2271 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
2272 done)
2273 (while (not done)
2274 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
2275 (setq done (or (bobp)
2276 (and (eq py-honor-comment-indentation t)
2277 (save-excursion
2278 (back-to-indentation)
2279 (not (looking-at prefix-re))
2280 ))
2281 (and (not (eq py-honor-comment-indentation t))
2282 (save-excursion
2283 (back-to-indentation)
2284 (and (not (looking-at prefix-re))
2285 (or (looking-at "[^#]")
2286 (not (zerop (current-column)))
2287 ))
2288 ))
2289 ))
2290 )))
2291 ;; if we landed inside a string, go to the beginning of that
2292 ;; string. this handles triple quoted, multi-line spanning
2293 ;; strings.
2294 (py-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
2295 ;; now skip backward over continued lines
2296 (setq placeholder (point))
2297 (py-goto-initial-line)
2298 ;; we may *now* have landed in a TQS, so find the beginning of
2299 ;; this string.
2300 (py-goto-beginning-of-tqs
2301 (save-excursion (nth 3 (parse-partial-sexp
2302 placeholder (point)))))
2303 (+ (current-indentation)
2304 (if (py-statement-opens-block-p)
2305 py-indent-offset
2306 (if (and honor-block-close-p (py-statement-closes-block-p))
2307 (- py-indent-offset)
2308 0)))
2309 )))))
2310
2311 (defun py-guess-indent-offset (&optional global)
2312 "Guess a good value for, and change, `py-indent-offset'.
2313
2314 By default, make a buffer-local copy of `py-indent-offset' with the
2315 new value, so that other Python buffers are not affected. With
2316 \\[universal-argument] (programmatically, optional argument GLOBAL),
2317 change the global value of `py-indent-offset'. This affects all
2318 Python buffers (that don't have their own buffer-local copy), both
2319 those currently existing and those created later in the Emacs session.
2320
2321 Some people use a different value for `py-indent-offset' than you use.
2322 There's no excuse for such foolishness, but sometimes you have to deal
2323 with their ugly code anyway. This function examines the file and sets
2324 `py-indent-offset' to what it thinks it was when they created the
2325 mess.
2326
2327 Specifically, it searches forward from the statement containing point,
2328 looking for a line that opens a block of code. `py-indent-offset' is
2329 set to the difference in indentation between that line and the Python
2330 statement following it. If the search doesn't succeed going forward,
2331 it's tried again going backward."
2332 (interactive "P") ; raw prefix arg
2333 (let (new-value
2334 (start (point))
2335 (restart (point))
2336 (found nil)
2337 colon-indent)
2338 (py-goto-initial-line)
2339 (while (not (or found (eobp)))
2340 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2341 (not (py-in-literal restart)))
2342 (setq restart (point))
2343 (py-goto-initial-line)
2344 (if (py-statement-opens-block-p)
2345 (setq found t)
2346 (goto-char restart))))
2347 (unless found
2348 (goto-char start)
2349 (py-goto-initial-line)
2350 (while (not (or found (bobp)))
2351 (setq found (and
2352 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2353 (or (py-goto-initial-line) t) ; always true -- side effect
2354 (py-statement-opens-block-p)))))
2355 (setq colon-indent (current-indentation)
2356 found (and found (zerop (py-next-statement 1)))
2357 new-value (- (current-indentation) colon-indent))
2358 (goto-char start)
2359 (if (not found)
2360 (error "Sorry, couldn't guess a value for py-indent-offset")
2361 (funcall (if global 'kill-local-variable 'make-local-variable)
2362 'py-indent-offset)
2363 (setq py-indent-offset new-value)
2364 (or noninteractive
2365 (message "%s value of py-indent-offset set to %d"
2366 (if global "Global" "Local")
2367 py-indent-offset)))
2368 ))
2369
2370 (defun py-comment-indent-function ()
2371 "Python version of `comment-indent-function'."
2372 ;; This is required when filladapt is turned off. Without it, when
2373 ;; filladapt is not used, comments which start in column zero
2374 ;; cascade one character to the right
2375 (save-excursion
2376 (beginning-of-line)
2377 (let ((eol (py-point 'eol)))
2378 (and comment-start-skip
2379 (re-search-forward comment-start-skip eol t)
2380 (setq eol (match-beginning 0)))
2381 (goto-char eol)
2382 (skip-chars-backward " \t")
2383 (max comment-column (+ (current-column) (if (bolp) 0 1)))
2384 )))
2385
2386 (defun py-narrow-to-defun (&optional class)
2387 "Make text outside current defun invisible.
2388 The defun visible is the one that contains point or follows point.
2389 Optional CLASS is passed directly to `py-beginning-of-def-or-class'."
2390 (interactive "P")
2391 (save-excursion
2392 (widen)
2393 (py-end-of-def-or-class class)
2394 (let ((end (point)))
2395 (py-beginning-of-def-or-class class)
2396 (narrow-to-region (point) end))))
2397
2398
2399 (defun py-shift-region (start end count)
2400 "Indent lines from START to END by COUNT spaces."
2401 (save-excursion
2402 (goto-char end)
2403 (beginning-of-line)
2404 (setq end (point))
2405 (goto-char start)
2406 (beginning-of-line)
2407 (setq start (point))
2408 (indent-rigidly start end count)))
2409
2410 (defun py-shift-region-left (start end &optional count)
2411 "Shift region of Python code to the left.
2412 The lines from the line containing the start of the current region up
2413 to (but not including) the line containing the end of the region are
2414 shifted to the left, by `py-indent-offset' columns.
2415
2416 If a prefix argument is given, the region is instead shifted by that
2417 many columns. With no active region, dedent only the current line.
2418 You cannot dedent the region if any line is already at column zero."
2419 (interactive
2420 (let ((p (point))
2421 (m (mark))
2422 (arg current-prefix-arg))
2423 (if m
2424 (list (min p m) (max p m) arg)
2425 (list p (save-excursion (forward-line 1) (point)) arg))))
2426 ;; if any line is at column zero, don't shift the region
2427 (save-excursion
2428 (goto-char start)
2429 (while (< (point) end)
2430 (back-to-indentation)
2431 (if (and (zerop (current-column))
2432 (not (looking-at "\\s *$")))
2433 (error "Region is at left edge"))
2434 (forward-line 1)))
2435 (py-shift-region start end (- (prefix-numeric-value
2436 (or count py-indent-offset))))
2437 (py-keep-region-active))
2438
2439 (defun py-shift-region-right (start end &optional count)
2440 "Shift region of Python code to the right.
2441 The lines from the line containing the start of the current region up
2442 to (but not including) the line containing the end of the region are
2443 shifted to the right, by `py-indent-offset' columns.
2444
2445 If a prefix argument is given, the region is instead shifted by that
2446 many columns. With no active region, indent only the current line."
2447 (interactive
2448 (let ((p (point))
2449 (m (mark))
2450 (arg current-prefix-arg))
2451 (if m
2452 (list (min p m) (max p m) arg)
2453 (list p (save-excursion (forward-line 1) (point)) arg))))
2454 (py-shift-region start end (prefix-numeric-value
2455 (or count py-indent-offset)))
2456 (py-keep-region-active))
2457
2458 (defun py-indent-region (start end &optional indent-offset)
2459 "Reindent a region of Python code.
2460
2461 The lines from the line containing the start of the current region up
2462 to (but not including) the line containing the end of the region are
2463 reindented. If the first line of the region has a non-whitespace
2464 character in the first column, the first line is left alone and the
2465 rest of the region is reindented with respect to it. Else the entire
2466 region is reindented with respect to the (closest code or indenting
2467 comment) statement immediately preceding the region.
2468
2469 This is useful when code blocks are moved or yanked, when enclosing
2470 control structures are introduced or removed, or to reformat code
2471 using a new value for the indentation offset.
2472
2473 If a numeric prefix argument is given, it will be used as the value of
2474 the indentation offset. Else the value of `py-indent-offset' will be
2475 used.
2476
2477 Warning: The region must be consistently indented before this function
2478 is called! This function does not compute proper indentation from
2479 scratch (that's impossible in Python), it merely adjusts the existing
2480 indentation to be correct in context.
2481
2482 Warning: This function really has no idea what to do with
2483 non-indenting comment lines, and shifts them as if they were indenting
2484 comment lines. Fixing this appears to require telepathy.
2485
2486 Special cases: whitespace is deleted from blank lines; continuation
2487 lines are shifted by the same amount their initial line was shifted,
2488 in order to preserve their relative indentation with respect to their
2489 initial line; and comment lines beginning in column 1 are ignored."
2490 (interactive "*r\nP") ; region; raw prefix arg
2491 (save-excursion
2492 (goto-char end) (beginning-of-line) (setq end (point-marker))
2493 (goto-char start) (beginning-of-line)
2494 (let ((py-indent-offset (prefix-numeric-value
2495 (or indent-offset py-indent-offset)))
2496 (indents '(-1)) ; stack of active indent levels
2497 (target-column 0) ; column to which to indent
2498 (base-shifted-by 0) ; amount last base line was shifted
2499 (indent-base (if (looking-at "[ \t\n]")
2500 (py-compute-indentation t)
2501 0))
2502 ci)
2503 (while (< (point) end)
2504 (setq ci (current-indentation))
2505 ;; figure out appropriate target column
2506 (cond
2507 ((or (eq (following-char) ?#) ; comment in column 1
2508 (looking-at "[ \t]*$")) ; entirely blank
2509 (setq target-column 0))
2510 ((py-continuation-line-p) ; shift relative to base line
2511 (setq target-column (+ ci base-shifted-by)))
2512 (t ; new base line
2513 (if (> ci (car indents)) ; going deeper; push it
2514 (setq indents (cons ci indents))
2515 ;; else we should have seen this indent before
2516 (setq indents (memq ci indents)) ; pop deeper indents
2517 (if (null indents)
2518 (error "Bad indentation in region, at line %d"
2519 (save-restriction
2520 (widen)
2521 (1+ (count-lines 1 (point)))))))
2522 (setq target-column (+ indent-base
2523 (* py-indent-offset
2524 (- (length indents) 2))))
2525 (setq base-shifted-by (- target-column ci))))
2526 ;; shift as needed
2527 (if (/= ci target-column)
2528 (progn
2529 (delete-horizontal-space)
2530 (indent-to target-column)))
2531 (forward-line 1))))
2532 (set-marker end nil))
2533
2534 (defun py-comment-region (beg end &optional arg)
2535 "Like `comment-region' but uses double hash (`#') comment starter."
2536 (interactive "r\nP")
2537 (let ((comment-start py-block-comment-prefix))
2538 (comment-region beg end arg)))
2539
2540
2541 ;; Functions for moving point
2542 (defun py-previous-statement (count)
2543 "Go to the start of the COUNTth preceding Python statement.
2544 By default, goes to the previous statement. If there is no such
2545 statement, goes to the first statement. Return count of statements
2546 left to move. `Statements' do not include blank, comment, or
2547 continuation lines."
2548 (interactive "p") ; numeric prefix arg
2549 (if (< count 0) (py-next-statement (- count))
2550 (py-goto-initial-line)
2551 (let (start)
2552 (while (and
2553 (setq start (point)) ; always true -- side effect
2554 (> count 0)
2555 (zerop (forward-line -1))
2556 (py-goto-statement-at-or-above))
2557 (setq count (1- count)))
2558 (if (> count 0) (goto-char start)))
2559 count))
2560
2561 (defun py-next-statement (count)
2562 "Go to the start of next Python statement.
2563 If the statement at point is the i'th Python statement, goes to the
2564 start of statement i+COUNT. If there is no such statement, goes to the
2565 last statement. Returns count of statements left to move. `Statements'
2566 do not include blank, comment, or continuation lines."
2567 (interactive "p") ; numeric prefix arg
2568 (if (< count 0) (py-previous-statement (- count))
2569 (beginning-of-line)
2570 (let (start)
2571 (while (and
2572 (setq start (point)) ; always true -- side effect
2573 (> count 0)
2574 (py-goto-statement-below))
2575 (setq count (1- count)))
2576 (if (> count 0) (goto-char start)))
2577 count))
2578
2579 (defun py-goto-block-up (&optional nomark)
2580 "Move up to start of current block.
2581 Go to the statement that starts the smallest enclosing block; roughly
2582 speaking, this will be the closest preceding statement that ends with a
2583 colon and is indented less than the statement you started on. If
2584 successful, also sets the mark to the starting point.
2585
2586 `\\[py-mark-block]' can be used afterward to mark the whole code
2587 block, if desired.
2588
2589 If called from a program, the mark will not be set if optional argument
2590 NOMARK is not nil."
2591 (interactive)
2592 (let ((start (point))
2593 (found nil)
2594 initial-indent)
2595 (py-goto-initial-line)
2596 ;; if on blank or non-indenting comment line, use the preceding stmt
2597 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2598 (progn
2599 (py-goto-statement-at-or-above)
2600 (setq found (py-statement-opens-block-p))))
2601 ;; search back for colon line indented less
2602 (setq initial-indent (current-indentation))
2603 (if (zerop initial-indent)
2604 ;; force fast exit
2605 (goto-char (point-min)))
2606 (while (not (or found (bobp)))
2607 (setq found
2608 (and
2609 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2610 (or (py-goto-initial-line) t) ; always true -- side effect
2611 (< (current-indentation) initial-indent)
2612 (py-statement-opens-block-p))))
2613 (if found
2614 (progn
2615 (or nomark (push-mark start))
2616 (back-to-indentation))
2617 (goto-char start)
2618 (error "Enclosing block not found"))))
2619
2620 (defun py-beginning-of-def-or-class (&optional class count)
2621 "Move point to start of `def' or `class'.
2622
2623 Searches back for the closest preceding `def'. If you supply a prefix
2624 arg, looks for a `class' instead. The docs below assume the `def'
2625 case; just substitute `class' for `def' for the other case.
2626 Programmatically, if CLASS is `either', then moves to either `class'
2627 or `def'.
2628
2629 When second optional argument is given programmatically, move to the
2630 COUNTth start of `def'.
2631
2632 If point is in a `def' statement already, and after the `d', simply
2633 moves point to the start of the statement.
2634
2635 Otherwise (i.e. when point is not in a `def' statement, or at or
2636 before the `d' of a `def' statement), searches for the closest
2637 preceding `def' statement, and leaves point at its start. If no such
2638 statement can be found, leaves point at the start of the buffer.
2639
2640 Returns t iff a `def' statement is found by these rules.
2641
2642 Note that doing this command repeatedly will take you closer to the
2643 start of the buffer each time.
2644
2645 To mark the current `def', see `\\[py-mark-def-or-class]'."
2646 (interactive "P") ; raw prefix arg
2647 (setq count (or count 1))
2648 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2649 (start-of-line (goto-char (py-point 'bol)))
2650 (start-of-stmt (goto-char (py-point 'bos)))
2651 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2652 (class "^[ \t]*class\\>")
2653 (t "^[ \t]*def\\>")))
2654 )
2655 ;; searching backward
2656 (if (and (< 0 count)
2657 (or (/= start-of-stmt start-of-line)
2658 (not at-or-before-p)))
2659 (end-of-line))
2660 ;; search forward
2661 (if (and (> 0 count)
2662 (zerop (current-column))
2663 (looking-at start-re))
2664 (end-of-line))
2665 (if (re-search-backward start-re nil 'move count)
2666 (goto-char (match-beginning 0)))))
2667
2668 ;; Backwards compatibility
2669 (defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
2670
2671 (defun py-end-of-def-or-class (&optional class count)
2672 "Move point beyond end of `def' or `class' body.
2673
2674 By default, looks for an appropriate `def'. If you supply a prefix
2675 arg, looks for a `class' instead. The docs below assume the `def'
2676 case; just substitute `class' for `def' for the other case.
2677 Programmatically, if CLASS is `either', then moves to either `class'
2678 or `def'.
2679
2680 When second optional argument is given programmatically, move to the
2681 COUNTth end of `def'.
2682
2683 If point is in a `def' statement already, this is the `def' we use.
2684
2685 Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2686 contains the statement you started on, that's the `def' we use.
2687
2688 Otherwise, we search forward for the closest following `def', and use that.
2689
2690 If a `def' can be found by these rules, point is moved to the start of
2691 the line immediately following the `def' block, and the position of the
2692 start of the `def' is returned.
2693
2694 Else point is moved to the end of the buffer, and nil is returned.
2695
2696 Note that doing this command repeatedly will take you closer to the
2697 end of the buffer each time.
2698
2699 To mark the current `def', see `\\[py-mark-def-or-class]'."
2700 (interactive "P") ; raw prefix arg
2701 (if (and count (/= count 1))
2702 (py-beginning-of-def-or-class (- 1 count)))
2703 (let ((start (progn (py-goto-initial-line) (point)))
2704 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2705 (class "class")
2706 (t "def")))
2707 (state 'not-found))
2708 ;; move point to start of appropriate def/class
2709 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2710 (setq state 'at-beginning)
2711 ;; else see if py-beginning-of-def-or-class hits container
2712 (if (and (py-beginning-of-def-or-class class)
2713 (progn (py-goto-beyond-block)
2714 (> (point) start)))
2715 (setq state 'at-end)
2716 ;; else search forward
2717 (goto-char start)
2718 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2719 (progn (setq state 'at-beginning)
2720 (beginning-of-line)))))
2721 (cond
2722 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2723 ((eq state 'at-end) t)
2724 ((eq state 'not-found) nil)
2725 (t (error "Internal error in `py-end-of-def-or-class'")))))
2726
2727 ;; Backwards compabitility
2728 (defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
2729
2730
2731 ;; Functions for marking regions
2732 (defun py-mark-block (&optional extend just-move)
2733 "Mark following block of lines. With prefix arg, mark structure.
2734 Easier to use than explain. It sets the region to an `interesting'
2735 block of succeeding lines. If point is on a blank line, it goes down to
2736 the next non-blank line. That will be the start of the region. The end
2737 of the region depends on the kind of line at the start:
2738
2739 - If a comment, the region will include all succeeding comment lines up
2740 to (but not including) the next non-comment line (if any).
2741
2742 - Else if a prefix arg is given, and the line begins one of these
2743 structures:
2744
2745 if elif else try except finally for while def class
2746
2747 the region will be set to the body of the structure, including
2748 following blocks that `belong' to it, but excluding trailing blank
2749 and comment lines. E.g., if on a `try' statement, the `try' block
2750 and all (if any) of the following `except' and `finally' blocks
2751 that belong to the `try' structure will be in the region. Ditto
2752 for if/elif/else, for/else and while/else structures, and (a bit
2753 degenerate, since they're always one-block structures) def and
2754 class blocks.
2755
2756 - Else if no prefix argument is given, and the line begins a Python
2757 block (see list above), and the block is not a `one-liner' (i.e.,
2758 the statement ends with a colon, not with code), the region will
2759 include all succeeding lines up to (but not including) the next
2760 code statement (if any) that's indented no more than the starting
2761 line, except that trailing blank and comment lines are excluded.
2762 E.g., if the starting line begins a multi-statement `def'
2763 structure, the region will be set to the full function definition,
2764 but without any trailing `noise' lines.
2765
2766 - Else the region will include all succeeding lines up to (but not
2767 including) the next blank line, or code or indenting-comment line
2768 indented strictly less than the starting line. Trailing indenting
2769 comment lines are included in this case, but not trailing blank
2770 lines.
2771
2772 A msg identifying the location of the mark is displayed in the echo
2773 area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2774
2775 If called from a program, optional argument EXTEND plays the role of
2776 the prefix arg, and if optional argument JUST-MOVE is not nil, just
2777 moves to the end of the block (& does not set mark or display a msg)."
2778 (interactive "P") ; raw prefix arg
2779 (py-goto-initial-line)
2780 ;; skip over blank lines
2781 (while (and
2782 (looking-at "[ \t]*$") ; while blank line
2783 (not (eobp))) ; & somewhere to go
2784 (forward-line 1))
2785 (if (eobp)
2786 (error "Hit end of buffer without finding a non-blank stmt"))
2787 (let ((initial-pos (point))
2788 (initial-indent (current-indentation))
2789 last-pos ; position of last stmt in region
2790 (followers
2791 '((if elif else) (elif elif else) (else)
2792 (try except finally) (except except) (finally)
2793 (for else) (while else)
2794 (def) (class) ) )
2795 first-symbol next-symbol)
2796
2797 (cond
2798 ;; if comment line, suck up the following comment lines
2799 ((looking-at "[ \t]*#")
2800 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2801 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2802 (setq last-pos (point)))
2803
2804 ;; else if line is a block line and EXTEND given, suck up
2805 ;; the whole structure
2806 ((and extend
2807 (setq first-symbol (py-suck-up-first-keyword) )
2808 (assq first-symbol followers))
2809 (while (and
2810 (or (py-goto-beyond-block) t) ; side effect
2811 (forward-line -1) ; side effect
2812 (setq last-pos (point)) ; side effect
2813 (py-goto-statement-below)
2814 (= (current-indentation) initial-indent)
2815 (setq next-symbol (py-suck-up-first-keyword))
2816 (memq next-symbol (cdr (assq first-symbol followers))))
2817 (setq first-symbol next-symbol)))
2818
2819 ;; else if line *opens* a block, search for next stmt indented <=
2820 ((py-statement-opens-block-p)
2821 (while (and
2822 (setq last-pos (point)) ; always true -- side effect
2823 (py-goto-statement-below)
2824 (> (current-indentation) initial-indent)
2825 )))
2826
2827 ;; else plain code line; stop at next blank line, or stmt or
2828 ;; indenting comment line indented <
2829 (t
2830 (while (and
2831 (setq last-pos (point)) ; always true -- side effect
2832 (or (py-goto-beyond-final-line) t)
2833 (not (looking-at "[ \t]*$")) ; stop at blank line
2834 (or
2835 (>= (current-indentation) initial-indent)
2836 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2837 nil)))
2838
2839 ;; skip to end of last stmt
2840 (goto-char last-pos)
2841 (py-goto-beyond-final-line)
2842
2843 ;; set mark & display
2844 (if just-move
2845 () ; just return
2846 (push-mark (point) 'no-msg)
2847 (forward-line -1)
2848 (message "Mark set after: %s" (py-suck-up-leading-text))
2849 (goto-char initial-pos))))
2850
2851 (defun py-mark-def-or-class (&optional class)
2852 "Set region to body of def (or class, with prefix arg) enclosing point.
2853 Pushes the current mark, then point, on the mark ring (all language
2854 modes do this, but although it's handy it's never documented ...).
2855
2856 In most Emacs language modes, this function bears at least a
2857 hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2858 `\\[py-beginning-of-def-or-class]'.
2859
2860 And in earlier versions of Python mode, all 3 were tightly connected.
2861 Turned out that was more confusing than useful: the `goto start' and
2862 `goto end' commands are usually used to search through a file, and
2863 people expect them to act a lot like `search backward' and `search
2864 forward' string-search commands. But because Python `def' and `class'
2865 can nest to arbitrary levels, finding the smallest def containing
2866 point cannot be done via a simple backward search: the def containing
2867 point may not be the closest preceding def, or even the closest
2868 preceding def that's indented less. The fancy algorithm required is
2869 appropriate for the usual uses of this `mark' command, but not for the
2870 `goto' variations.
2871
2872 So the def marked by this command may not be the one either of the
2873 `goto' commands find: If point is on a blank or non-indenting comment
2874 line, moves back to start of the closest preceding code statement or
2875 indenting comment line. If this is a `def' statement, that's the def
2876 we use. Else searches for the smallest enclosing `def' block and uses
2877 that. Else signals an error.
2878
2879 When an enclosing def is found: The mark is left immediately beyond
2880 the last line of the def block. Point is left at the start of the
2881 def, except that: if the def is preceded by a number of comment lines
2882 followed by (at most) one optional blank line, point is left at the
2883 start of the comments; else if the def is preceded by a blank line,
2884 point is left at its start.
2885
2886 The intent is to mark the containing def/class and its associated
2887 documentation, to make moving and duplicating functions and classes
2888 pleasant."
2889 (interactive "P") ; raw prefix arg
2890 (let ((start (point))
2891 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2892 (class "class")
2893 (t "def"))))
2894 (push-mark start)
2895 (if (not (py-go-up-tree-to-keyword which))
2896 (progn (goto-char start)
2897 (error "Enclosing %s not found"
2898 (if (eq class 'either)
2899 "def or class"
2900 which)))
2901 ;; else enclosing def/class found
2902 (setq start (point))
2903 (py-goto-beyond-block)
2904 (push-mark (point))
2905 (goto-char start)
2906 (if (zerop (forward-line -1)) ; if there is a preceding line
2907 (progn
2908 (if (looking-at "[ \t]*$") ; it's blank
2909 (setq start (point)) ; so reset start point
2910 (goto-char start)) ; else try again
2911 (if (zerop (forward-line -1))
2912 (if (looking-at "[ \t]*#") ; a comment
2913 ;; look back for non-comment line
2914 ;; tricky: note that the regexp matches a blank
2915 ;; line, cuz \n is in the 2nd character class
2916 (and
2917 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2918 (forward-line 1))
2919 ;; no comment, so go back
2920 (goto-char start)))))))
2921 (exchange-point-and-mark)
2922 (py-keep-region-active))
2923
2924 ;; ripped from cc-mode
2925 (defun py-forward-into-nomenclature (&optional arg)
2926 "Move forward to end of a nomenclature section or word.
2927 With \\[universal-argument] (programmatically, optional argument ARG),
2928 do it that many times.
2929
2930 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2931 (interactive "p")
2932 (let ((case-fold-search nil))
2933 (if (> arg 0)
2934 (re-search-forward
2935 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2936 (point-max) t arg)
2937 (while (and (< arg 0)
2938 (re-search-backward
2939 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
2940 (point-min) 0))
2941 (forward-char 1)
2942 (setq arg (1+ arg)))))
2943 (py-keep-region-active))
2944
2945 (defun py-backward-into-nomenclature (&optional arg)
2946 "Move backward to beginning of a nomenclature section or word.
2947 With optional ARG, move that many times. If ARG is negative, move
2948 forward.
2949
2950 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2951 (interactive "p")
2952 (py-forward-into-nomenclature (- arg))
2953 (py-keep-region-active))
2954
2955
2956
2957 ;; pdbtrack functions
2958 (defun py-pdbtrack-toggle-stack-tracking (arg)
2959 (interactive "P")
2960 (if (not (get-buffer-process (current-buffer)))
2961 (error "No process associated with buffer '%s'" (current-buffer)))
2962 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2963 (if (or (not arg)
2964 (zerop (setq arg (prefix-numeric-value arg))))
2965 (setq py-pdbtrack-do-tracking-p (not py-pdbtrack-do-tracking-p))
2966 (setq py-pdbtrack-do-tracking-p (> arg 0)))
2967 (message "%sabled Python's pdbtrack"
2968 (if py-pdbtrack-do-tracking-p "En" "Dis")))
2969
2970 (defun turn-on-pdbtrack ()
2971 (interactive)
2972 (py-pdbtrack-toggle-stack-tracking 1))
2973
2974 (defun turn-off-pdbtrack ()
2975 (interactive)
2976 (py-pdbtrack-toggle-stack-tracking 0))
2977
2978
2979
2980 ;; Pychecker
2981
2982 ;; hack for FSF Emacs
2983 (unless (fboundp 'read-shell-command)
2984 (defalias 'read-shell-command 'read-string))
2985
2986 (defun py-pychecker-run (command)
2987 "*Run pychecker (default on the file currently visited)."
2988 (interactive
2989 (let ((default
2990 (format "%s %s %s" py-pychecker-command
2991 (mapconcat 'identity py-pychecker-command-args " ")
2992 (buffer-file-name)))
2993 (last (when py-pychecker-history
2994 (let* ((lastcmd (car py-pychecker-history))
2995 (cmd (cdr (reverse (split-string lastcmd))))
2996 (newcmd (reverse (cons (buffer-file-name) cmd))))
2997 (mapconcat 'identity newcmd " ")))))
2998
2999 (list
3000 (if (fboundp 'read-shell-command)
3001 (read-shell-command "Run pychecker like this: "
3002 (if last
3003 last
3004 default)
3005 'py-pychecker-history)
3006 (read-string "Run pychecker like this: "
3007 (if last
3008 last
3009 default)
3010 'py-pychecker-history))
3011 )))
3012 (save-some-buffers (not py-ask-about-save) nil)
3013 (compile-internal command "No more errors"))
3014
3015
3016
3017 ;; pydoc commands. The guts of this function is stolen from XEmacs's
3018 ;; symbol-near-point, but without the useless regexp-quote call on the
3019 ;; results, nor the interactive bit. Also, we've added the temporary
3020 ;; syntax table setting, which Skip originally had broken out into a
3021 ;; separate function. Note that Emacs doesn't have the original
3022 ;; function.
3023 (defun py-symbol-near-point ()
3024 "Return the first textual item to the nearest point."
3025 ;; alg stolen from etag.el
3026 (save-excursion
3027 (with-syntax-table py-dotted-expression-syntax-table
3028 (if (or (bobp) (not (memq (char-syntax (char-before)) '(?w ?_))))
3029 (while (not (looking-at "\\sw\\|\\s_\\|\\'"))
3030 (forward-char 1)))
3031 (while (looking-at "\\sw\\|\\s_")
3032 (forward-char 1))
3033 (if (re-search-backward "\\sw\\|\\s_" nil t)
3034 (progn (forward-char 1)
3035 (buffer-substring (point)
3036 (progn (forward-sexp -1)
3037 (while (looking-at "\\s'")
3038 (forward-char 1))
3039 (point))))
3040 nil))))
3041
3042 (defun py-help-at-point ()
3043 "Get help from Python based on the symbol nearest point."
3044 (interactive)
3045 (let* ((sym (py-symbol-near-point))
3046 (base (substring sym 0 (or (search "." sym :from-end t) 0)))
3047 cmd)
3048 (if (not (equal base ""))
3049 (setq cmd (concat "import " base "\n")))
3050 (setq cmd (concat "import pydoc\n"
3051 cmd
3052 "try: pydoc.help('" sym "')\n"
3053 "except: print 'No help available on:', \"" sym "\""))
3054 (message cmd)
3055 (py-execute-string cmd)
3056 (set-buffer "*Python Output*")
3057 ;; BAW: Should we really be leaving the output buffer in help-mode?
3058 (help-mode)))
3059
3060
3061
3062 ;; Documentation functions
3063
3064 ;; dump the long form of the mode blurb; does the usual doc escapes,
3065 ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
3066 ;; out of the right places, along with the keys they're on & current
3067 ;; values
3068 (defun py-dump-help-string (str)
3069 (with-output-to-temp-buffer "*Help*"
3070 (let ((locals (buffer-local-variables))
3071 funckind funcname func funcdoc
3072 (start 0) mstart end
3073 keys )
3074 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
3075 (setq mstart (match-beginning 0) end (match-end 0)
3076 funckind (substring str (match-beginning 1) (match-end 1))
3077 funcname (substring str (match-beginning 2) (match-end 2))
3078 func (intern funcname))
3079 (princ (substitute-command-keys (substring str start mstart)))
3080 (cond
3081 ((equal funckind "c") ; command
3082 (setq funcdoc (documentation func)
3083 keys (concat
3084 "Key(s): "
3085 (mapconcat 'key-description
3086 (where-is-internal func py-mode-map)
3087 ", "))))
3088 ((equal funckind "v") ; variable
3089 (setq funcdoc (documentation-property func 'variable-documentation)
3090 keys (if (assq func locals)
3091 (concat
3092 "Local/Global values: "
3093 (prin1-to-string (symbol-value func))
3094 " / "
3095 (prin1-to-string (default-value func)))
3096 (concat
3097 "Value: "
3098 (prin1-to-string (symbol-value func))))))
3099 (t ; unexpected
3100 (error "Error in py-dump-help-string, tag `%s'" funckind)))
3101 (princ (format "\n-> %s:\t%s\t%s\n\n"
3102 (if (equal funckind "c") "Command" "Variable")
3103 funcname keys))
3104 (princ funcdoc)
3105 (terpri)
3106 (setq start end))
3107 (princ (substitute-command-keys (substring str start))))
3108 (print-help-return-message)))
3109
3110 (defun py-describe-mode ()
3111 "Dump long form of Python-mode docs."
3112 (interactive)
3113 (py-dump-help-string "Major mode for editing Python files.
3114 Knows about Python indentation, tokens, comments and continuation lines.
3115 Paragraphs are separated by blank lines only.
3116
3117 Major sections below begin with the string `@'; specific function and
3118 variable docs begin with `->'.
3119
3120 @EXECUTING PYTHON CODE
3121
3122 \\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
3123 \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
3124 \\[py-execute-region]\tsends the current region
3125 \\[py-execute-def-or-class]\tsends the current function or class definition
3126 \\[py-execute-string]\tsends an arbitrary string
3127 \\[py-shell]\tstarts a Python interpreter window; this will be used by
3128 \tsubsequent Python execution commands
3129 %c:py-execute-import-or-reload
3130 %c:py-execute-buffer
3131 %c:py-execute-region
3132 %c:py-execute-def-or-class
3133 %c:py-execute-string
3134 %c:py-shell
3135
3136 @VARIABLES
3137
3138 py-indent-offset\tindentation increment
3139 py-block-comment-prefix\tcomment string used by comment-region
3140
3141 py-python-command\tshell command to invoke Python interpreter
3142 py-temp-directory\tdirectory used for temp files (if needed)
3143
3144 py-beep-if-tab-change\tring the bell if tab-width is changed
3145 %v:py-indent-offset
3146 %v:py-block-comment-prefix
3147 %v:py-python-command
3148 %v:py-temp-directory
3149 %v:py-beep-if-tab-change
3150
3151 @KINDS OF LINES
3152
3153 Each physical line in the file is either a `continuation line' (the
3154 preceding line ends with a backslash that's not part of a comment, or
3155 the paren/bracket/brace nesting level at the start of the line is
3156 non-zero, or both) or an `initial line' (everything else).
3157
3158 An initial line is in turn a `blank line' (contains nothing except
3159 possibly blanks or tabs), a `comment line' (leftmost non-blank
3160 character is `#'), or a `code line' (everything else).
3161
3162 Comment Lines
3163
3164 Although all comment lines are treated alike by Python, Python mode
3165 recognizes two kinds that act differently with respect to indentation.
3166
3167 An `indenting comment line' is a comment line with a blank, tab or
3168 nothing after the initial `#'. The indentation commands (see below)
3169 treat these exactly as if they were code lines: a line following an
3170 indenting comment line will be indented like the comment line. All
3171 other comment lines (those with a non-whitespace character immediately
3172 following the initial `#') are `non-indenting comment lines', and
3173 their indentation is ignored by the indentation commands.
3174
3175 Indenting comment lines are by far the usual case, and should be used
3176 whenever possible. Non-indenting comment lines are useful in cases
3177 like these:
3178
3179 \ta = b # a very wordy single-line comment that ends up being
3180 \t #... continued onto another line
3181
3182 \tif a == b:
3183 ##\t\tprint 'panic!' # old code we've `commented out'
3184 \t\treturn a
3185
3186 Since the `#...' and `##' comment lines have a non-whitespace
3187 character following the initial `#', Python mode ignores them when
3188 computing the proper indentation for the next line.
3189
3190 Continuation Lines and Statements
3191
3192 The Python-mode commands generally work on statements instead of on
3193 individual lines, where a `statement' is a comment or blank line, or a
3194 code line and all of its following continuation lines (if any)
3195 considered as a single logical unit. The commands in this mode
3196 generally (when it makes sense) automatically move to the start of the
3197 statement containing point, even if point happens to be in the middle
3198 of some continuation line.
3199
3200
3201 @INDENTATION
3202
3203 Primarily for entering new code:
3204 \t\\[indent-for-tab-command]\t indent line appropriately
3205 \t\\[py-newline-and-indent]\t insert newline, then indent
3206 \t\\[py-electric-backspace]\t reduce indentation, or delete single character
3207
3208 Primarily for reindenting existing code:
3209 \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
3210 \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
3211
3212 \t\\[py-indent-region]\t reindent region to match its context
3213 \t\\[py-shift-region-left]\t shift region left by py-indent-offset
3214 \t\\[py-shift-region-right]\t shift region right by py-indent-offset
3215
3216 Unlike most programming languages, Python uses indentation, and only
3217 indentation, to specify block structure. Hence the indentation supplied
3218 automatically by Python-mode is just an educated guess: only you know
3219 the block structure you intend, so only you can supply correct
3220 indentation.
3221
3222 The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
3223 the indentation of preceding statements. E.g., assuming
3224 py-indent-offset is 4, after you enter
3225 \tif a > 0: \\[py-newline-and-indent]
3226 the cursor will be moved to the position of the `_' (_ is not a
3227 character in the file, it's just used here to indicate the location of
3228 the cursor):
3229 \tif a > 0:
3230 \t _
3231 If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
3232 to
3233 \tif a > 0:
3234 \t c = d
3235 \t _
3236 Python-mode cannot know whether that's what you intended, or whether
3237 \tif a > 0:
3238 \t c = d
3239 \t_
3240 was your intent. In general, Python-mode either reproduces the
3241 indentation of the (closest code or indenting-comment) preceding
3242 statement, or adds an extra py-indent-offset blanks if the preceding
3243 statement has `:' as its last significant (non-whitespace and non-
3244 comment) character. If the suggested indentation is too much, use
3245 \\[py-electric-backspace] to reduce it.
3246
3247 Continuation lines are given extra indentation. If you don't like the
3248 suggested indentation, change it to something you do like, and Python-
3249 mode will strive to indent later lines of the statement in the same way.
3250
3251 If a line is a continuation line by virtue of being in an unclosed
3252 paren/bracket/brace structure (`list', for short), the suggested
3253 indentation depends on whether the current line contains the first item
3254 in the list. If it does, it's indented py-indent-offset columns beyond
3255 the indentation of the line containing the open bracket. If you don't
3256 like that, change it by hand. The remaining items in the list will mimic
3257 whatever indentation you give to the first item.
3258
3259 If a line is a continuation line because the line preceding it ends with
3260 a backslash, the third and following lines of the statement inherit their
3261 indentation from the line preceding them. The indentation of the second
3262 line in the statement depends on the form of the first (base) line: if
3263 the base line is an assignment statement with anything more interesting
3264 than the backslash following the leftmost assigning `=', the second line
3265 is indented two columns beyond that `='. Else it's indented to two
3266 columns beyond the leftmost solid chunk of non-whitespace characters on
3267 the base line.
3268
3269 Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
3270 repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
3271 structure you intend.
3272 %c:indent-for-tab-command
3273 %c:py-newline-and-indent
3274 %c:py-electric-backspace
3275
3276
3277 The next function may be handy when editing code you didn't write:
3278 %c:py-guess-indent-offset
3279
3280
3281 The remaining `indent' functions apply to a region of Python code. They
3282 assume the block structure (equals indentation, in Python) of the region
3283 is correct, and alter the indentation in various ways while preserving
3284 the block structure:
3285 %c:py-indent-region
3286 %c:py-shift-region-left
3287 %c:py-shift-region-right
3288
3289 @MARKING & MANIPULATING REGIONS OF CODE
3290
3291 \\[py-mark-block]\t mark block of lines
3292 \\[py-mark-def-or-class]\t mark smallest enclosing def
3293 \\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
3294 \\[comment-region]\t comment out region of code
3295 \\[universal-argument] \\[comment-region]\t uncomment region of code
3296 %c:py-mark-block
3297 %c:py-mark-def-or-class
3298 %c:comment-region
3299
3300 @MOVING POINT
3301
3302 \\[py-previous-statement]\t move to statement preceding point
3303 \\[py-next-statement]\t move to statement following point
3304 \\[py-goto-block-up]\t move up to start of current block
3305 \\[py-beginning-of-def-or-class]\t move to start of def
3306 \\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
3307 \\[py-end-of-def-or-class]\t move to end of def
3308 \\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
3309
3310 The first two move to one statement beyond the statement that contains
3311 point. A numeric prefix argument tells them to move that many
3312 statements instead. Blank lines, comment lines, and continuation lines
3313 do not count as `statements' for these commands. So, e.g., you can go
3314 to the first code statement in a file by entering
3315 \t\\[beginning-of-buffer]\t to move to the top of the file
3316 \t\\[py-next-statement]\t to skip over initial comments and blank lines
3317 Or do `\\[py-previous-statement]' with a huge prefix argument.
3318 %c:py-previous-statement
3319 %c:py-next-statement
3320 %c:py-goto-block-up
3321 %c:py-beginning-of-def-or-class
3322 %c:py-end-of-def-or-class
3323
3324 @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
3325
3326 `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
3327
3328 `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
3329 overall class and def structure of a module.
3330
3331 `\\[back-to-indentation]' moves point to a line's first non-blank character.
3332
3333 `\\[indent-relative]' is handy for creating odd indentation.
3334
3335 @OTHER EMACS HINTS
3336
3337 If you don't like the default value of a variable, change its value to
3338 whatever you do like by putting a `setq' line in your .emacs file.
3339 E.g., to set the indentation increment to 4, put this line in your
3340 .emacs:
3341 \t(setq py-indent-offset 4)
3342 To see the value of a variable, do `\\[describe-variable]' and enter the variable
3343 name at the prompt.
3344
3345 When entering a key sequence like `C-c C-n', it is not necessary to
3346 release the CONTROL key after doing the `C-c' part -- it suffices to
3347 press the CONTROL key, press and release `c' (while still holding down
3348 CONTROL), press and release `n' (while still holding down CONTROL), &
3349 then release CONTROL.
3350
3351 Entering Python mode calls with no arguments the value of the variable
3352 `python-mode-hook', if that value exists and is not nil; for backward
3353 compatibility it also tries `py-mode-hook'; see the `Hooks' section of
3354 the Elisp manual for details.
3355
3356 Obscure: When python-mode is first loaded, it looks for all bindings
3357 to newline-and-indent in the global keymap, and shadows them with
3358 local bindings to py-newline-and-indent."))
3359
3360 (require 'info-look)
3361 ;; The info-look package does not always provide this function (it
3362 ;; appears this is the case with XEmacs 21.1)
3363 (when (fboundp 'info-lookup-maybe-add-help)
3364 (info-lookup-maybe-add-help
3365 :mode 'python-mode
3366 :regexp "[a-zA-Z0-9_]+"
3367 :doc-spec '(("(python-lib)Module Index")
3368 ("(python-lib)Class-Exception-Object Index")
3369 ("(python-lib)Function-Method-Variable Index")
3370 ("(python-lib)Miscellaneous Index")))
3371 )
3372
3373
3374 ;; Helper functions
3375 (defvar py-parse-state-re
3376 (concat
3377 "^[ \t]*\\(elif\\|else\\|while\\|def\\|class\\)\\>"
3378 "\\|"
3379 "^[^ #\t\n]"))
3380
3381 (defun py-parse-state ()
3382 "Return the parse state at point (see `parse-partial-sexp' docs)."
3383 (save-excursion
3384 (let ((here (point))
3385 pps done)
3386 (while (not done)
3387 ;; back up to the first preceding line (if any; else start of
3388 ;; buffer) that begins with a popular Python keyword, or a
3389 ;; non- whitespace and non-comment character. These are good
3390 ;; places to start parsing to see whether where we started is
3391 ;; at a non-zero nesting level. It may be slow for people who
3392 ;; write huge code blocks or huge lists ... tough beans.
3393 (re-search-backward py-parse-state-re nil 'move)
3394 (beginning-of-line)
3395 ;; In XEmacs, we have a much better way to test for whether
3396 ;; we're in a triple-quoted string or not. Emacs does not
3397 ;; have this built-in function, which is its loss because
3398 ;; without scanning from the beginning of the buffer, there's
3399 ;; no accurate way to determine this otherwise.
3400 (save-excursion (setq pps (parse-partial-sexp (point) here)))
3401 ;; make sure we don't land inside a triple-quoted string
3402 (setq done (or (not (nth 3 pps))
3403 (bobp)))
3404 ;; Just go ahead and short circuit the test back to the
3405 ;; beginning of the buffer. This will be slow, but not
3406 ;; nearly as slow as looping through many
3407 ;; re-search-backwards.
3408 (if (not done)
3409 (goto-char (point-min))))
3410 pps)))
3411
3412 (defun py-nesting-level ()
3413 "Return the buffer position of the last unclosed enclosing list.
3414 If nesting level is zero, return nil."
3415 (let ((status (py-parse-state)))
3416 (if (zerop (car status))
3417 nil ; not in a nest
3418 (car (cdr status))))) ; char# of open bracket
3419
3420 (defun py-backslash-continuation-line-p ()
3421 "Return t iff preceding line ends with backslash that is not in a comment."
3422 (save-excursion
3423 (beginning-of-line)
3424 (and
3425 ;; use a cheap test first to avoid the regexp if possible
3426 ;; use 'eq' because char-after may return nil
3427 (eq (char-after (- (point) 2)) ?\\ )
3428 ;; make sure; since eq test passed, there is a preceding line
3429 (forward-line -1) ; always true -- side effect
3430 (looking-at py-continued-re))))
3431
3432 (defun py-continuation-line-p ()
3433 "Return t iff current line is a continuation line."
3434 (save-excursion
3435 (beginning-of-line)
3436 (or (py-backslash-continuation-line-p)
3437 (py-nesting-level))))
3438
3439 (defun py-goto-beginning-of-tqs (delim)
3440 "Go to the beginning of the triple quoted string we find ourselves in.
3441 DELIM is the TQS string delimiter character we're searching backwards
3442 for."
3443 (let ((skip (and delim (make-string 1 delim)))
3444 (continue t))
3445 (when skip
3446 (save-excursion
3447 (while continue
3448 (py-safe (search-backward skip))
3449 (setq continue (and (not (bobp))
3450 (= (char-before) ?\\))))
3451 (if (and (= (char-before) delim)
3452 (= (char-before (1- (point))) delim))
3453 (setq skip (make-string 3 delim))))
3454 ;; we're looking at a triple-quoted string
3455 (py-safe (search-backward skip)))))
3456
3457 (defun py-goto-initial-line ()
3458 "Go to the initial line of the current statement.
3459 Usually this is the line we're on, but if we're on the 2nd or
3460 following lines of a continuation block, we need to go up to the first
3461 line of the block."
3462 ;; Tricky: We want to avoid quadratic-time behavior for long
3463 ;; continued blocks, whether of the backslash or open-bracket
3464 ;; varieties, or a mix of the two. The following manages to do that
3465 ;; in the usual cases.
3466 ;;
3467 ;; Also, if we're sitting inside a triple quoted string, this will
3468 ;; drop us at the line that begins the string.
3469 (let (open-bracket-pos)
3470 (while (py-continuation-line-p)
3471 (beginning-of-line)
3472 (if (py-backslash-continuation-line-p)
3473 (while (py-backslash-continuation-line-p)
3474 (forward-line -1))
3475 ;; else zip out of nested brackets/braces/parens
3476 (while (setq open-bracket-pos (py-nesting-level))
3477 (goto-char open-bracket-pos)))))
3478 (beginning-of-line))
3479
3480 (defun py-goto-beyond-final-line ()
3481 "Go to the point just beyond the fine line of the current statement.
3482 Usually this is the start of the next line, but if this is a
3483 multi-line statement we need to skip over the continuation lines."
3484 ;; Tricky: Again we need to be clever to avoid quadratic time
3485 ;; behavior.
3486 ;;
3487 ;; XXX: Not quite the right solution, but deals with multi-line doc
3488 ;; strings
3489 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
3490 (goto-char (match-end 0)))
3491 ;;
3492 (forward-line 1)
3493 (let (state)
3494 (while (and (py-continuation-line-p)
3495 (not (eobp)))
3496 ;; skip over the backslash flavor
3497 (while (and (py-backslash-continuation-line-p)
3498 (not (eobp)))
3499 (forward-line 1))
3500 ;; if in nest, zip to the end of the nest
3501 (setq state (py-parse-state))
3502 (if (and (not (zerop (car state)))
3503 (not (eobp)))
3504 (progn
3505 (parse-partial-sexp (point) (point-max) 0 nil state)
3506 (forward-line 1))))))
3507
3508 (defun py-statement-opens-block-p ()
3509 "Return t iff the current statement opens a block.
3510 I.e., iff it ends with a colon that is not in a comment. Point should
3511 be at the start of a statement."
3512 (save-excursion
3513 (let ((start (point))
3514 (finish (progn (py-goto-beyond-final-line) (1- (point))))
3515 (searching t)
3516 (answer nil)
3517 state)
3518 (goto-char start)
3519 (while searching
3520 ;; look for a colon with nothing after it except whitespace, and
3521 ;; maybe a comment
3522 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
3523 finish t)
3524 (if (eq (point) finish) ; note: no `else' clause; just
3525 ; keep searching if we're not at
3526 ; the end yet
3527 ;; sure looks like it opens a block -- but it might
3528 ;; be in a comment
3529 (progn
3530 (setq searching nil) ; search is done either way
3531 (setq state (parse-partial-sexp start
3532 (match-beginning 0)))
3533 (setq answer (not (nth 4 state)))))
3534 ;; search failed: couldn't find another interesting colon
3535 (setq searching nil)))
3536 answer)))
3537
3538 (defun py-statement-closes-block-p ()
3539 "Return t iff the current statement closes a block.
3540 I.e., if the line starts with `return', `raise', `break', `continue',
3541 and `pass'. This doesn't catch embedded statements."
3542 (let ((here (point)))
3543 (py-goto-initial-line)
3544 (back-to-indentation)
3545 (prog1
3546 (looking-at (concat py-block-closing-keywords-re "\\>"))
3547 (goto-char here))))
3548
3549 (defun py-goto-beyond-block ()
3550 "Go to point just beyond the final line of block begun by the current line.
3551 This is the same as where `py-goto-beyond-final-line' goes unless
3552 we're on colon line, in which case we go to the end of the block.
3553 Assumes point is at the beginning of the line."
3554 (if (py-statement-opens-block-p)
3555 (py-mark-block nil 'just-move)
3556 (py-goto-beyond-final-line)))
3557
3558 (defun py-goto-statement-at-or-above ()
3559 "Go to the start of the first statement at or preceding point.
3560 Return t if there is such a statement, otherwise nil. `Statement'
3561 does not include blank lines, comments, or continuation lines."
3562 (py-goto-initial-line)
3563 (if (looking-at py-blank-or-comment-re)
3564 ;; skip back over blank & comment lines
3565 ;; note: will skip a blank or comment line that happens to be
3566 ;; a continuation line too
3567 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
3568 (progn (py-goto-initial-line) t)
3569 nil)
3570 t))
3571
3572 (defun py-goto-statement-below ()
3573 "Go to start of the first statement following the statement containing point.
3574 Return t if there is such a statement, otherwise nil. `Statement'
3575 does not include blank lines, comments, or continuation lines."
3576 (beginning-of-line)
3577 (let ((start (point)))
3578 (py-goto-beyond-final-line)
3579 (while (and
3580 (or (looking-at py-blank-or-comment-re)
3581 (py-in-literal))
3582 (not (eobp)))
3583 (forward-line 1))
3584 (if (eobp)
3585 (progn (goto-char start) nil)
3586 t)))
3587
3588 (defun py-go-up-tree-to-keyword (key)
3589 "Go to begining of statement starting with KEY, at or preceding point.
3590
3591 KEY is a regular expression describing a Python keyword. Skip blank
3592 lines and non-indenting comments. If the statement found starts with
3593 KEY, then stop, otherwise go back to first enclosing block starting
3594 with KEY. If successful, leave point at the start of the KEY line and
3595 return t. Otherwise, leave point at an undefined place and return nil."
3596 ;; skip blanks and non-indenting #
3597 (py-goto-initial-line)
3598 (while (and
3599 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3600 (zerop (forward-line -1))) ; go back
3601 nil)
3602 (py-goto-initial-line)
3603 (let* ((re (concat "[ \t]*" key "\\>"))
3604 (case-fold-search nil) ; let* so looking-at sees this
3605 (found (looking-at re))
3606 (dead nil))
3607 (while (not (or found dead))
3608 (condition-case nil ; in case no enclosing block
3609 (py-goto-block-up 'no-mark)
3610 (error (setq dead t)))
3611 (or dead (setq found (looking-at re))))
3612 (beginning-of-line)
3613 found))
3614
3615 (defun py-suck-up-leading-text ()
3616 "Return string in buffer from start of indentation to end of line.
3617 Prefix with \"...\" if leading whitespace was skipped."
3618 (save-excursion
3619 (back-to-indentation)
3620 (concat
3621 (if (bolp) "" "...")
3622 (buffer-substring (point) (progn (end-of-line) (point))))))
3623
3624 (defun py-suck-up-first-keyword ()
3625 "Return first keyword on the line as a Lisp symbol.
3626 `Keyword' is defined (essentially) as the regular expression
3627 ([a-z]+). Returns nil if none was found."
3628 (let ((case-fold-search nil))
3629 (if (looking-at "[ \t]*\\([a-z]+\\)\\>")
3630 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3631 nil)))
3632
3633 (defun py-current-defun ()
3634 "Python value for `add-log-current-defun-function'.
3635 This tells add-log.el how to find the current function/method/variable."
3636 (save-excursion
3637
3638 ;; Move back to start of the current statement.
3639
3640 (py-goto-initial-line)
3641 (back-to-indentation)
3642 (while (and (or (looking-at py-blank-or-comment-re)
3643 (py-in-literal))
3644 (not (bobp)))
3645 (backward-to-indentation 1))
3646 (py-goto-initial-line)
3647
3648 (let ((scopes "")
3649 (sep "")
3650 dead assignment)
3651
3652 ;; Check for an assignment. If this assignment exists inside a
3653 ;; def, it will be overwritten inside the while loop. If it
3654 ;; exists at top lever or inside a class, it will be preserved.
3655
3656 (when (looking-at "[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*=")
3657 (setq scopes (buffer-substring (match-beginning 1) (match-end 1)))
3658 (setq assignment t)
3659 (setq sep "."))
3660
3661 ;; Prepend the name of each outer socpe (def or class).
3662
3663 (while (not dead)
3664 (if (and (py-go-up-tree-to-keyword "\\(class\\|def\\)")
3665 (looking-at
3666 "[ \t]*\\(class\\|def\\)[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*"))
3667 (let ((name (buffer-substring (match-beginning 2) (match-end 2))))
3668 (if (and assignment (looking-at "[ \t]*def"))
3669 (setq scopes name)
3670 (setq scopes (concat name sep scopes))
3671 (setq sep "."))))
3672 (setq assignment nil)
3673 (condition-case nil ; Terminate nicely at top level.
3674 (py-goto-block-up 'no-mark)
3675 (error (setq dead t))))
3676 (if (string= scopes "")
3677 nil
3678 scopes))))
3679
3680
3681
3682 (defconst py-help-address "python-mode@python.org"
3683 "Address accepting submission of bug reports.")
3684
3685 (defun py-version ()
3686 "Echo the current version of `python-mode' in the minibuffer."
3687 (interactive)
3688 (message "Using `python-mode' version %s" py-version)
3689 (py-keep-region-active))
3690
3691 ;; only works under Emacs 19
3692 ;(eval-when-compile
3693 ; (require 'reporter))
3694
3695 (defun py-submit-bug-report (enhancement-p)
3696 "Submit via mail a bug report on `python-mode'.
3697 With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3698 non-nil) just submit an enhancement request."
3699 (interactive
3700 (list (not (y-or-n-p
3701 "Is this a bug report (hit `n' to send other comments)? "))))
3702 (let ((reporter-prompt-for-summary-p (if enhancement-p
3703 "(Very) brief summary: "
3704 t)))
3705 (require 'reporter)
3706 (reporter-submit-bug-report
3707 py-help-address ;address
3708 (concat "python-mode " py-version) ;pkgname
3709 ;; varlist
3710 (if enhancement-p nil
3711 '(py-python-command
3712 py-indent-offset
3713 py-block-comment-prefix
3714 py-temp-directory
3715 py-beep-if-tab-change))
3716 nil ;pre-hooks
3717 nil ;post-hooks
3718 "Dear Barry,") ;salutation
3719 (if enhancement-p nil
3720 (set-mark (point))
3721 (insert
3722 "Please replace this text with a sufficiently large code sample\n\
3723 and an exact recipe so that I can reproduce your problem. Failure\n\
3724 to do so may mean a greater delay in fixing your bug.\n\n")
3725 (exchange-point-and-mark)
3726 (py-keep-region-active))))
3727
3728
3729 (defun py-kill-emacs-hook ()
3730 "Delete files in `py-file-queue'.
3731 These are Python temporary files awaiting execution."
3732 (mapcar #'(lambda (filename)
3733 (py-safe (delete-file filename)))
3734 py-file-queue))
3735
3736 ;; arrange to kill temp files when Emacs exists
3737 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
3738 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
3739
3740 ;; Add a designator to the minor mode strings
3741 (or (assq 'py-pdbtrack-is-tracking-p minor-mode-alist)
3742 (push '(py-pdbtrack-is-tracking-p py-pdbtrack-minor-mode-string)
3743 minor-mode-alist))
3744
3745
3746
3747 ;;; paragraph and string filling code from Bernhard Herzog
3748 ;;; see http://mail.python.org/pipermail/python-list/2002-May/103189.html
3749
3750 (defun py-fill-comment (&optional justify)
3751 "Fill the comment paragraph around point"
3752 (let (;; Non-nil if the current line contains a comment.
3753 has-comment
3754
3755 ;; If has-comment, the appropriate fill-prefix for the comment.
3756 comment-fill-prefix)
3757
3758 ;; Figure out what kind of comment we are looking at.
3759 (save-excursion
3760 (beginning-of-line)
3761 (cond
3762 ;; A line with nothing but a comment on it?
3763 ((looking-at "[ \t]*#[# \t]*")
3764 (setq has-comment t
3765 comment-fill-prefix (buffer-substring (match-beginning 0)
3766 (match-end 0))))
3767
3768 ;; A line with some code, followed by a comment? Remember that the hash
3769 ;; which starts the comment shouldn't be part of a string or character.
3770 ((progn
3771 (while (not (looking-at "#\\|$"))
3772 (skip-chars-forward "^#\n\"'\\")
3773 (cond
3774 ((eq (char-after (point)) ?\\) (forward-char 2))
3775 ((memq (char-after (point)) '(?\" ?')) (forward-sexp 1))))
3776 (looking-at "#+[\t ]*"))
3777 (setq has-comment t)
3778 (setq comment-fill-prefix
3779 (concat (make-string (current-column) ? )
3780 (buffer-substring (match-beginning 0) (match-end 0)))))))
3781
3782 (if (not has-comment)
3783 (fill-paragraph justify)
3784
3785 ;; Narrow to include only the comment, and then fill the region.
3786 (save-restriction
3787 (narrow-to-region
3788
3789 ;; Find the first line we should include in the region to fill.
3790 (save-excursion
3791 (while (and (zerop (forward-line -1))
3792 (looking-at "^[ \t]*#")))
3793
3794 ;; We may have gone to far. Go forward again.
3795 (or (looking-at "^[ \t]*#")
3796 (forward-line 1))
3797 (point))
3798
3799 ;; Find the beginning of the first line past the region to fill.
3800 (save-excursion
3801 (while (progn (forward-line 1)
3802 (looking-at "^[ \t]*#")))
3803 (point)))
3804
3805 ;; Lines with only hashes on them can be paragraph boundaries.
3806 (let ((paragraph-start (concat paragraph-start "\\|[ \t#]*$"))
3807 (paragraph-separate (concat paragraph-separate "\\|[ \t#]*$"))
3808 (fill-prefix comment-fill-prefix))
3809 ;;(message "paragraph-start %S paragraph-separate %S"
3810 ;;paragraph-start paragraph-separate)
3811 (fill-paragraph justify))))
3812 t))
3813
3814
3815 (defun py-fill-string (start &optional justify)
3816 "Fill the paragraph around (point) in the string starting at start"
3817 ;; basic strategy: narrow to the string and call the default
3818 ;; implementation
3819 (let (;; the start of the string's contents
3820 string-start
3821 ;; the end of the string's contents
3822 string-end
3823 ;; length of the string's delimiter
3824 delim-length
3825 ;; The string delimiter
3826 delim
3827 )
3828
3829 (save-excursion
3830 (goto-char start)
3831 (if (looking-at "\\('''\\|\"\"\"\\|'\\|\"\\)\\\\?\n?")
3832 (setq string-start (match-end 0)
3833 delim-length (- (match-end 1) (match-beginning 1))
3834 delim (buffer-substring-no-properties (match-beginning 1)
3835 (match-end 1)))
3836 (error "The parameter start is not the beginning of a python string"))
3837
3838 ;; if the string is the first token on a line and doesn't start with
3839 ;; a newline, fill as if the string starts at the beginning of the
3840 ;; line. this helps with one line docstrings
3841 (save-excursion
3842 (beginning-of-line)
3843 (and (/= (char-before string-start) ?\n)
3844 (looking-at (concat "[ \t]*" delim))
3845 (setq string-start (point))))
3846
3847 (forward-sexp (if (= delim-length 3) 2 1))
3848
3849 ;; with both triple quoted strings and single/double quoted strings
3850 ;; we're now directly behind the first char of the end delimiter
3851 ;; (this doesn't work correctly when the triple quoted string
3852 ;; contains the quote mark itself). The end of the string's contents
3853 ;; is one less than point
3854 (setq string-end (1- (point))))
3855
3856 ;; Narrow to the string's contents and fill the current paragraph
3857 (save-restriction
3858 (narrow-to-region string-start string-end)
3859 (let ((ends-with-newline (= (char-before (point-max)) ?\n)))
3860 (fill-paragraph justify)
3861 (if (and (not ends-with-newline)
3862 (= (char-before (point-max)) ?\n))
3863 ;; the default fill-paragraph implementation has inserted a
3864 ;; newline at the end. Remove it again.
3865 (save-excursion
3866 (goto-char (point-max))
3867 (delete-char -1)))))
3868
3869 ;; return t to indicate that we've done our work
3870 t))
3871
3872 (defun py-fill-paragraph (&optional justify)
3873 "Like \\[fill-paragraph], but handle Python comments and strings.
3874 If any of the current line is a comment, fill the comment or the
3875 paragraph of it that point is in, preserving the comment's indentation
3876 and initial `#'s.
3877 If point is inside a string, narrow to that string and fill.
3878 "
3879 (interactive "P")
3880 (let* ((bod (py-point 'bod))
3881 (pps (parse-partial-sexp bod (point))))
3882 (cond
3883 ;; are we inside a comment or on a line with only whitespace before
3884 ;; the comment start?
3885 ((or (nth 4 pps)
3886 (save-excursion (beginning-of-line) (looking-at "[ \t]*#")))
3887 (py-fill-comment justify))
3888 ;; are we inside a string?
3889 ((nth 3 pps)
3890 (py-fill-string (nth 8 pps)))
3891 ;; are we at the opening quote of a string, or in the indentation?
3892 ((save-excursion
3893 (forward-word 1)
3894 (eq (py-in-literal) 'string))
3895 (save-excursion
3896 (py-fill-string (py-point 'boi))))
3897 ;; are we at or after the closing quote of a string?
3898 ((save-excursion
3899 (backward-word 1)
3900 (eq (py-in-literal) 'string))
3901 (save-excursion
3902 (py-fill-string (py-point 'boi))))
3903 ;; otherwise use the default
3904 (t
3905 (fill-paragraph justify)))))
3906
3907
3908
3909 (provide 'python-mode)
3910 ;;; python-mode.el ends here