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