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