1 ;;; python-mode.el --- Major mode for editing Python programs
3 ;; Copyright (C) 1992,1993,1994 Tim Peters
5 ;; Author: 2003-2009 https://launchpad.net/python-mode
6 ;; 1995-2002 Barry A. Warsaw
7 ;; 1992-1994 Tim Peters
8 ;; Maintainer: python-mode@python.org
10 ;; Keywords: python languages oop
12 (defconst py-version "5.0.0+"
13 "`python-mode' version number.")
15 ;; This software is provided as-is, without express or implied warranty.
16 ;; Permission to use, copy, modify, distribute or sell this software, without
17 ;; fee, for any purpose and by any individual or organization, is hereby
18 ;; granted, provided that the above copyright notice and this paragraph appear
23 ;; This is a major mode for editing Python programs. It was developed by Tim
24 ;; Peters after an original idea by Michael A. Guravage. Tim subsequently
25 ;; left the net and in 1995, Barry Warsaw inherited the mode. Tim came back
26 ;; but disavowed all responsibility for the mode. In fact, we suspect he
27 ;; doesn't even use Emacs any more <wink>. In 2003, python-mode.el was moved
28 ;; to its own SourceForge project apart from the Python project, and in 2008
29 ;; it was moved to Launchpad for all project administration. python-mode.el
30 ;; is maintained by the volunteers at the python-mode@python.org mailing
33 ;; python-mode.el is different than, and pre-dates by many years, the
34 ;; python.el that comes with FSF Emacs. We'd like to merge the two modes but
35 ;; have few cycles to do so. Volunteers are welcome.
37 ;; pdbtrack support contributed by Ken Manheimer, April 2001. Skip Montanaro
38 ;; has also contributed significantly to python-mode's development.
40 ;; Please use Launchpad to submit bugs or patches:
42 ;; https://launchpad.net/python-mode
46 ;; To install, just drop this file into a directory on your load-path and
47 ;; byte-compile it. To set up Emacs to automatically edit files ending in
48 ;; ".py" using python-mode add the following to your ~/.emacs file (GNU
49 ;; Emacs) or ~/.xemacs/init.el file (XEmacs):
50 ;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
51 ;; (setq interpreter-mode-alist (cons '("python" . python-mode)
52 ;; interpreter-mode-alist))
53 ;; (autoload 'python-mode "python-mode" "Python editing mode." t)
55 ;; In XEmacs syntax highlighting should be enabled automatically. In GNU
56 ;; Emacs you may have to add these lines to your ~/.emacs file:
57 ;; (global-font-lock-mode t)
58 ;; (setq font-lock-maximum-decoration t)
62 ;; As mentioned above, please use the Launchpad python-mode project for
63 ;; submitting bug reports or patches. The old recommendation, to use C-c C-b
64 ;; will still work, but those reports have a higher chance of getting buried
65 ;; in our inboxes. Please include a complete, but concise code sample and a
66 ;; recipe for reproducing the bug. Send suggestions and other comments to
67 ;; python-mode@python.org.
69 ;; When in a Python mode buffer, do a C-h m for more help. It's doubtful that
70 ;; a texinfo manual would be very useful, but if you want to contribute one,
71 ;; we'll certainly accept it!
82 ;; user definable variables
83 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
86 "Support for the Python programming language, <http://www.python.org/>"
90 (defcustom py-tab-always-indent t
91 "*Non-nil means TAB in Python mode should always reindent the current line,
92 regardless of where in the line point is when the TAB command is used."
96 (defcustom py-python-command "python"
97 "*Shell command used to start Python interpreter."
101 (make-obsolete-variable 'py-jpython-command 'py-jython-command)
102 (defcustom py-jython-command "jython"
103 "*Shell command used to start the Jython interpreter."
106 :tag "Jython Command")
108 (defcustom py-default-interpreter 'cpython
109 "*Which Python interpreter is used by default.
110 The value for this variable can be either `cpython' or `jython'.
112 When the value is `cpython', the variables `py-python-command' and
113 `py-python-command-args' are consulted to determine the interpreter
114 and arguments to use.
116 When the value is `jython', the variables `py-jython-command' and
117 `py-jython-command-args' are consulted to determine the interpreter
118 and arguments to use.
120 Note that this variable is consulted only the first time that a Python
121 mode buffer is visited during an Emacs session. After that, use
122 \\[py-toggle-shells] to change the interpreter shell."
123 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
124 (const :tag "Jython" jython))
127 (defcustom py-python-command-args '("-i")
128 "*List of string arguments to be used when starting a Python shell."
129 :type '(repeat string)
132 (make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args)
133 (defcustom py-jython-command-args '("-i")
134 "*List of string arguments to be used when starting a Jython shell."
135 :type '(repeat string)
137 :tag "Jython Command Args")
139 (defcustom py-indent-offset 4
140 "*Amount of offset per level of indentation.
141 `\\[py-guess-indent-offset]' can usually guess a good value when
142 you're editing someone else's Python code."
146 (defcustom py-continuation-offset 4
147 "*Additional amount of offset to give for some continuation lines.
148 Continuation lines are those that immediately follow a backslash
149 terminated line. Only those continuation lines for a block opening
150 statement are given this extra offset."
154 (defcustom py-smart-indentation t
155 "*Should `python-mode' try to automagically set some indentation variables?
156 When this variable is non-nil, two things happen when a buffer is set
159 1. `py-indent-offset' is guessed from existing code in the buffer.
160 Only guessed values between 2 and 8 are considered. If a valid
161 guess can't be made (perhaps because you are visiting a new
162 file), then the value in `py-indent-offset' is used.
164 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
165 equal `tab-width' (`indent-tabs-mode' is never turned on by
166 Python mode). This means that for newly written code, tabs are
167 only inserted in indentation if one tab is one indentation
168 level, otherwise only spaces are used.
170 Note that both these settings occur *after* `python-mode-hook' is run,
171 so if you want to defeat the automagic configuration, you must also
172 set `py-smart-indentation' to nil in your `python-mode-hook'."
176 (defcustom py-align-multiline-strings-p t
177 "*Flag describing how multi-line triple quoted strings are aligned.
178 When this flag is non-nil, continuation lines are lined up under the
179 preceding line's indentation. When this flag is nil, continuation
180 lines are aligned to column zero."
181 :type '(choice (const :tag "Align under preceding line" t)
182 (const :tag "Align to column zero" nil))
185 (defcustom py-block-comment-prefix "##"
186 "*String used by \\[comment-region] to comment out a block of code.
187 This should follow the convention for non-indenting comment lines so
188 that the indentation commands won't get confused (i.e., the string
189 should be of the form `#x...' where `x' is not a blank or a tab, and
190 `...' is arbitrary). However, this string should not end in whitespace."
194 (defcustom py-honor-comment-indentation t
195 "*Controls how comment lines influence subsequent indentation.
197 When nil, all comment lines are skipped for indentation purposes, and
198 if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
200 When t, lines that begin with a single `#' are a hint to subsequent
201 line indentation. If the previous line is such a comment line (as
202 opposed to one that starts with `py-block-comment-prefix'), then its
203 indentation is used as a hint for this line's indentation. Lines that
204 begin with `py-block-comment-prefix' are ignored for indentation
207 When not nil or t, comment lines that begin with a single `#' are used
208 as indentation hints, unless the comment character is in column zero."
210 (const :tag "Skip all comment lines (fast)" nil)
211 (const :tag "Single # `sets' indentation for next line" t)
212 (const :tag "Single # `sets' indentation except at column zero"
217 (defcustom py-temp-directory
218 (let ((ok '(lambda (x)
220 (setq x (expand-file-name x)) ; always true
224 (or (funcall ok (getenv "TMPDIR"))
225 (funcall ok "/usr/tmp")
227 (funcall ok "/var/tmp")
230 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
231 "*Directory used for temporary files created by a *Python* process.
232 By default, the first directory from this list that exists and that you
233 can write into: the value (if any) of the environment variable TMPDIR,
234 /usr/tmp, /tmp, /var/tmp, or the current directory."
238 (defcustom py-beep-if-tab-change t
239 "*Ring the bell if `tab-width' is changed.
240 If a comment of the form
242 \t# vi:set tabsize=<number>:
244 is found before the first code line when the file is entered, and the
245 current value of (the general Emacs variable) `tab-width' does not
246 equal <number>, `tab-width' is set to <number>, a message saying so is
247 displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
248 the Emacs bell is also rung as a warning."
252 (defcustom py-jump-on-exception t
253 "*Jump to innermost exception frame in *Python Output* buffer.
254 When this variable is non-nil and an exception occurs when running
255 Python code synchronously in a subprocess, jump immediately to the
256 source code of the innermost traceback frame."
260 (defcustom py-ask-about-save t
261 "If not nil, ask about which buffers to save before executing some code.
262 Otherwise, all modified buffers are saved without asking."
266 (defcustom py-backspace-function 'backward-delete-char-untabify
267 "*Function called by `py-electric-backspace' when deleting backwards."
271 (defcustom py-delete-function 'delete-char
272 "*Function called by `py-electric-delete' when deleting forwards."
276 (defcustom py-imenu-show-method-args-p nil
277 "*Controls echoing of arguments of functions & methods in the Imenu buffer.
278 When non-nil, arguments are printed."
281 (make-variable-buffer-local 'py-indent-offset)
283 (defcustom py-pdbtrack-do-tracking-p t
284 "*Controls whether the pdbtrack feature is enabled or not.
285 When non-nil, pdbtrack is enabled in all comint-based buffers,
286 e.g. shell buffers and the *Python* buffer. When using pdb to debug a
287 Python program, pdbtrack notices the pdb prompt and displays the
288 source file and line that the program is stopped at, much the same way
289 as gud-mode does for debugging C programs with gdb."
292 (make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
294 (defcustom py-pdbtrack-minor-mode-string " PDB"
295 "*String to use in the minor mode list when pdbtrack is enabled."
299 (defcustom py-import-check-point-max
301 "Maximum number of characters to search for a Java-ish import statement.
302 When `python-mode' tries to calculate the shell to use (either a
303 CPython or a Jython shell), it looks at the so-called `shebang' line
304 -- i.e. #! line. If that's not available, it looks at some of the
305 file heading imports to see if they look Java-like."
310 (make-obsolete-variable 'py-jpython-packages 'py-jython-packages)
311 (defcustom py-jython-packages
312 '("java" "javax" "org" "com")
313 "Imported packages that imply `jython-mode'."
314 :type '(repeat string)
318 (defvar py-master-file nil
319 "If non-nil, execute the named file instead of the buffer's file.
320 The intent is to allow you to set this variable in the file's local
321 variable section, e.g.:
324 # py-master-file: \"master.py\"
327 so that typing \\[py-execute-buffer] in that buffer executes the named
328 master file instead of the buffer's file. If the file name has a
329 relative path, the value of variable `default-directory' for the
330 buffer is prepended to come up with a file name.")
331 (make-variable-buffer-local 'py-master-file)
333 (defcustom py-pychecker-command "pychecker"
334 "*Shell command used to run Pychecker."
337 :tag "Pychecker Command")
339 (defcustom py-pychecker-command-args '("--stdlib")
340 "*List of string arguments to be passed to pychecker."
341 :type '(repeat string)
343 :tag "Pychecker Command Args")
345 (defvar py-shell-alist
346 '(("jython" . 'jython)
347 ("python" . 'cpython))
348 "*Alist of interpreters and python shells. Used by `py-choose-shell'
349 to select the appropriate python interpreter mode for a file.")
351 (defcustom py-shell-input-prompt-1-regexp "^>>> "
352 "*A regular expression to match the input prompt of the shell."
356 (defcustom py-shell-input-prompt-2-regexp "^[.][.][.] "
357 "*A regular expression to match the input prompt of the shell after the
358 first line of input."
362 (defcustom py-shell-switch-buffers-on-execute t
363 "*Controls switching to the Python buffer where commands are
364 executed. When non-nil the buffer switches to the Python buffer, if
365 not no switching occurs."
369 (defcustom py-hide-show-keywords '("class" "def" "elif" "else" "except"
370 "for" "if" "while" "finally" "try" "with")
371 "*Keywords used by hide-show"
372 :type '(repeat string)
375 (defcustom py-hide-show-hide-docstrings t
376 "*If doc strings shall be hidden"
382 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
383 ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
385 (defvar py-line-number-offset 0
386 "When an exception occurs as a result of py-execute-region, a
387 subsequent py-up-exception needs the line number where the region
388 started, in order to jump to the correct file line. This variable is
389 set in py-execute-region and used in py-jump-to-exception.")
391 (defconst py-emacs-features
394 "A list of features extant in the Emacs you are using.
395 There are many flavors of Emacs out there, with different levels of
396 support for features needed by `python-mode'.")
398 ;; Face for None, True, False, self, and Ellipsis
399 (defvar py-pseudo-keyword-face 'py-pseudo-keyword-face
400 "Face for pseudo keywords in Python mode, like self, True, False, Ellipsis.")
401 (make-face 'py-pseudo-keyword-face)
403 ;; PEP 318 decorators
404 (defvar py-decorators-face 'py-decorators-face
405 "Face method decorators.")
406 (make-face 'py-decorators-face)
409 (defvar py-builtins-face 'py-builtins-face
410 "Face for builtins like TypeError, object, open, and exec.")
411 (make-face 'py-builtins-face)
413 ;; XXX, TODO, and FIXME comments and such
414 (defvar py-XXX-tag-face 'py-XXX-tag-face
415 "Face for XXX, TODO, and FIXME tags")
416 (make-face 'py-XXX-tag-face)
418 (defun py-font-lock-mode-hook ()
419 (or (face-differs-from-default-p 'py-pseudo-keyword-face)
420 (copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face))
421 (or (face-differs-from-default-p 'py-builtins-face)
422 (copy-face 'font-lock-keyword-face 'py-builtins-face))
423 (or (face-differs-from-default-p 'py-decorators-face)
424 (copy-face 'py-pseudo-keyword-face 'py-decorators-face))
425 (or (face-differs-from-default-p 'py-XXX-tag-face)
426 (copy-face 'font-lock-comment-face 'py-XXX-tag-face))
428 (add-hook 'font-lock-mode-hook 'py-font-lock-mode-hook)
430 (defvar python-font-lock-keywords
431 (let ((kw1 (mapconcat 'identity
432 '("and" "assert" "break" "class"
433 "continue" "def" "del" "elif"
434 "else" "except" "for" "None"
435 "from" "global" "if" "import"
436 "in" "is" "lambda" "not"
437 "or" "pass" "raise" "as"
438 "return" "while" "with" "yield"
441 (kw2 (mapconcat 'identity
442 '("else:" "except:" "finally:" "try:")
444 (kw3 (mapconcat 'identity
445 ;; Don't include Ellipsis in this list, since it is
446 ;; already defined as a pseudo keyword.
448 "__import__" "__name__" "abs" "all" "any" "apply"
449 "basestring" "bin" "bool" "buffer" "bytearray"
450 "callable" "chr" "classmethod" "cmp" "coerce"
451 "compile" "complex" "copyright" "credits"
452 "delattr" "dict" "dir" "divmod" "enumerate" "eval"
453 "exec" "execfile" "exit" "file" "filter" "float"
454 "format" "getattr" "globals" "hasattr" "hash" "help"
455 "hex" "id" "input" "int" "intern" "isinstance"
456 "issubclass" "iter" "len" "license" "list" "locals"
457 "long" "map" "max" "memoryview" "min" "next"
458 "object" "oct" "open" "ord" "pow" "print" "property"
459 "quit" "range" "raw_input" "reduce" "reload" "repr"
460 "round" "set" "setattr" "slice" "sorted"
461 "staticmethod" "str" "sum" "super" "tuple" "type"
462 "unichr" "unicode" "vars" "xrange" "zip")
464 (kw4 (mapconcat 'identity
465 ;; Exceptions and warnings
466 '("ArithmeticError" "AssertionError"
467 "AttributeError" "BaseException" "BufferError"
468 "BytesWarning" "DeprecationWarning" "EOFError"
469 "EnvironmentError" "Exception"
470 "FloatingPointError" "FutureWarning" "GeneratorExit"
471 "IOError" "ImportError" "ImportWarning"
472 "IndentationError" "IndexError"
473 "KeyError" "KeyboardInterrupt" "LookupError"
474 "MemoryError" "NameError" "NotImplemented"
475 "NotImplementedError" "OSError" "OverflowError"
476 "PendingDeprecationWarning" "ReferenceError"
477 "RuntimeError" "RuntimeWarning" "StandardError"
478 "StopIteration" "SyntaxError" "SyntaxWarning"
479 "SystemError" "SystemExit" "TabError" "TypeError"
480 "UnboundLocalError" "UnicodeDecodeError"
481 "UnicodeEncodeError" "UnicodeError"
482 "UnicodeTranslateError" "UnicodeWarning"
483 "UserWarning" "ValueError" "Warning"
488 '("^[ \t]*\\(@.+\\)" 1 'py-decorators-face)
490 (cons (concat "\\<\\(" kw1 "\\)\\>[ \n\t(]") 1)
491 ;; builtins when they don't appear as object attributes
492 (list (concat "\\([^. \t]\\|^\\)[ \t]*\\<\\(" kw3 "\\)\\>[ \n\t(]") 2
494 ;; block introducing keywords with immediately following colons.
495 ;; Yes "except" is in both lists.
496 (cons (concat "\\<\\(" kw2 "\\)[ \n\t(]") 1)
498 (list (concat "\\<\\(" kw4 "\\)[ \n\t:,(]") 1 'py-builtins-face)
500 '("\\<class[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" 1 font-lock-type-face)
502 '("\\<def[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
503 1 font-lock-function-name-face)
505 '("\\<\\(self\\|Ellipsis\\|True\\|False\\)\\>"
506 1 py-pseudo-keyword-face)
507 ;; XXX, TODO, and FIXME tags
508 '("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t)
510 "Additional expressions to highlight in Python mode.")
511 (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
513 ;; have to bind py-file-queue before installing the kill-emacs-hook
514 (defvar py-file-queue nil
515 "Queue of Python temp files awaiting execution.
516 Currently-active file is at the head of the list.")
518 (defvar py-pdbtrack-is-tracking-p nil)
520 (defvar py-pychecker-history nil)
526 (defconst py-stringlit-re
528 ;; These fail if backslash-quote ends the string (not worth
529 ;; fixing?). They precede the short versions so that the first two
530 ;; quotes don't look like an empty short string.
532 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
533 ;; with potential embedded single quotes
534 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
536 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
537 ;; with potential embedded double quotes
538 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
540 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
542 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
544 "Regular expression matching a Python string literal.")
546 (defconst py-continued-re
547 ;; This is tricky because a trailing backslash does not mean
548 ;; continuation if it's in a comment
550 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
552 "Regular expression matching Python backslash continuation lines.")
554 (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
555 "Regular expression matching a blank or comment line.")
557 (defconst py-outdent-re
558 (concat "\\(" (mapconcat 'identity
560 "except\\(\\s +.*\\)?:"
565 "Regular expression matching statements to be dedented one level.")
567 (defconst py-block-closing-keywords-re
568 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
569 "Regular expression matching keywords which typically close a block.")
571 (defconst py-no-outdent-re
576 "except\\(\\s +.*\\)?:"
581 (concat py-block-closing-keywords-re "[ \t\n]")
585 "Regular expression matching lines not to dedent after.")
587 (defvar py-traceback-line-re
588 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
589 "Regular expression that describes tracebacks.")
591 ;; pdbtrack constants
592 (defconst py-pdbtrack-stack-entry-regexp
593 ; "^> \\([^(]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
594 "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
595 "Regular expression pdbtrack uses to find a stack trace entry.")
597 (defconst py-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
598 "Regular expression pdbtrack uses to recognize a pdb prompt.")
600 (defconst py-pdbtrack-track-range 10000
601 "Max number of characters from end of buffer to search for stack entry.")
605 ;; Major mode boilerplate
607 ;; define a mode-specific abbrev table for those who use such things
608 (defvar python-mode-abbrev-table nil
609 "Abbrev table in use in `python-mode' buffers.")
610 (define-abbrev-table 'python-mode-abbrev-table nil)
612 (defvar python-mode-hook nil
613 "*Hook called by `python-mode'.")
615 (make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook)
616 (defvar jython-mode-hook nil
617 "*Hook called by `jython-mode'. `jython-mode' also calls
618 `python-mode-hook'.")
620 (defvar py-shell-hook nil
621 "*Hook called by `py-shell'.")
623 ;; In previous version of python-mode.el, the hook was incorrectly
624 ;; called py-mode-hook, and was not defvar'd. Deprecate its use.
625 (and (fboundp 'make-obsolete-variable)
626 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
628 (defvar py-mode-map ()
629 "Keymap used in `python-mode' buffers.")
632 (setq py-mode-map (make-sparse-keymap))
634 (define-key py-mode-map ":" 'py-electric-colon)
635 ;; indentation level modifiers
636 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
637 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
638 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
639 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
640 ;; subprocess commands
641 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
642 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
643 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
644 (define-key py-mode-map "\C-c|" 'py-execute-region)
645 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
646 (define-key py-mode-map "\C-c!" 'py-shell)
647 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
648 ;; Caution! Enter here at your own risk. We are trying to support
649 ;; several behaviors and it gets disgusting. :-( This logic ripped
650 ;; largely from CC Mode.
652 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
653 ;; backwards deletion behavior to DEL, which both Delete and
654 ;; Backspace get translated to. There's no way to separate this
655 ;; behavior in a clean way, so deal with it! Besides, it's been
656 ;; this way since the dawn of time.
657 (if (not (boundp 'delete-key-deletes-forward))
658 (define-key py-mode-map "\177" 'py-electric-backspace)
659 ;; However, XEmacs 20 actually achieved enlightenment. It is
660 ;; possible to sanely define both backward and forward deletion
661 ;; behavior under X separately (TTYs are forever beyond hope, but
662 ;; who cares? XEmacs 20 does the right thing with these too).
663 (define-key py-mode-map [delete] 'py-electric-delete)
664 (define-key py-mode-map [backspace] 'py-electric-backspace))
665 ;; Separate M-BS from C-M-h. The former should remain
666 ;; backward-kill-word.
667 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
668 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
670 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
671 (define-key py-mode-map "\C-c\t" 'py-indent-region)
672 (define-key py-mode-map "\C-c\C-d" 'py-pdbtrack-toggle-stack-tracking)
673 (define-key py-mode-map "\C-c\C-f" 'py-sort-imports)
674 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
675 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
676 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
677 (define-key py-mode-map "\C-c#" 'py-comment-region)
678 (define-key py-mode-map "\C-c?" 'py-describe-mode)
679 (define-key py-mode-map "\C-c\C-h" 'py-help-at-point)
680 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
681 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
682 (define-key py-mode-map "\C-c-" 'py-up-exception)
683 (define-key py-mode-map "\C-c=" 'py-down-exception)
684 ;; stuff that is `standard' but doesn't interface well with
685 ;; python-mode, which forces us to rebind to special commands
686 (define-key py-mode-map "\C-xnd" 'py-narrow-to-defun)
688 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
689 (define-key py-mode-map "\C-c\C-v" 'py-version)
690 (define-key py-mode-map "\C-c\C-w" 'py-pychecker-run)
691 ;; shadow global bindings for newline-and-indent w/ the py- version.
692 ;; BAW - this is extremely bad form, but I'm not going to change it
694 (mapc #'(lambda (key)
695 (define-key py-mode-map key 'py-newline-and-indent))
696 (where-is-internal 'newline-and-indent))
697 ;; Force RET to be py-newline-and-indent even if it didn't get
698 ;; mapped by the above code. motivation: Emacs' default binding for
699 ;; RET is `newline' and C-j is `newline-and-indent'. Most Pythoneers
700 ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
701 ;; dislike this are probably knowledgeable enough to do a rebind.
702 ;; However, we do *not* change C-j since many Emacsers have already
703 ;; swapped RET and C-j and they don't want C-j bound to `newline' to
705 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
708 (defvar py-mode-output-map nil
709 "Keymap used in *Python Output* buffers.")
710 (if py-mode-output-map
712 (setq py-mode-output-map (make-sparse-keymap))
713 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
714 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
715 ;; TBD: Disable all self-inserting keys. This is bogus, we should
716 ;; really implement this as *Python Output* buffer being read-only
717 (mapc #' (lambda (key)
718 (define-key py-mode-output-map key
719 #'(lambda () (interactive) (beep))))
720 (where-is-internal 'self-insert-command))
723 (defvar py-shell-map nil
724 "Keymap used in *Python* shell buffers.")
727 (setq py-shell-map (copy-keymap comint-mode-map))
728 (define-key py-shell-map [tab] 'tab-to-tab-stop)
729 (define-key py-shell-map "\C-c-" 'py-up-exception)
730 (define-key py-shell-map "\C-c=" 'py-down-exception)
733 (defvar py-mode-syntax-table nil
734 "Syntax table used in `python-mode' buffers.")
735 (when (not py-mode-syntax-table)
736 (setq py-mode-syntax-table (make-syntax-table))
737 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
738 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
739 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
740 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
741 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
742 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
743 ;; Add operator symbols misassigned in the std table
744 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
745 (modify-syntax-entry ?\% "." py-mode-syntax-table)
746 (modify-syntax-entry ?\& "." py-mode-syntax-table)
747 (modify-syntax-entry ?\* "." py-mode-syntax-table)
748 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
749 (modify-syntax-entry ?\- "." py-mode-syntax-table)
750 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
751 (modify-syntax-entry ?\< "." py-mode-syntax-table)
752 (modify-syntax-entry ?\= "." py-mode-syntax-table)
753 (modify-syntax-entry ?\> "." py-mode-syntax-table)
754 (modify-syntax-entry ?\| "." py-mode-syntax-table)
755 ;; For historical reasons, underscore is word class instead of
756 ;; symbol class. GNU conventions say it should be symbol class, but
757 ;; there's a natural conflict between what major mode authors want
758 ;; and what users expect from `forward-word' and `backward-word'.
759 ;; Guido and I have hashed this out and have decided to keep
760 ;; underscore in word class. If you're tempted to change it, try
761 ;; binding M-f and M-b to py-forward-into-nomenclature and
762 ;; py-backward-into-nomenclature instead. This doesn't help in all
763 ;; situations where you'd want the different behavior
764 ;; (e.g. backward-kill-word).
765 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
766 ;; Both single quote and double quote are string delimiters
767 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
768 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
769 ;; backquote is open and close paren
770 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
771 ;; comment delimiters
772 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
773 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
776 ;; An auxiliary syntax table which places underscore and dot in the
777 ;; symbol class for simplicity
778 (defvar py-dotted-expression-syntax-table nil
779 "Syntax table used to identify Python dotted expressions.")
780 (when (not py-dotted-expression-syntax-table)
781 (setq py-dotted-expression-syntax-table
782 (copy-syntax-table py-mode-syntax-table))
783 (modify-syntax-entry ?_ "_" py-dotted-expression-syntax-table)
784 (modify-syntax-entry ?. "_" py-dotted-expression-syntax-table))
789 (defmacro py-safe (&rest body)
790 "Safely execute BODY, return nil if an error occurred."
795 (defsubst py-keep-region-active ()
796 "Keep the region active in XEmacs."
797 ;; Ignore byte-compiler warnings you might see. Also note that
798 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
799 ;; to take explicit action.
800 (and (boundp 'zmacs-region-stays)
801 (setq zmacs-region-stays t)))
803 (defsubst py-point (position)
804 "Returns the value of point at certain commonly referenced POSITIONs.
805 POSITION can be one of the following symbols:
807 bol -- beginning of line
809 bod -- beginning of def or class
810 eod -- end of def or class
811 bob -- beginning of buffer
813 boi -- back to indentation
814 bos -- beginning of statement
816 This function does not modify point or mark."
817 (let ((here (point)))
819 ((eq position 'bol) (beginning-of-line))
820 ((eq position 'eol) (end-of-line))
821 ((eq position 'bod) (py-beginning-of-def-or-class 'either))
822 ((eq position 'eod) (py-end-of-def-or-class 'either))
823 ;; Kind of funny, I know, but useful for py-up-exception.
824 ((eq position 'bob) (goto-char (point-min)))
825 ((eq position 'eob) (goto-char (point-max)))
826 ((eq position 'boi) (back-to-indentation))
827 ((eq position 'bos) (py-goto-initial-line))
828 (t (error "Unknown buffer position requested: %s" position))
834 (defsubst py-highlight-line (from to file line)
836 ((fboundp 'make-extent)
838 (let ((e (make-extent from to)))
839 (set-extent-property e 'mouse-face 'highlight)
840 (set-extent-property e 'py-exc-info (cons file line))
841 (set-extent-property e 'keymap py-mode-output-map)))
843 ;; Emacs -- Please port this!
847 (defun py-in-literal (&optional lim)
848 "Return non-nil if point is in a Python literal (a comment or string).
849 Optional argument LIM indicates the beginning of the containing form,
850 i.e. the limit on how far back to scan."
851 ;; This is the version used for non-XEmacs, which has a nicer
854 ;; WARNING: Watch out for infinite recursion.
855 (let* ((lim (or lim (py-point 'bod)))
856 (state (parse-partial-sexp lim (point))))
858 ((nth 3 state) 'string)
859 ((nth 4 state) 'comment)
862 ;; XEmacs has a built-in function that should make this much quicker.
863 ;; In this case, lim is ignored
864 (defun py-fast-in-literal (&optional lim)
865 "Fast version of `py-in-literal', used only by XEmacs.
866 Optional LIM is ignored."
867 ;; don't have to worry about context == 'block-comment
868 (buffer-syntactic-context))
870 (if (fboundp 'buffer-syntactic-context)
871 (defalias 'py-in-literal 'py-fast-in-literal))
875 ;; Menu definitions, only relevent if you have the easymenu.el package
876 ;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
878 "Menu for Python Mode.
879 This menu will get created automatically if you have the `easymenu'
880 package. Note that the latest X/Emacs releases contain this package.")
882 (and (py-safe (require 'easymenu) t)
884 py-menu py-mode-map "Python Mode menu"
886 ["Comment Out Region" py-comment-region (mark)]
887 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
889 ["Mark current block" py-mark-block t]
890 ["Mark current def" py-mark-def-or-class t]
891 ["Mark current class" (py-mark-def-or-class t) t]
893 ["Shift region left" py-shift-region-left (mark)]
894 ["Shift region right" py-shift-region-right (mark)]
896 ["Import/reload file" py-execute-import-or-reload t]
897 ["Execute buffer" py-execute-buffer t]
898 ["Execute region" py-execute-region (mark)]
899 ["Execute def or class" py-execute-def-or-class (mark)]
900 ["Execute string" py-execute-string t]
901 ["Start interpreter..." py-shell t]
903 ["Go to start of block" py-goto-block-up t]
904 ["Go to start of class" (py-beginning-of-def-or-class t) t]
905 ["Move to end of class" (py-end-of-def-or-class t) t]
906 ["Move to start of def" py-beginning-of-def-or-class t]
907 ["Move to end of def" py-end-of-def-or-class t]
909 ["Describe mode" py-describe-mode t]
915 (defvar py-imenu-class-regexp
916 (concat ; <<classes>>
918 "^[ \t]*" ; newline and maybe whitespace
919 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
920 ; possibly multiple superclasses
921 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
922 "[ \t]*:" ; and the final :
925 "Regexp for Python classes for use with the Imenu package."
928 (defvar py-imenu-method-regexp
929 (concat ; <<methods and functions>>
931 "^[ \t]*" ; new line and maybe whitespace
932 "\\(def[ \t]+" ; function definitions start with def
933 "\\([a-zA-Z0-9_]+\\)" ; name is here
934 ; function arguments...
935 ;; "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
936 "[ \t]*(\\([^:#]*\\))"
938 "[ \t]*:" ; and then the :
939 "\\)" ; >>methods and functions<<
941 "Regexp for Python methods/functions for use with the Imenu package."
944 (defvar py-imenu-method-no-arg-parens '(2 8)
945 "Indices into groups of the Python regexp for use with Imenu.
947 Using these values will result in smaller Imenu lists, as arguments to
948 functions are not listed.
950 See the variable `py-imenu-show-method-args-p' for more
953 (defvar py-imenu-method-arg-parens '(2 7)
954 "Indices into groups of the Python regexp for use with imenu.
955 Using these values will result in large Imenu lists, as arguments to
956 functions are listed.
958 See the variable `py-imenu-show-method-args-p' for more
961 ;; Note that in this format, this variable can still be used with the
962 ;; imenu--generic-function. Otherwise, there is no real reason to have
964 (defvar py-imenu-generic-expression
967 py-imenu-class-regexp
969 py-imenu-method-regexp
971 py-imenu-method-no-arg-parens)
972 "Generic Python expression which may be used directly with Imenu.
973 Used by setting the variable `imenu-generic-expression' to this value.
974 Also, see the function \\[py-imenu-create-index] for a better
975 alternative for finding the index.")
977 ;; These next two variables are used when searching for the Python
978 ;; class/definitions. Just saving some time in accessing the
979 ;; generic-python-expression, really.
980 (defvar py-imenu-generic-regexp nil)
981 (defvar py-imenu-generic-parens nil)
984 (defun py-imenu-create-index-function ()
985 "Python interface function for the Imenu package.
986 Finds all Python classes and functions/methods. Calls function
987 \\[py-imenu-create-index-engine]. See that function for the details
989 (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
990 py-imenu-generic-parens (if py-imenu-show-method-args-p
991 py-imenu-method-arg-parens
992 py-imenu-method-no-arg-parens))
993 (goto-char (point-min))
994 ;; Warning: When the buffer has no classes or functions, this will
995 ;; return nil, which seems proper according to the Imenu API, but
996 ;; causes an error in the XEmacs port of Imenu. Sigh.
997 (py-imenu-create-index-engine nil))
999 (defun py-imenu-create-index-engine (&optional start-indent)
1000 "Function for finding Imenu definitions in Python.
1002 Finds all definitions (classes, methods, or functions) in a Python
1003 file for the Imenu package.
1005 Returns a possibly nested alist of the form
1007 (INDEX-NAME . INDEX-POSITION)
1009 The second element of the alist may be an alist, producing a nested
1012 (INDEX-NAME . INDEX-ALIST)
1014 This function should not be called directly, as it calls itself
1015 recursively and requires some setup. Rather this is the engine for
1016 the function \\[py-imenu-create-index-function].
1018 It works recursively by looking for all definitions at the current
1019 indention level. When it finds one, it adds it to the alist. If it
1020 finds a definition at a greater indentation level, it removes the
1021 previous definition from the alist. In its place it adds all
1022 definitions found at the next indentation level. When it finds a
1023 definition that is less indented then the current level, it returns
1024 the alist it has created thus far.
1026 The optional argument START-INDENT indicates the starting indentation
1027 at which to continue looking for Python classes, methods, or
1028 functions. If this is not supplied, the function uses the indentation
1029 of the first definition found."
1035 (class-paren (first py-imenu-generic-parens))
1036 (def-paren (second py-imenu-generic-parens)))
1038 (re-search-forward py-imenu-generic-regexp (point-max) t))
1041 ;; used to set def-name to this value but generic-extract-name
1042 ;; is new to imenu-1.14. this way it still works with
1044 ;;(imenu--generic-extract-name py-imenu-generic-parens))
1045 (let ((cur-paren (if (match-beginning class-paren)
1046 class-paren def-paren)))
1048 (buffer-substring-no-properties (match-beginning cur-paren)
1049 (match-end cur-paren))))
1051 (py-beginning-of-def-or-class 'either))
1053 (setq cur-indent (current-indentation)))
1054 ;; HACK: want to go to the next correct definition location. We
1055 ;; explicitly list them here but it would be better to have them
1058 (or (match-beginning class-paren)
1059 (match-beginning def-paren)))
1060 ;; if we don't have a starting indent level, take this one
1062 (setq start-indent cur-indent))
1063 ;; if we don't have class name yet, take this one
1065 (setq prev-name def-name))
1066 ;; what level is the next definition on? must be same, deeper
1067 ;; or shallower indentation
1069 ;; Skip code in comments and strings
1071 ;; at the same indent level, add it to the list...
1072 ((= start-indent cur-indent)
1073 (push (cons def-name def-pos) index-alist))
1074 ;; deeper indented expression, recurse
1075 ((< start-indent cur-indent)
1076 ;; the point is currently on the expression we're supposed to
1077 ;; start on, so go back to the last expression. The recursive
1078 ;; call will find this place again and add it to the correct
1080 (re-search-backward py-imenu-generic-regexp (point-min) 'move)
1081 (setq sub-method-alist (py-imenu-create-index-engine cur-indent))
1082 (if sub-method-alist
1083 ;; we put the last element on the index-alist on the start
1084 ;; of the submethod alist so the user can still get to it.
1085 (let ((save-elmt (pop index-alist)))
1086 (push (cons prev-name
1087 (cons save-elmt sub-method-alist))
1089 ;; found less indented expression, we're done.
1091 (setq looking-p nil)
1092 (re-search-backward py-imenu-generic-regexp (point-min) t)))
1094 (setq prev-name def-name)
1097 (re-search-forward py-imenu-generic-regexp
1098 (point-max) 'move))))
1099 (nreverse index-alist)))
1103 (defun py-choose-shell-by-shebang ()
1104 "Choose CPython or Jython mode by looking at #! on the first line.
1105 Returns the appropriate mode function.
1106 Used by `py-choose-shell', and similar to but distinct from
1107 `set-auto-mode', though it uses `auto-mode-interpreter-regexp' (if available)."
1108 ;; look for an interpreter specified in the first line
1109 ;; similar to set-auto-mode (files.el)
1110 (let* ((re (if (boundp 'auto-mode-interpreter-regexp)
1111 auto-mode-interpreter-regexp
1112 ;; stolen from Emacs 21.2
1113 "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1114 (interpreter (save-excursion
1115 (goto-char (point-min))
1120 ;; Map interpreter name to a mode.
1121 (setq elt (assoc (file-name-nondirectory interpreter)
1123 (and elt (caddr elt))))
1127 (defun py-choose-shell-by-import ()
1128 "Choose CPython or Jython mode based imports.
1129 If a file imports any packages in `py-jython-packages', within
1130 `py-import-check-point-max' characters from the start of the file,
1131 return `jython', otherwise return nil."
1134 (goto-char (point-min))
1135 (while (and (not mode)
1136 (search-forward-regexp
1137 "^\\(\\(from\\)\\|\\(import\\)\\) \\([^ \t\n.]+\\)"
1138 py-import-check-point-max t))
1139 (setq mode (and (member (match-string 4) py-jython-packages)
1145 (defun py-choose-shell ()
1146 "Choose CPython or Jython mode. Returns the appropriate mode function.
1147 This does the following:
1148 - look for an interpreter with `py-choose-shell-by-shebang'
1149 - examine imports using `py-choose-shell-by-import'
1150 - default to the variable `py-default-interpreter'"
1152 (or (py-choose-shell-by-shebang)
1153 (py-choose-shell-by-import)
1154 py-default-interpreter
1155 ; 'cpython ;; don't use to py-default-interpreter, because default
1156 ; ;; is only way to choose CPython
1161 (defun python-mode ()
1162 "Major mode for editing Python files.
1163 To submit a problem report, enter `\\[py-submit-bug-report]' from a
1164 `python-mode' buffer. Do `\\[py-describe-mode]' for detailed
1165 documentation. To see what version of `python-mode' you are running,
1166 enter `\\[py-version]'.
1168 This mode knows about Python indentation, tokens, comments and
1169 continuation lines. Paragraphs are separated by blank lines only.
1175 py-indent-offset\t\tindentation increment
1176 py-block-comment-prefix\t\tcomment string used by `comment-region'
1177 py-python-command\t\tshell command to invoke Python interpreter
1178 py-temp-directory\t\tdirectory used for temp files (if needed)
1179 py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
1181 ;; set up local variables
1182 (kill-all-local-variables)
1183 (make-local-variable 'font-lock-defaults)
1184 (make-local-variable 'paragraph-separate)
1185 (make-local-variable 'paragraph-start)
1186 (make-local-variable 'require-final-newline)
1187 (make-local-variable 'comment-start)
1188 (make-local-variable 'comment-end)
1189 (make-local-variable 'comment-start-skip)
1190 (make-local-variable 'comment-column)
1191 (make-local-variable 'comment-indent-function)
1192 (make-local-variable 'indent-region-function)
1193 (make-local-variable 'indent-line-function)
1194 (make-local-variable 'add-log-current-defun-function)
1195 (make-local-variable 'fill-paragraph-function)
1197 (set-syntax-table py-mode-syntax-table)
1198 (setq major-mode 'python-mode
1200 local-abbrev-table python-mode-abbrev-table
1201 font-lock-defaults '(python-font-lock-keywords)
1202 paragraph-separate "^[ \t]*$"
1203 paragraph-start "^[ \t]*$"
1204 require-final-newline t
1207 comment-start-skip "# *"
1209 comment-indent-function 'py-comment-indent-function
1210 indent-region-function 'py-indent-region
1211 indent-line-function 'py-indent-line
1212 ;; tell add-log.el how to find the current function/method/variable
1213 add-log-current-defun-function 'py-current-defun
1215 fill-paragraph-function 'py-fill-paragraph
1217 (use-local-map py-mode-map)
1220 (easy-menu-add py-menu))
1221 ;; Emacs 19 requires this
1222 (if (boundp 'comment-multi-line)
1223 (setq comment-multi-line nil))
1224 ;; Install Imenu if available
1225 (when (py-safe (require 'imenu))
1226 (setq imenu-create-index-function #'py-imenu-create-index-function)
1227 (setq imenu-generic-expression py-imenu-generic-expression)
1228 (if (fboundp 'imenu-add-to-menubar)
1229 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1232 ;; Add support for HideShow
1233 (add-to-list 'hs-special-modes-alist (list
1234 'python-mode (concat (if py-hide-show-hide-docstrings "^\\s-*\"\"\"\\|" "") (mapconcat 'identity (mapcar #'(lambda (x) (concat "^\\s-*" x "\\>")) py-hide-show-keywords ) "\\|")) nil "#"
1236 (py-goto-beyond-block)
1237 (skip-chars-backward " \t\n"))
1240 ;; Run the mode hook. Note that py-mode-hook is deprecated.
1241 (if python-mode-hook
1242 (run-hooks 'python-mode-hook)
1243 (run-hooks 'py-mode-hook))
1244 ;; Now do the automagical guessing
1245 (if py-smart-indentation
1246 (let ((offset py-indent-offset))
1247 ;; It's okay if this fails to guess a good value
1248 (if (and (py-safe (py-guess-indent-offset))
1249 (<= py-indent-offset 8)
1250 (>= py-indent-offset 2))
1251 (setq offset py-indent-offset))
1252 (setq py-indent-offset offset)
1253 ;; Only turn indent-tabs-mode off if tab-width !=
1254 ;; py-indent-offset. Never turn it on, because the user must
1255 ;; have explicitly turned it off.
1256 (if (/= tab-width py-indent-offset)
1257 (setq indent-tabs-mode nil))
1259 ;; Set the default shell if not already set
1260 (when (null py-which-shell)
1261 (py-toggle-shells (py-choose-shell))))
1264 (make-obsolete 'jpython-mode 'jython-mode)
1265 (defun jython-mode ()
1266 "Major mode for editing Jython/Jython files.
1267 This is a simple wrapper around `python-mode'.
1268 It runs `jython-mode-hook' then calls `python-mode.'
1269 It is added to `interpreter-mode-alist' and `py-choose-shell'.
1273 (py-toggle-shells 'jython)
1274 (when jython-mode-hook
1275 (run-hooks 'jython-mode-hook)))
1278 ;; It's handy to add recognition of Python files to the
1279 ;; interpreter-mode-alist and to auto-mode-alist. With the former, we
1280 ;; can specify different `derived-modes' based on the #! line, but
1281 ;; with the latter, we can't. So we just won't add them if they're
1284 (let ((modes '(("jython" . jython-mode)
1285 ("python" . python-mode))))
1287 (when (not (assoc (car modes) interpreter-mode-alist))
1288 (push (car modes) interpreter-mode-alist))
1289 (setq modes (cdr modes))))
1291 (when (not (or (rassq 'python-mode auto-mode-alist)
1292 (rassq 'jython-mode auto-mode-alist)))
1293 (push '("\\.py$" . python-mode) auto-mode-alist))
1297 ;; electric characters
1298 (defun py-outdent-p ()
1299 "Returns non-nil if the current line should dedent one level."
1301 (and (progn (back-to-indentation)
1302 (looking-at py-outdent-re))
1303 ;; short circuit infloop on illegal construct
1305 (progn (forward-line -1)
1306 (py-goto-initial-line)
1307 (back-to-indentation)
1308 (while (or (looking-at py-blank-or-comment-re)
1310 (backward-to-indentation 1))
1311 (not (looking-at py-no-outdent-re)))
1314 (defun py-electric-colon (arg)
1316 In certain cases the line is dedented appropriately. If a numeric
1317 argument ARG is provided, that many colons are inserted
1318 non-electrically. Electric behavior is inhibited inside a string or
1321 (self-insert-command (prefix-numeric-value arg))
1322 ;; are we in a string or comment?
1324 (let ((pps (parse-partial-sexp (save-excursion
1325 (py-beginning-of-def-or-class)
1328 (not (or (nth 3 pps) (nth 4 pps)))))
1330 (let ((here (point))
1332 (indent (py-compute-indentation t)))
1335 (= indent (save-excursion
1336 (py-next-statement -1)
1337 (py-compute-indentation t)))
1339 (setq outdent py-indent-offset))
1340 ;; Don't indent, only dedent. This assumes that any lines
1341 ;; that are already dedented relative to
1342 ;; py-compute-indentation were put there on purpose. It's
1343 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1344 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1345 ;; determine this???
1346 (if (< (current-indentation) indent) nil
1349 (delete-horizontal-space)
1350 (indent-to (- indent outdent))
1354 ;; Python subprocess utilities and filters
1355 (defun py-execute-file (proc filename)
1356 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1357 Make that process's buffer visible and force display. Also make
1358 comint believe the user typed this string so that
1359 `kill-output-from-shell' does The Right Thing."
1360 (let ((curbuf (current-buffer))
1361 (procbuf (process-buffer proc))
1362 ; (comint-scroll-to-bottom-on-output t)
1363 (msg (format "## working on region in file %s...\n" filename))
1364 ;; add some comment, so that we can filter it out of history
1365 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
1368 (set-buffer procbuf)
1369 (goto-char (point-max))
1370 (move-marker (process-mark proc) (point))
1371 (funcall (process-filter proc) proc msg))
1372 (set-buffer curbuf))
1373 (process-send-string proc cmd)))
1375 (defun py-comint-output-filter-function (string)
1376 "Watch output for Python prompt and exec next file waiting in queue.
1377 This function is appropriate for `comint-output-filter-functions'."
1378 ;;remove ansi terminal escape sequences from string, not sure why they are
1380 (setq string (ansi-color-filter-apply string))
1381 (when (and (string-match py-shell-input-prompt-1-regexp string)
1383 (if py-shell-switch-buffers-on-execute
1384 (pop-to-buffer (current-buffer)))
1385 (py-safe (delete-file (car py-file-queue)))
1386 (setq py-file-queue (cdr py-file-queue))
1388 (let ((pyproc (get-buffer-process (current-buffer))))
1389 (py-execute-file pyproc (car py-file-queue))))
1392 (defun py-pdbtrack-overlay-arrow (activation)
1393 "Activate or de arrow at beginning-of-line in current buffer."
1394 ;; This was derived/simplified from edebug-overlay-arrow
1396 (setq overlay-arrow-position (make-marker))
1397 (setq overlay-arrow-string "=>")
1398 (set-marker overlay-arrow-position (py-point 'bol) (current-buffer))
1399 (setq py-pdbtrack-is-tracking-p t))
1400 (overlay-arrow-position
1401 (setq overlay-arrow-position nil)
1402 (setq py-pdbtrack-is-tracking-p nil))
1405 (defun py-pdbtrack-track-stack-file (text)
1406 "Show the file indicated by the pdb stack entry line, in a separate window.
1408 Activity is disabled if the buffer-local variable
1409 `py-pdbtrack-do-tracking-p' is nil.
1411 We depend on the pdb input prompt matching `py-pdbtrack-input-prompt'
1412 at the beginning of the line.
1414 If the traceback target file path is invalid, we look for the most
1415 recently visited python-mode buffer which either has the name of the
1416 current function \(or class) or which defines the function \(or
1417 class). This is to provide for remote scripts, eg, Zope's 'Script
1418 (Python)' - put a _copy_ of the script in a buffer named for the
1419 script, and set to python-mode, and pdbtrack will find it.)"
1420 ;; Instead of trying to piece things together from partial text
1421 ;; (which can be almost useless depending on Emacs version), we
1422 ;; monitor to the point where we have the next pdb prompt, and then
1423 ;; check all text from comint-last-input-end to process-mark.
1425 ;; Also, we're very conservative about clearing the overlay arrow,
1426 ;; to minimize residue. This means, for instance, that executing
1427 ;; other pdb commands wipe out the highlight. You can always do a
1428 ;; 'where' (aka 'w') command to reveal the overlay arrow.
1429 (let* ((origbuf (current-buffer))
1430 (currproc (get-buffer-process origbuf)))
1432 (if (not (and currproc py-pdbtrack-do-tracking-p))
1433 (py-pdbtrack-overlay-arrow nil)
1435 (let* ((procmark (process-mark currproc))
1436 (block (buffer-substring (max comint-last-input-end
1438 py-pdbtrack-track-range))
1440 target target_fname target_lineno target_buffer)
1442 (if (not (string-match (concat py-pdbtrack-input-prompt "$") block))
1443 (py-pdbtrack-overlay-arrow nil)
1445 (setq target (py-pdbtrack-get-source-buffer block))
1447 (if (stringp target)
1448 (message "pdbtrack: %s" target)
1450 (setq target_lineno (car target))
1451 (setq target_buffer (cadr target))
1452 (setq target_fname (buffer-file-name target_buffer))
1453 (switch-to-buffer-other-window target_buffer)
1454 (goto-line target_lineno)
1455 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
1456 (py-pdbtrack-overlay-arrow t)
1457 (pop-to-buffer origbuf t)
1462 (defun py-pdbtrack-get-source-buffer (block)
1463 "Return line number and buffer of code indicated by block's traceback text.
1465 We look first to visit the file indicated in the trace.
1467 Failing that, we look for the most recently visited python-mode buffer
1468 with the same name or having the named function.
1470 If we're unable find the source code we return a string describing the
1471 problem as best as we can determine."
1473 (if (not (string-match py-pdbtrack-stack-entry-regexp block))
1475 "Traceback cue not found"
1477 (let* ((filename (match-string 1 block))
1478 (lineno (string-to-number (match-string 2 block)))
1479 (funcname (match-string 3 block))
1482 (cond ((file-exists-p filename)
1483 (list lineno (find-file-noselect filename)))
1485 ((setq funcbuffer (py-pdbtrack-grub-for-buffer funcname lineno))
1486 (if (string-match "/Script (Python)$" filename)
1487 ;; Add in number of lines for leading '##' comments:
1491 (set-buffer funcbuffer)
1495 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
1496 (buffer-substring (point-min)
1499 (list lineno funcbuffer))
1501 ((= (elt filename 0) ?\<)
1502 (format "(Non-file source: '%s')" filename))
1504 (t (format "Not found: %s(), %s" funcname filename)))
1509 (defun py-pdbtrack-grub-for-buffer (funcname lineno)
1510 "Find most recent buffer itself named or having function funcname.
1512 We walk the buffer-list history for python-mode buffers that are
1513 named for funcname or define a function funcname."
1514 (let ((buffers (buffer-list))
1517 (while (and buffers (not got))
1518 (setq buf (car buffers)
1519 buffers (cdr buffers))
1520 (if (and (save-excursion (set-buffer buf)
1521 (string= major-mode "python-mode"))
1522 (or (string-match funcname (buffer-name buf))
1523 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
1527 (buffer-substring (point-min)
1532 (defun py-postprocess-output-buffer (buf)
1533 "Highlight exceptions found in BUF.
1534 If an exception occurred return t, otherwise return nil. BUF must exist."
1535 (let (line file bol err-p)
1538 (goto-char (point-min))
1539 (while (re-search-forward py-traceback-line-re nil t)
1540 (setq file (match-string 1)
1541 line (string-to-number (match-string 2))
1542 bol (py-point 'bol))
1543 (py-highlight-line bol (py-point 'eol) file line)))
1544 (when (and py-jump-on-exception line)
1546 (py-jump-to-exception file line)
1552 ;;; Subprocess commands
1554 ;; only used when (memq 'broken-temp-names py-emacs-features)
1555 (defvar py-serial-number 0)
1556 (defvar py-exception-buffer nil)
1557 (defvar py-output-buffer "*Python Output*")
1558 (make-variable-buffer-local 'py-output-buffer)
1560 ;; for toggling between CPython and Jython
1561 (defvar py-which-shell nil)
1562 (defvar py-which-args py-python-command-args)
1563 (defvar py-which-bufname "Python")
1564 (make-variable-buffer-local 'py-which-shell)
1565 (make-variable-buffer-local 'py-which-args)
1566 (make-variable-buffer-local 'py-which-bufname)
1568 (defun py-toggle-shells (arg)
1569 "Toggles between the CPython and Jython shells.
1571 With positive argument ARG (interactively \\[universal-argument]),
1572 uses the CPython shell, with negative ARG uses the Jython shell, and
1573 with a zero argument, toggles the shell.
1575 Programmatically, ARG can also be one of the symbols `cpython' or
1576 `jython', equivalent to positive arg and negative arg respectively."
1578 ;; default is to toggle
1585 (if (string-equal py-which-bufname "Python")
1588 ((equal arg 'cpython) (setq arg 1))
1589 ((equal arg 'jython) (setq arg -1)))
1594 (setq py-which-shell py-python-command
1595 py-which-args py-python-command-args
1596 py-which-bufname "Python"
1598 (if (string-equal py-which-bufname "Jython")
1599 (setq mode-name "Python")))
1601 (setq py-which-shell py-jython-command
1602 py-which-args py-jython-command-args
1603 py-which-bufname "Jython"
1605 (if (string-equal py-which-bufname "Python")
1606 (setq mode-name "Jython")))
1608 (message "Using the %s shell" msg)
1609 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
1612 (defun py-shell (&optional argprompt)
1613 "Start an interactive Python interpreter in another window.
1614 This is like Shell mode, except that Python is running in the window
1615 instead of a shell. See the `Interactive Shell' and `Shell Mode'
1616 sections of the Emacs manual for details, especially for the key
1617 bindings active in the `*Python*' buffer.
1619 With optional \\[universal-argument], the user is prompted for the
1620 flags to pass to the Python interpreter. This has no effect when this
1621 command is used to switch to an existing process, only when a new
1622 process is started. If you use this, you will probably want to ensure
1623 that the current arguments are retained (they will be included in the
1624 prompt). This argument is ignored when this function is called
1625 programmatically, or when running in Emacs 19.34 or older.
1627 Note: You can toggle between using the CPython interpreter and the
1628 Jython interpreter by hitting \\[py-toggle-shells]. This toggles
1629 buffer local variables which control whether all your subshell
1630 interactions happen to the `*Jython*' or `*Python*' buffers (the
1631 latter is the name used for the CPython buffer).
1633 Warning: Don't use an interactive Python if you change sys.ps1 or
1634 sys.ps2 from their default values, or if you're running code that
1635 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1636 distinguish your output from Python's output, and assumes that `>>> '
1637 at the start of a line is a prompt from Python. Similarly, the Emacs
1638 Shell mode code assumes that both `>>> ' and `... ' at the start of a
1639 line are Python prompts. Bad things can happen if you fool either
1642 Warning: If you do any editing *in* the process buffer *while* the
1643 buffer is accepting output from Python, do NOT attempt to `undo' the
1644 changes. Some of the output (nowhere near the parts you changed!) may
1645 be lost if you do. This appears to be an Emacs bug, an unfortunate
1646 interaction between undo and process filters; the same problem exists in
1647 non-Python process buffers using the default (Emacs-supplied) process
1650 ;; Set the default shell if not already set
1651 (when (null py-which-shell)
1652 (py-toggle-shells py-default-interpreter))
1653 (let ((args py-which-args))
1654 (when (and argprompt
1656 (fboundp 'split-string))
1657 ;; TBD: Perhaps force "-i" in the final list?
1658 (setq args (split-string
1659 (read-string (concat py-which-bufname
1662 (mapconcat 'identity py-which-args " ") " ")
1664 (if (not (equal (buffer-name) "*Python*"))
1665 (switch-to-buffer-other-window
1666 (apply 'make-comint py-which-bufname py-which-shell nil args))
1667 (apply 'make-comint py-which-bufname py-which-shell nil args))
1668 (make-local-variable 'comint-prompt-regexp)
1669 (setq comint-prompt-regexp (concat py-shell-input-prompt-1-regexp "\\|"
1670 py-shell-input-prompt-2-regexp "\\|"
1672 (add-hook 'comint-output-filter-functions
1673 'py-comint-output-filter-function)
1675 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
1676 (setq py-pdbtrack-do-tracking-p t)
1677 (set-syntax-table py-mode-syntax-table)
1678 (use-local-map py-shell-map)
1679 (run-hooks 'py-shell-hook)
1682 (defun py-clear-queue ()
1683 "Clear the queue of temporary files waiting to execute."
1685 (let ((n (length py-file-queue)))
1686 (mapc 'delete-file py-file-queue)
1687 (setq py-file-queue nil)
1688 (message "%d pending files de-queued." n)))
1691 (defun py-execute-region (start end &optional async)
1692 "Execute the region in a Python interpreter.
1694 The region is first copied into a temporary file (in the directory
1695 `py-temp-directory'). If there is no Python interpreter shell
1696 running, this file is executed synchronously using
1697 `shell-command-on-region'. If the program is long running, use
1698 \\[universal-argument] to run the command asynchronously in its own
1701 When this function is used programmatically, arguments START and END
1702 specify the region to execute, and optional third argument ASYNC, if
1703 non-nil, specifies to run the command asynchronously in its own
1706 If the Python interpreter shell is running, the region is execfile()'d
1707 in that shell. If you try to execute regions too quickly,
1708 `python-mode' will queue them up and execute them one at a time when
1709 it sees a `>>> ' prompt from Python. Each time this happens, the
1710 process buffer is popped into a window (if it's not already in some
1711 window) so you can see it, and a comment of the form
1713 \t## working on region in file <name>...
1715 is inserted at the end. See also the command `py-clear-queue'."
1716 (interactive "r\nP")
1717 ;; Skip ahead to the first non-blank line
1718 (let* ((proc (get-process py-which-bufname))
1719 (temp (if (memq 'broken-temp-names py-emacs-features)
1721 ((sn py-serial-number)
1722 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1723 (setq py-serial-number (1+ py-serial-number))
1725 (format "python-%d-%d" sn pid)
1726 (format "python-%d" sn)))
1727 (make-temp-name "python-")))
1728 (file (concat (expand-file-name temp py-temp-directory) ".py"))
1729 (cur (current-buffer))
1730 (buf (get-buffer-create file))
1732 ;; Write the contents of the buffer, watching out for indented regions.
1736 (while (and (looking-at "\\s *$")
1739 (setq start (point))
1741 (error "Region is empty"))
1742 (setq py-line-number-offset (count-lines 1 start))
1743 (let ((needs-if (/= (py-point 'bol) (py-point 'boi))))
1748 (setq py-line-number-offset (- py-line-number-offset 1)))
1749 (insert-buffer-substring cur start end)
1750 ;; Set the shell either to the #! line command, or to the
1751 ;; py-which-shell buffer local variable.
1752 (setq shell (or (py-choose-shell-by-shebang)
1753 (py-choose-shell-by-import)
1756 ;; always run the code in its own asynchronous subprocess
1758 ;; User explicitly wants this to run in its own async subprocess
1761 (write-region (point-min) (point-max) file nil 'nomsg))
1762 (let* ((buf (generate-new-buffer-name py-output-buffer))
1763 ;; TBD: a horrible hack, but why create new Custom variables?
1764 (arg (if (string-equal py-which-bufname "Python")
1766 (start-process py-which-bufname buf shell arg file)
1768 (py-postprocess-output-buffer buf)
1769 ;; TBD: clean up the temporary file!
1771 ;; if the Python interpreter shell is running, queue it up for
1774 ;; use the existing python shell
1777 (write-region (point-min) (point-max) file nil 'nomsg))
1778 (if (not py-file-queue)
1779 (py-execute-file proc file)
1780 (message "File %s queued for execution" file))
1781 (setq py-file-queue (append py-file-queue (list file)))
1782 (setq py-exception-buffer (cons file (current-buffer))))
1784 ;; TBD: a horrible hack, but why create new Custom variables?
1785 (let ((cmd (concat py-which-shell (if (string-equal py-which-bufname
1788 ;; otherwise either run it synchronously in a subprocess
1791 (shell-command-on-region (point-min) (point-max)
1792 cmd py-output-buffer))
1793 ;; shell-command-on-region kills the output buffer if it never
1794 ;; existed and there's no output from the command
1795 (if (not (get-buffer py-output-buffer))
1796 (message "No output.")
1797 (setq py-exception-buffer (current-buffer))
1798 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1799 (pop-to-buffer py-output-buffer)
1801 (pop-to-buffer py-exception-buffer)))
1804 ;; Clean up after ourselves.
1808 ;; Code execution commands
1809 (defun py-execute-buffer (&optional async)
1810 "Send the contents of the buffer to a Python interpreter.
1811 If the file local variable `py-master-file' is non-nil, execute the
1812 named file instead of the buffer's file.
1814 If there is a *Python* process buffer it is used. If a clipping
1815 restriction is in effect, only the accessible portion of the buffer is
1816 sent. A trailing newline will be supplied if needed.
1818 See the `\\[py-execute-region]' docs for an account of some
1819 subtleties, including the use of the optional ASYNC argument."
1821 (let ((old-buffer (current-buffer)))
1823 (let* ((filename (expand-file-name py-master-file))
1824 (buffer (or (get-file-buffer filename)
1825 (find-file-noselect filename))))
1826 (set-buffer buffer)))
1827 (py-execute-region (point-min) (point-max) async)
1828 (pop-to-buffer old-buffer)))
1830 (defun py-execute-import-or-reload (&optional async)
1831 "Import the current buffer's file in a Python interpreter.
1833 If the file has already been imported, then do reload instead to get
1836 If the file's name does not end in \".py\", then do execfile instead.
1838 If the current buffer is not visiting a file, do `py-execute-buffer'
1841 If the file local variable `py-master-file' is non-nil, import or
1842 reload the named file instead of the buffer's file. The file may be
1843 saved based on the value of `py-execute-import-or-reload-save-p'.
1845 See the `\\[py-execute-region]' docs for an account of some
1846 subtleties, including the use of the optional ASYNC argument.
1848 This may be preferable to `\\[py-execute-buffer]' because:
1850 - Definitions stay in their module rather than appearing at top
1851 level, where they would clutter the global namespace and not affect
1852 uses of qualified names (MODULE.NAME).
1854 - The Python debugger gets line number information about the functions."
1856 ;; Check file local variable py-master-file
1858 (let* ((filename (expand-file-name py-master-file))
1859 (buffer (or (get-file-buffer filename)
1860 (find-file-noselect filename))))
1861 (set-buffer buffer)))
1862 (let ((file (buffer-file-name (current-buffer))))
1865 ;; Maybe save some buffers
1866 (save-some-buffers (not py-ask-about-save) nil)
1868 (if (string-match "\\.py$" file)
1869 (let ((f (file-name-sans-extension
1870 (file-name-nondirectory file))))
1871 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1873 (format "execfile(r'%s')\n" file))
1876 (py-execute-buffer async))))
1879 (defun py-execute-def-or-class (&optional async)
1880 "Send the current function or class definition to a Python interpreter.
1882 If there is a *Python* process buffer it is used.
1884 See the `\\[py-execute-region]' docs for an account of some
1885 subtleties, including the use of the optional ASYNC argument."
1888 (py-mark-def-or-class)
1889 ;; mark is before point
1890 (py-execute-region (mark) (point) async)))
1893 (defun py-execute-string (string &optional async)
1894 "Send the argument STRING to a Python interpreter.
1896 If there is a *Python* process buffer it is used.
1898 See the `\\[py-execute-region]' docs for an account of some
1899 subtleties, including the use of the optional ASYNC argument."
1900 (interactive "sExecute Python command: ")
1902 (set-buffer (get-buffer-create
1903 (generate-new-buffer-name " *Python Command*")))
1905 (py-execute-region (point-min) (point-max) async)))
1909 (defun py-jump-to-exception (file line)
1910 "Jump to the Python code in FILE at LINE."
1911 (let ((buffer (cond ((string-equal file "<stdin>")
1912 (if (consp py-exception-buffer)
1913 (cdr py-exception-buffer)
1914 py-exception-buffer))
1915 ((and (consp py-exception-buffer)
1916 (string-equal file (car py-exception-buffer)))
1917 (cdr py-exception-buffer))
1918 ((py-safe (find-file-noselect file)))
1919 ;; could not figure out what file the exception
1920 ;; is pointing to, so prompt for it
1921 (t (find-file (read-file-name "Exception file: "
1924 ;; Fiddle about with line number
1925 (setq line (+ py-line-number-offset line))
1927 (pop-to-buffer buffer)
1928 ;; Force Python mode
1929 (if (not (eq major-mode 'python-mode))
1932 (message "Jumping to exception in file %s on line %d" file line)))
1934 (defun py-mouseto-exception (event)
1935 "Jump to the code which caused the Python exception at EVENT.
1936 EVENT is usually a mouse click."
1939 ((fboundp 'event-point)
1941 (let* ((point (event-point event))
1942 (buffer (event-buffer event))
1943 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1944 (info (and e (extent-property e 'py-exc-info))))
1945 (message "Event point: %d, info: %s" point info)
1947 (py-jump-to-exception (car info) (cdr info)))
1949 ;; Emacs -- Please port this!
1952 (defun py-goto-exception ()
1953 "Go to the line indicated by the traceback."
1958 (if (looking-at py-traceback-line-re)
1959 (setq file (match-string 1)
1960 line (string-to-number (match-string 2)))))
1962 (error "Not on a traceback line"))
1963 (py-jump-to-exception file line)))
1965 (defun py-find-next-exception (start buffer searchdir errwhere)
1966 "Find the next Python exception and jump to the code that caused it.
1967 START is the buffer position in BUFFER from which to begin searching
1968 for an exception. SEARCHDIR is a function, either
1969 `re-search-backward' or `re-search-forward' indicating the direction
1970 to search. ERRWHERE is used in an error message if the limit (top or
1971 bottom) of the trackback stack is encountered."
1975 (goto-char (py-point start))
1976 (if (funcall searchdir py-traceback-line-re nil t)
1977 (setq file (match-string 1)
1978 line (string-to-number (match-string 2)))))
1980 (py-jump-to-exception file line)
1981 (error "%s of traceback" errwhere))))
1983 (defun py-down-exception (&optional bottom)
1984 "Go to the next line down in the traceback.
1985 With \\[univeral-argument] (programmatically, optional argument
1986 BOTTOM), jump to the bottom (innermost) exception in the exception
1989 (let* ((proc (get-process "Python"))
1990 (buffer (if proc "*Python*" py-output-buffer)))
1992 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1993 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1995 (defun py-up-exception (&optional top)
1996 "Go to the previous line up in the traceback.
1997 With \\[universal-argument] (programmatically, optional argument TOP)
1998 jump to the top (outermost) exception in the exception stack."
2000 (let* ((proc (get-process "Python"))
2001 (buffer (if proc "*Python*" py-output-buffer)))
2003 (py-find-next-exception 'bob buffer 're-search-forward "Top")
2004 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
2007 ;; Electric deletion
2008 (defun py-electric-backspace (arg)
2009 "Delete preceding character or levels of indentation.
2010 Deletion is performed by calling the function in `py-backspace-function'
2011 with a single argument (the number of characters to delete).
2013 If point is at the leftmost column, delete the preceding newline.
2015 Otherwise, if point is at the leftmost non-whitespace character of a
2016 line that is neither a continuation line nor a non-indenting comment
2017 line, or if point is at the end of a blank line, this command reduces
2018 the indentation to match that of the line that opened the current
2019 block of code. The line that opened the block is displayed in the
2020 echo area to help you keep track of where you are. With
2021 \\[universal-argument] dedents that many blocks (but not past column
2024 Otherwise the preceding character is deleted, converting a tab to
2025 spaces if needed so that only a single column position is deleted.
2026 \\[universal-argument] specifies how many characters to delete;
2029 When used programmatically, argument ARG specifies the number of
2030 blocks to dedent, or the number of characters to delete, as indicated
2033 (if (or (/= (current-indentation) (current-column))
2035 (py-continuation-line-p)
2036 ; (not py-honor-comment-indentation)
2037 ; (looking-at "#[^ \t\n]") ; non-indenting #
2039 (funcall py-backspace-function arg)
2040 ;; else indent the same as the colon line that opened the block
2041 ;; force non-blank so py-goto-block-up doesn't ignore it
2044 (let ((base-indent 0) ; indentation of base line
2045 (base-text "") ; and text of base line
2049 (condition-case nil ; in case no enclosing block
2051 (py-goto-block-up 'no-mark)
2052 (setq base-indent (current-indentation)
2053 base-text (py-suck-up-leading-text)
2056 (setq arg (1- arg))))
2057 (delete-char 1) ; toss the dummy character
2058 (delete-horizontal-space)
2059 (indent-to base-indent)
2061 (message "Closes block: %s" base-text)))))
2064 (defun py-electric-delete (arg)
2065 "Delete preceding or following character or levels of whitespace.
2067 The behavior of this function depends on the variable
2068 `delete-key-deletes-forward'. If this variable is nil (or does not
2069 exist, as in older Emacsen and non-XEmacs versions), then this
2070 function behaves identically to \\[c-electric-backspace].
2072 If `delete-key-deletes-forward' is non-nil and is supported in your
2073 Emacs, then deletion occurs in the forward direction, by calling the
2074 function in `py-delete-function'.
2076 \\[universal-argument] (programmatically, argument ARG) specifies the
2077 number of characters to delete (default is 1)."
2079 (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
2081 (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
2082 delete-key-deletes-forward))
2083 (funcall py-delete-function arg)
2084 (py-electric-backspace arg)))
2086 ;; required for pending-del and delsel modes
2087 (put 'py-electric-colon 'delete-selection t) ;delsel
2088 (put 'py-electric-colon 'pending-delete t) ;pending-del
2089 (put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
2090 (put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
2091 (put 'py-electric-delete 'delete-selection 'supersede) ;delsel
2092 (put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
2096 (defun py-indent-line (&optional arg)
2097 "Fix the indentation of the current line according to Python rules.
2098 With \\[universal-argument] (programmatically, the optional argument
2099 ARG non-nil), ignore dedenting rules for block closing statements
2100 (e.g. return, raise, break, continue, pass)
2102 This function is normally bound to `indent-line-function' so
2103 \\[indent-for-tab-command] will call it."
2105 (let* ((ci (current-indentation))
2106 (move-to-indentation-p (<= (current-column) ci))
2107 (need (py-compute-indentation (not arg)))
2108 (cc (current-column)))
2109 ;; dedent out a level if previous command was the same unless we're in
2111 (if (and (equal last-command this-command)
2115 (delete-horizontal-space)
2116 (indent-to (* (/ (- cc 1) py-indent-offset) py-indent-offset)))
2118 ;; see if we need to dedent
2120 (setq need (- need py-indent-offset)))
2121 (if (or py-tab-always-indent
2122 move-to-indentation-p)
2123 (progn (if (/= ci need)
2126 (delete-horizontal-space)
2128 (if move-to-indentation-p (back-to-indentation)))
2131 (defun py-newline-and-indent ()
2132 "Strives to act like the Emacs `newline-and-indent'.
2133 This is just `strives to' because correct indentation can't be computed
2134 from scratch for Python code. In general, deletes the whitespace before
2135 point, inserts a newline, and takes an educated guess as to how you want
2136 the new line indented."
2138 (let ((ci (current-indentation)))
2139 (if (< ci (current-column)) ; if point beyond indentation
2140 (newline-and-indent)
2141 ;; else try to act like newline-and-indent "normally" acts
2144 (move-to-column ci))))
2146 (defun py-compute-indentation (honor-block-close-p)
2147 "Compute Python indentation.
2148 When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
2149 `raise', `break', `continue', and `pass' force one level of
2153 (let* ((bod (py-point 'bod))
2154 (pps (parse-partial-sexp bod (point)))
2155 (boipps (parse-partial-sexp bod (py-point 'boi)))
2158 ;; are we inside a multi-line string or comment?
2159 ((or (and (nth 3 pps) (nth 3 boipps))
2160 (and (nth 4 pps) (nth 4 boipps)))
2162 (if (not py-align-multiline-strings-p) 0
2163 ;; skip back over blank & non-indenting comment lines
2164 ;; note: will skip a blank or non-indenting comment line
2165 ;; that happens to be a continuation line too
2166 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
2167 (back-to-indentation)
2168 (if (py-statement-opens-block-p)
2169 (+ (current-column) py-indent-offset)
2170 (current-column)))))
2171 ;; are we on a continuation line?
2172 ((py-continuation-line-p)
2173 (let ((startpos (point))
2174 (open-bracket-pos (py-nesting-level))
2175 endpos searching found state cind cline)
2176 (if open-bracket-pos
2178 (setq endpos (py-point 'bol))
2179 (py-goto-initial-line)
2180 (setq cind (current-indentation))
2183 (nth 9 (save-excursion
2184 (parse-partial-sexp (point) endpos)))
2186 (if (search-forward "\n" bp t) (setq cline cind))
2188 (skip-chars-forward " \t")
2189 (setq cind (if (memq (following-char) '(?\n ?# ?\\))
2190 (+ cline py-indent-offset)
2191 (current-column)))))
2192 ;; else on backslash continuation line
2194 (if (py-continuation-line-p) ; on at least 3rd line in block
2195 (current-indentation) ; so just continue the pattern
2196 ;; else started on 2nd line in block, so indent more.
2197 ;; if base line is an assignment with a start on a RHS,
2198 ;; indent to 2 beyond the leftmost "="; else skip first
2199 ;; chunk of non-whitespace characters on base line, + 1 more
2202 (setq endpos (point)
2204 (back-to-indentation)
2205 (setq startpos (point))
2206 ;; look at all "=" from left to right, stopping at first
2207 ;; one not nested in a list or string
2209 (skip-chars-forward "^=" endpos)
2210 (if (= (point) endpos)
2211 (setq searching nil)
2213 (setq state (parse-partial-sexp startpos (point)))
2214 (if (and (zerop (car state)) ; not in a bracket
2215 (null (nth 3 state))) ; & not in a string
2217 (setq searching nil) ; done searching in any case
2220 (eq (following-char) ?=)
2221 (memq (char-after (- (point) 2))
2223 (if (or (not found) ; not an assignment
2224 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
2226 (goto-char startpos)
2227 (skip-chars-forward "^ \t\n")))
2228 ;; if this is a continuation for a block opening
2229 ;; statement, add some extra offset.
2230 (+ (current-column) (if (py-statement-opens-block-p)
2231 py-continuation-offset 0)
2235 ;; not on a continuation line
2236 ((bobp) (current-indentation))
2238 ;; Dfn: "Indenting comment line". A line containing only a
2239 ;; comment, but which is treated like a statement for
2240 ;; indentation calculation purposes. Such lines are only
2241 ;; treated specially by the mode; they are not treated
2242 ;; specially by the Python interpreter.
2244 ;; The rules for indenting comment lines are a line where:
2245 ;; - the first non-whitespace character is `#', and
2246 ;; - the character following the `#' is whitespace, and
2247 ;; - the line is dedented with respect to (i.e. to the left
2248 ;; of) the indentation of the preceding non-blank line.
2250 ;; The first non-blank line following an indenting comment
2251 ;; line is given the same amount of indentation as the
2252 ;; indenting comment line.
2254 ;; All other comment-only lines are ignored for indentation
2257 ;; Are we looking at a comment-only line which is *not* an
2258 ;; indenting comment line? If so, we assume that it's been
2259 ;; placed at the desired indentation, so leave it alone.
2260 ;; Indenting comment lines are aligned as statements down
2262 ((and (looking-at "[ \t]*#[^ \t\n]")
2263 ;; NOTE: this test will not be performed in older Emacsen
2264 (fboundp 'forward-comment)
2265 (<= (current-indentation)
2267 (forward-comment (- (point-max)))
2268 (current-indentation))))
2269 (current-indentation))
2271 ;; else indentation based on that of the statement that
2272 ;; precedes us; use the first line of that statement to
2273 ;; establish the base, in case the user forced a non-std
2274 ;; indentation for the continuation lines (if any)
2276 ;; skip back over blank & non-indenting comment lines note:
2277 ;; will skip a blank or non-indenting comment line that
2278 ;; happens to be a continuation line too. use fast Emacs 19
2279 ;; function if it's there.
2280 (if (and (eq py-honor-comment-indentation nil)
2281 (fboundp 'forward-comment))
2282 (forward-comment (- (point-max)))
2283 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
2286 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
2287 (setq done (or (bobp)
2288 (and (eq py-honor-comment-indentation t)
2290 (back-to-indentation)
2291 (not (looking-at prefix-re))
2293 (and (not (eq py-honor-comment-indentation t))
2295 (back-to-indentation)
2296 (and (not (looking-at prefix-re))
2297 (or (looking-at "[^#]")
2298 (not (zerop (current-column)))
2303 ;; if we landed inside a string, go to the beginning of that
2304 ;; string. this handles triple quoted, multi-line spanning
2306 (py-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
2307 ;; now skip backward over continued lines
2308 (setq placeholder (point))
2309 (py-goto-initial-line)
2310 ;; we may *now* have landed in a TQS, so find the beginning of
2312 (py-goto-beginning-of-tqs
2313 (save-excursion (nth 3 (parse-partial-sexp
2314 placeholder (point)))))
2315 (+ (current-indentation)
2316 (if (py-statement-opens-block-p)
2318 (if (and honor-block-close-p (py-statement-closes-block-p))
2319 (- py-indent-offset)
2323 (defun py-guess-indent-offset (&optional global)
2324 "Guess a good value for, and change, `py-indent-offset'.
2326 By default, make a buffer-local copy of `py-indent-offset' with the
2327 new value, so that other Python buffers are not affected. With
2328 \\[universal-argument] (programmatically, optional argument GLOBAL),
2329 change the global value of `py-indent-offset'. This affects all
2330 Python buffers (that don't have their own buffer-local copy), both
2331 those currently existing and those created later in the Emacs session.
2333 Some people use a different value for `py-indent-offset' than you use.
2334 There's no excuse for such foolishness, but sometimes you have to deal
2335 with their ugly code anyway. This function examines the file and sets
2336 `py-indent-offset' to what it thinks it was when they created the
2339 Specifically, it searches forward from the statement containing point,
2340 looking for a line that opens a block of code. `py-indent-offset' is
2341 set to the difference in indentation between that line and the Python
2342 statement following it. If the search doesn't succeed going forward,
2343 it's tried again going backward."
2344 (interactive "P") ; raw prefix arg
2350 (py-goto-initial-line)
2351 (while (not (or found (eobp)))
2352 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2353 (not (py-in-literal restart)))
2354 (setq restart (point))
2355 (py-goto-initial-line)
2356 (if (py-statement-opens-block-p)
2358 (goto-char restart))))
2361 (py-goto-initial-line)
2362 (while (not (or found (bobp)))
2364 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2365 (or (py-goto-initial-line) t) ; always true -- side effect
2366 (py-statement-opens-block-p)))))
2367 (setq colon-indent (current-indentation)
2368 found (and found (zerop (py-next-statement 1)))
2369 new-value (- (current-indentation) colon-indent))
2372 (error "Sorry, couldn't guess a value for py-indent-offset")
2373 (funcall (if global 'kill-local-variable 'make-local-variable)
2375 (setq py-indent-offset new-value)
2377 (message "%s value of py-indent-offset set to %d"
2378 (if global "Global" "Local")
2382 (defun py-comment-indent-function ()
2383 "Python version of `comment-indent-function'."
2384 ;; This is required when filladapt is turned off. Without it, when
2385 ;; filladapt is not used, comments which start in column zero
2386 ;; cascade one character to the right
2389 (let ((eol (py-point 'eol)))
2390 (and comment-start-skip
2391 (re-search-forward comment-start-skip eol t)
2392 (setq eol (match-beginning 0)))
2394 (skip-chars-backward " \t")
2395 (max comment-column (+ (current-column) (if (bolp) 0 1)))
2398 (defun py-narrow-to-defun (&optional class)
2399 "Make text outside current defun invisible.
2400 The defun visible is the one that contains point or follows point.
2401 Optional CLASS is passed directly to `py-beginning-of-def-or-class'."
2405 (py-end-of-def-or-class class)
2406 (let ((end (point)))
2407 (py-beginning-of-def-or-class class)
2408 (narrow-to-region (point) end))))
2411 (defun py-shift-region (start end count)
2412 "Indent lines from START to END by COUNT spaces."
2419 (setq start (point))
2420 (indent-rigidly start end count)))
2422 (defun py-shift-region-left (start end &optional count)
2423 "Shift region of Python code to the left.
2424 The lines from the line containing the start of the current region up
2425 to (but not including) the line containing the end of the region are
2426 shifted to the left, by `py-indent-offset' columns.
2428 If a prefix argument is given, the region is instead shifted by that
2429 many columns. With no active region, dedent only the current line.
2430 You cannot dedent the region if any line is already at column zero."
2434 (arg current-prefix-arg))
2436 (list (min p m) (max p m) arg)
2437 (list p (save-excursion (forward-line 1) (point)) arg))))
2438 ;; if any line is at column zero, don't shift the region
2441 (while (< (point) end)
2442 (back-to-indentation)
2443 (if (and (zerop (current-column))
2444 (not (looking-at "\\s *$")))
2445 (error "Region is at left edge"))
2447 (py-shift-region start end (- (prefix-numeric-value
2448 (or count py-indent-offset))))
2449 (py-keep-region-active))
2451 (defun py-shift-region-right (start end &optional count)
2452 "Shift region of Python code to the right.
2453 The lines from the line containing the start of the current region up
2454 to (but not including) the line containing the end of the region are
2455 shifted to the right, by `py-indent-offset' columns.
2457 If a prefix argument is given, the region is instead shifted by that
2458 many columns. With no active region, indent only the current line."
2462 (arg current-prefix-arg))
2464 (list (min p m) (max p m) arg)
2465 (list p (save-excursion (forward-line 1) (point)) arg))))
2466 (py-shift-region start end (prefix-numeric-value
2467 (or count py-indent-offset)))
2468 (py-keep-region-active))
2470 (defun py-indent-region (start end &optional indent-offset)
2471 "Reindent a region of Python code.
2473 The lines from the line containing the start of the current region up
2474 to (but not including) the line containing the end of the region are
2475 reindented. If the first line of the region has a non-whitespace
2476 character in the first column, the first line is left alone and the
2477 rest of the region is reindented with respect to it. Else the entire
2478 region is reindented with respect to the (closest code or indenting
2479 comment) statement immediately preceding the region.
2481 This is useful when code blocks are moved or yanked, when enclosing
2482 control structures are introduced or removed, or to reformat code
2483 using a new value for the indentation offset.
2485 If a numeric prefix argument is given, it will be used as the value of
2486 the indentation offset. Else the value of `py-indent-offset' will be
2489 Warning: The region must be consistently indented before this function
2490 is called! This function does not compute proper indentation from
2491 scratch (that's impossible in Python), it merely adjusts the existing
2492 indentation to be correct in context.
2494 Warning: This function really has no idea what to do with
2495 non-indenting comment lines, and shifts them as if they were indenting
2496 comment lines. Fixing this appears to require telepathy.
2498 Special cases: whitespace is deleted from blank lines; continuation
2499 lines are shifted by the same amount their initial line was shifted,
2500 in order to preserve their relative indentation with respect to their
2501 initial line; and comment lines beginning in column 1 are ignored."
2502 (interactive "*r\nP") ; region; raw prefix arg
2504 (goto-char end) (beginning-of-line) (setq end (point-marker))
2505 (goto-char start) (beginning-of-line)
2506 (let ((py-indent-offset (prefix-numeric-value
2507 (or indent-offset py-indent-offset)))
2508 (indents '(-1)) ; stack of active indent levels
2509 (target-column 0) ; column to which to indent
2510 (base-shifted-by 0) ; amount last base line was shifted
2511 (indent-base (if (looking-at "[ \t\n]")
2512 (py-compute-indentation t)
2515 (while (< (point) end)
2516 (setq ci (current-indentation))
2517 ;; figure out appropriate target column
2519 ((or (eq (following-char) ?#) ; comment in column 1
2520 (looking-at "[ \t]*$")) ; entirely blank
2521 (setq target-column 0))
2522 ((py-continuation-line-p) ; shift relative to base line
2523 (setq target-column (+ ci base-shifted-by)))
2525 (if (> ci (car indents)) ; going deeper; push it
2526 (setq indents (cons ci indents))
2527 ;; else we should have seen this indent before
2528 (setq indents (memq ci indents)) ; pop deeper indents
2530 (error "Bad indentation in region, at line %d"
2533 (1+ (count-lines 1 (point)))))))
2534 (setq target-column (+ indent-base
2536 (- (length indents) 2))))
2537 (setq base-shifted-by (- target-column ci))))
2539 (if (/= ci target-column)
2541 (delete-horizontal-space)
2542 (indent-to target-column)))
2544 (set-marker end nil))
2546 (defun py-comment-region (beg end &optional arg)
2547 "Like `comment-region' but uses double hash (`#') comment starter."
2548 (interactive "r\nP")
2549 (let ((comment-start py-block-comment-prefix))
2550 (comment-region beg end arg)))
2552 (defun py-join-words-wrapping (words separator line-prefix line-length)
2554 (current-line line-prefix))
2556 (let* ((word (car words))
2557 (maybe-line (concat current-line word separator)))
2558 (if (> (length maybe-line) line-length)
2559 (setq lines (cons (substring current-line 0 -1) lines)
2560 current-line (concat line-prefix word separator " "))
2561 (setq current-line (concat maybe-line " "))))
2562 (setq words (cdr words)))
2563 (setq lines (cons (substring
2564 current-line 0 (- 0 (length separator) 1)) lines))
2565 (mapconcat 'identity (nreverse lines) "\n")))
2567 (defun py-sort-imports ()
2568 "Sort multiline imports.
2569 Put point inside the parentheses of a multiline import and hit
2570 \\[py-sort-imports] to sort the imports lexicographically"
2573 (let ((open-paren (save-excursion (progn (up-list -1) (point))))
2574 (close-paren (save-excursion (progn (up-list 1) (point))))
2576 (goto-char (1+ open-paren))
2577 (skip-chars-forward " \n\t")
2578 (setq sorted-imports
2581 (split-string (buffer-substring
2583 (save-excursion (goto-char (1- close-paren))
2584 (skip-chars-backward " \n\t")
2587 ;; XXX Should this sort case insensitively?
2589 ;; Remove empty strings.
2590 (delete-region open-paren close-paren)
2591 (goto-char open-paren)
2593 (insert (py-join-words-wrapping (remove "" sorted-imports) "," " " 78))
2599 ;; Functions for moving point
2600 (defun py-previous-statement (count)
2601 "Go to the start of the COUNTth preceding Python statement.
2602 By default, goes to the previous statement. If there is no such
2603 statement, goes to the first statement. Return count of statements
2604 left to move. `Statements' do not include blank, comment, or
2605 continuation lines."
2606 (interactive "p") ; numeric prefix arg
2607 (if (< count 0) (py-next-statement (- count))
2608 (py-goto-initial-line)
2611 (setq start (point)) ; always true -- side effect
2613 (zerop (forward-line -1))
2614 (py-goto-statement-at-or-above))
2615 (setq count (1- count)))
2616 (if (> count 0) (goto-char start)))
2619 (defun py-next-statement (count)
2620 "Go to the start of next Python statement.
2621 If the statement at point is the i'th Python statement, goes to the
2622 start of statement i+COUNT. If there is no such statement, goes to the
2623 last statement. Returns count of statements left to move. `Statements'
2624 do not include blank, comment, or continuation lines."
2625 (interactive "p") ; numeric prefix arg
2626 (if (< count 0) (py-previous-statement (- count))
2630 (setq start (point)) ; always true -- side effect
2632 (py-goto-statement-below))
2633 (setq count (1- count)))
2634 (if (> count 0) (goto-char start)))
2637 (defun py-goto-block-up (&optional nomark)
2638 "Move up to start of current block.
2639 Go to the statement that starts the smallest enclosing block; roughly
2640 speaking, this will be the closest preceding statement that ends with a
2641 colon and is indented less than the statement you started on. If
2642 successful, also sets the mark to the starting point.
2644 `\\[py-mark-block]' can be used afterward to mark the whole code
2647 If called from a program, the mark will not be set if optional argument
2650 (let ((start (point))
2653 (py-goto-initial-line)
2654 ;; if on blank or non-indenting comment line, use the preceding stmt
2655 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2657 (py-goto-statement-at-or-above)
2658 (setq found (py-statement-opens-block-p))))
2659 ;; search back for colon line indented less
2660 (setq initial-indent (current-indentation))
2661 (if (zerop initial-indent)
2663 (goto-char (point-min)))
2664 (while (not (or found (bobp)))
2667 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2668 (or (py-goto-initial-line) t) ; always true -- side effect
2669 (< (current-indentation) initial-indent)
2670 (py-statement-opens-block-p))))
2673 (or nomark (push-mark start))
2674 (back-to-indentation))
2676 (error "Enclosing block not found"))))
2678 (defun py-beginning-of-def-or-class (&optional class count)
2679 "Move point to start of `def' or `class'.
2681 Searches back for the closest preceding `def'. If you supply a prefix
2682 arg, looks for a `class' instead. The docs below assume the `def'
2683 case; just substitute `class' for `def' for the other case.
2684 Programmatically, if CLASS is `either', then moves to either `class'
2687 When second optional argument is given programmatically, move to the
2688 COUNTth start of `def'.
2690 If point is in a `def' statement already, and after the `d', simply
2691 moves point to the start of the statement.
2693 Otherwise (i.e. when point is not in a `def' statement, or at or
2694 before the `d' of a `def' statement), searches for the closest
2695 preceding `def' statement, and leaves point at its start. If no such
2696 statement can be found, leaves point at the start of the buffer.
2698 Returns t iff a `def' statement is found by these rules.
2700 Note that doing this command repeatedly will take you closer to the
2701 start of the buffer each time.
2703 To mark the current `def', see `\\[py-mark-def-or-class]'."
2704 (interactive "P") ; raw prefix arg
2705 (setq count (or count 1))
2706 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2707 (start-of-line (goto-char (py-point 'bol)))
2708 (start-of-stmt (goto-char (py-point 'bos)))
2709 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2710 (class "^[ \t]*class\\>")
2711 (t "^[ \t]*def\\>")))
2713 ;; searching backward
2714 (if (and (< 0 count)
2715 (or (/= start-of-stmt start-of-line)
2716 (not at-or-before-p)))
2719 (if (and (> 0 count)
2720 (zerop (current-column))
2721 (looking-at start-re))
2723 (if (re-search-backward start-re nil 'move count)
2724 (goto-char (match-beginning 0)))))
2726 ;; Backwards compatibility
2727 (defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
2729 (defun py-end-of-def-or-class (&optional class count)
2730 "Move point beyond end of `def' or `class' body.
2732 By default, looks for an appropriate `def'. If you supply a prefix
2733 arg, looks for a `class' instead. The docs below assume the `def'
2734 case; just substitute `class' for `def' for the other case.
2735 Programmatically, if CLASS is `either', then moves to either `class'
2738 When second optional argument is given programmatically, move to the
2739 COUNTth end of `def'.
2741 If point is in a `def' statement already, this is the `def' we use.
2743 Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2744 contains the statement you started on, that's the `def' we use.
2746 Otherwise, we search forward for the closest following `def', and use that.
2748 If a `def' can be found by these rules, point is moved to the start of
2749 the line immediately following the `def' block, and the position of the
2750 start of the `def' is returned.
2752 Else point is moved to the end of the buffer, and nil is returned.
2754 Note that doing this command repeatedly will take you closer to the
2755 end of the buffer each time.
2757 To mark the current `def', see `\\[py-mark-def-or-class]'."
2758 (interactive "P") ; raw prefix arg
2759 (if (and count (/= count 1))
2760 (py-beginning-of-def-or-class (- 1 count)))
2761 (let ((start (progn (py-goto-initial-line) (point)))
2762 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2766 ;; move point to start of appropriate def/class
2767 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2768 (setq state 'at-beginning)
2769 ;; else see if py-beginning-of-def-or-class hits container
2770 (if (and (py-beginning-of-def-or-class class)
2771 (progn (py-goto-beyond-block)
2773 (setq state 'at-end)
2774 ;; else search forward
2776 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2777 (progn (setq state 'at-beginning)
2778 (beginning-of-line)))))
2780 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2781 ((eq state 'at-end) t)
2782 ((eq state 'not-found) nil)
2783 (t (error "Internal error in `py-end-of-def-or-class'")))))
2785 ;; Backwards compabitility
2786 (defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
2789 ;; Functions for marking regions
2790 (defun py-mark-block (&optional extend just-move)
2791 "Mark following block of lines. With prefix arg, mark structure.
2792 Easier to use than explain. It sets the region to an `interesting'
2793 block of succeeding lines. If point is on a blank line, it goes down to
2794 the next non-blank line. That will be the start of the region. The end
2795 of the region depends on the kind of line at the start:
2797 - If a comment, the region will include all succeeding comment lines up
2798 to (but not including) the next non-comment line (if any).
2800 - Else if a prefix arg is given, and the line begins one of these
2803 if elif else try except finally for while def class
2805 the region will be set to the body of the structure, including
2806 following blocks that `belong' to it, but excluding trailing blank
2807 and comment lines. E.g., if on a `try' statement, the `try' block
2808 and all (if any) of the following `except' and `finally' blocks
2809 that belong to the `try' structure will be in the region. Ditto
2810 for if/elif/else, for/else and while/else structures, and (a bit
2811 degenerate, since they're always one-block structures) def and
2814 - Else if no prefix argument is given, and the line begins a Python
2815 block (see list above), and the block is not a `one-liner' (i.e.,
2816 the statement ends with a colon, not with code), the region will
2817 include all succeeding lines up to (but not including) the next
2818 code statement (if any) that's indented no more than the starting
2819 line, except that trailing blank and comment lines are excluded.
2820 E.g., if the starting line begins a multi-statement `def'
2821 structure, the region will be set to the full function definition,
2822 but without any trailing `noise' lines.
2824 - Else the region will include all succeeding lines up to (but not
2825 including) the next blank line, or code or indenting-comment line
2826 indented strictly less than the starting line. Trailing indenting
2827 comment lines are included in this case, but not trailing blank
2830 A msg identifying the location of the mark is displayed in the echo
2831 area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2833 If called from a program, optional argument EXTEND plays the role of
2834 the prefix arg, and if optional argument JUST-MOVE is not nil, just
2835 moves to the end of the block (& does not set mark or display a msg)."
2836 (interactive "P") ; raw prefix arg
2837 (py-goto-initial-line)
2838 ;; skip over blank lines
2840 (looking-at "[ \t]*$") ; while blank line
2841 (not (eobp))) ; & somewhere to go
2844 (error "Hit end of buffer without finding a non-blank stmt"))
2845 (let ((initial-pos (point))
2846 (initial-indent (current-indentation))
2847 last-pos ; position of last stmt in region
2849 '((if elif else) (elif elif else) (else)
2850 (try except finally) (except except) (finally)
2851 (for else) (while else)
2853 first-symbol next-symbol)
2856 ;; if comment line, suck up the following comment lines
2857 ((looking-at "[ \t]*#")
2858 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2859 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2860 (setq last-pos (point)))
2862 ;; else if line is a block line and EXTEND given, suck up
2863 ;; the whole structure
2865 (setq first-symbol (py-suck-up-first-keyword) )
2866 (assq first-symbol followers))
2868 (or (py-goto-beyond-block) t) ; side effect
2869 (forward-line -1) ; side effect
2870 (setq last-pos (point)) ; side effect
2871 (py-goto-statement-below)
2872 (= (current-indentation) initial-indent)
2873 (setq next-symbol (py-suck-up-first-keyword))
2874 (memq next-symbol (cdr (assq first-symbol followers))))
2875 (setq first-symbol next-symbol)))
2877 ;; else if line *opens* a block, search for next stmt indented <=
2878 ((py-statement-opens-block-p)
2880 (setq last-pos (point)) ; always true -- side effect
2881 (py-goto-statement-below)
2882 (> (current-indentation) initial-indent)
2885 ;; else plain code line; stop at next blank line, or stmt or
2886 ;; indenting comment line indented <
2889 (setq last-pos (point)) ; always true -- side effect
2890 (or (py-goto-beyond-final-line) t)
2891 (not (looking-at "[ \t]*$")) ; stop at blank line
2893 (>= (current-indentation) initial-indent)
2894 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2897 ;; skip to end of last stmt
2898 (goto-char last-pos)
2899 (py-goto-beyond-final-line)
2901 ;; set mark & display
2904 (push-mark (point) 'no-msg)
2906 (message "Mark set after: %s" (py-suck-up-leading-text))
2907 (goto-char initial-pos))))
2909 (defun py-mark-def-or-class (&optional class)
2910 "Set region to body of def (or class, with prefix arg) enclosing point.
2911 Pushes the current mark, then point, on the mark ring (all language
2912 modes do this, but although it's handy it's never documented ...).
2914 In most Emacs language modes, this function bears at least a
2915 hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2916 `\\[py-beginning-of-def-or-class]'.
2918 And in earlier versions of Python mode, all 3 were tightly connected.
2919 Turned out that was more confusing than useful: the `goto start' and
2920 `goto end' commands are usually used to search through a file, and
2921 people expect them to act a lot like `search backward' and `search
2922 forward' string-search commands. But because Python `def' and `class'
2923 can nest to arbitrary levels, finding the smallest def containing
2924 point cannot be done via a simple backward search: the def containing
2925 point may not be the closest preceding def, or even the closest
2926 preceding def that's indented less. The fancy algorithm required is
2927 appropriate for the usual uses of this `mark' command, but not for the
2930 So the def marked by this command may not be the one either of the
2931 `goto' commands find: If point is on a blank or non-indenting comment
2932 line, moves back to start of the closest preceding code statement or
2933 indenting comment line. If this is a `def' statement, that's the def
2934 we use. Else searches for the smallest enclosing `def' block and uses
2935 that. Else signals an error.
2937 When an enclosing def is found: The mark is left immediately beyond
2938 the last line of the def block. Point is left at the start of the
2939 def, except that: if the def is preceded by a number of comment lines
2940 followed by (at most) one optional blank line, point is left at the
2941 start of the comments; else if the def is preceded by a blank line,
2942 point is left at its start.
2944 The intent is to mark the containing def/class and its associated
2945 documentation, to make moving and duplicating functions and classes
2947 (interactive "P") ; raw prefix arg
2948 (let ((start (point))
2949 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2953 (if (not (py-go-up-tree-to-keyword which))
2954 (progn (goto-char start)
2955 (error "Enclosing %s not found"
2956 (if (eq class 'either)
2959 ;; else enclosing def/class found
2960 (setq start (point))
2961 (py-goto-beyond-block)
2964 (if (zerop (forward-line -1)) ; if there is a preceding line
2966 (if (looking-at "[ \t]*$") ; it's blank
2967 (setq start (point)) ; so reset start point
2968 (goto-char start)) ; else try again
2969 (if (zerop (forward-line -1))
2970 (if (looking-at "[ \t]*#") ; a comment
2971 ;; look back for non-comment line
2972 ;; tricky: note that the regexp matches a blank
2973 ;; line, cuz \n is in the 2nd character class
2975 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2977 ;; no comment, so go back
2978 (goto-char start)))))))
2979 (exchange-point-and-mark)
2980 (py-keep-region-active))
2982 ;; ripped from cc-mode
2983 (defun py-forward-into-nomenclature (&optional arg)
2984 "Move forward to end of a nomenclature section or word.
2985 With \\[universal-argument] (programmatically, optional argument ARG),
2986 do it that many times.
2988 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2990 (let ((case-fold-search nil))
2993 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2995 (while (and (< arg 0)
2997 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
3000 (setq arg (1+ arg)))))
3001 (py-keep-region-active))
3003 (defun py-backward-into-nomenclature (&optional arg)
3004 "Move backward to beginning of a nomenclature section or word.
3005 With optional ARG, move that many times. If ARG is negative, move
3008 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
3010 (py-forward-into-nomenclature (- arg))
3011 (py-keep-region-active))
3015 ;; pdbtrack functions
3016 (defun py-pdbtrack-toggle-stack-tracking (arg)
3018 (if (not (get-buffer-process (current-buffer)))
3019 (error "No process associated with buffer '%s'" (current-buffer)))
3020 ;; missing or 0 is toggle, >0 turn on, <0 turn off
3022 (zerop (setq arg (prefix-numeric-value arg))))
3023 (setq py-pdbtrack-do-tracking-p (not py-pdbtrack-do-tracking-p))
3024 (setq py-pdbtrack-do-tracking-p (> arg 0)))
3025 (message "%sabled Python's pdbtrack"
3026 (if py-pdbtrack-do-tracking-p "En" "Dis")))
3028 (defun turn-on-pdbtrack ()
3030 (py-pdbtrack-toggle-stack-tracking 1))
3032 (defun turn-off-pdbtrack ()
3034 (py-pdbtrack-toggle-stack-tracking 0))
3040 ;; hack for FSF Emacs
3041 (unless (fboundp 'read-shell-command)
3042 (defalias 'read-shell-command 'read-string))
3044 (defun py-pychecker-run (command)
3045 "*Run pychecker (default on the file currently visited)."
3048 (format "%s %s %s" py-pychecker-command
3049 (mapconcat 'identity py-pychecker-command-args " ")
3050 (buffer-file-name)))
3051 (last (when py-pychecker-history
3052 (let* ((lastcmd (car py-pychecker-history))
3053 (cmd (cdr (reverse (split-string lastcmd))))
3054 (newcmd (reverse (cons (buffer-file-name) cmd))))
3055 (mapconcat 'identity newcmd " ")))))
3058 (if (fboundp 'read-shell-command)
3059 (read-shell-command "Run pychecker like this: "
3063 'py-pychecker-history)
3064 (read-string "Run pychecker like this: "
3068 'py-pychecker-history))
3070 (save-some-buffers (not py-ask-about-save) nil)
3071 (if (fboundp 'compilation-start)
3073 (compilation-start command)
3075 (compile-internal command "No more errors")))
3079 ;; pydoc commands. The guts of this function is stolen from XEmacs's
3080 ;; symbol-near-point, but without the useless regexp-quote call on the
3081 ;; results, nor the interactive bit. Also, we've added the temporary
3082 ;; syntax table setting, which Skip originally had broken out into a
3083 ;; separate function. Note that Emacs doesn't have the original
3085 (defun py-symbol-near-point ()
3086 "Return the first textual item to the nearest point."
3087 ;; alg stolen from etag.el
3089 (with-syntax-table py-dotted-expression-syntax-table
3090 (if (or (bobp) (not (memq (char-syntax (char-before)) '(?w ?_))))
3091 (while (not (looking-at "\\sw\\|\\s_\\|\\'"))
3093 (while (looking-at "\\sw\\|\\s_")
3095 (if (re-search-backward "\\sw\\|\\s_" nil t)
3096 (progn (forward-char 1)
3097 (buffer-substring (point)
3098 (progn (forward-sexp -1)
3099 (while (looking-at "\\s'")
3104 (defun py-help-at-point ()
3105 "Get help from Python based on the symbol nearest point."
3107 (let* ((sym (py-symbol-near-point))
3108 (base (substring sym 0 (or (search "." sym :from-end t) 0)))
3110 (if (not (equal base ""))
3111 (setq cmd (concat "import " base "\n")))
3112 (setq cmd (concat "import pydoc\n"
3114 "try: pydoc.help('" sym "')\n"
3115 "except: print 'No help available on:', \"" sym "\""))
3117 (py-execute-string cmd)
3118 (set-buffer "*Python Output*")
3119 ;; BAW: Should we really be leaving the output buffer in help-mode?
3124 ;; Documentation functions
3126 ;; dump the long form of the mode blurb; does the usual doc escapes,
3127 ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
3128 ;; out of the right places, along with the keys they're on & current
3130 (defun py-dump-help-string (str)
3131 (with-output-to-temp-buffer "*Help*"
3132 (let ((locals (buffer-local-variables))
3133 funckind funcname func funcdoc
3134 (start 0) mstart end
3136 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
3137 (setq mstart (match-beginning 0) end (match-end 0)
3138 funckind (substring str (match-beginning 1) (match-end 1))
3139 funcname (substring str (match-beginning 2) (match-end 2))
3140 func (intern funcname))
3141 (princ (substitute-command-keys (substring str start mstart)))
3143 ((equal funckind "c") ; command
3144 (setq funcdoc (documentation func)
3147 (mapconcat 'key-description
3148 (where-is-internal func py-mode-map)
3150 ((equal funckind "v") ; variable
3151 (setq funcdoc (documentation-property func 'variable-documentation)
3152 keys (if (assq func locals)
3154 "Local/Global values: "
3155 (prin1-to-string (symbol-value func))
3157 (prin1-to-string (default-value func)))
3160 (prin1-to-string (symbol-value func))))))
3162 (error "Error in py-dump-help-string, tag `%s'" funckind)))
3163 (princ (format "\n-> %s:\t%s\t%s\n\n"
3164 (if (equal funckind "c") "Command" "Variable")
3169 (princ (substitute-command-keys (substring str start))))
3170 (print-help-return-message)))
3172 (defun py-describe-mode ()
3173 "Dump long form of Python-mode docs."
3175 (py-dump-help-string "Major mode for editing Python files.
3176 Knows about Python indentation, tokens, comments and continuation lines.
3177 Paragraphs are separated by blank lines only.
3179 Major sections below begin with the string `@'; specific function and
3180 variable docs begin with `->'.
3182 @EXECUTING PYTHON CODE
3184 \\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
3185 \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
3186 \\[py-execute-region]\tsends the current region
3187 \\[py-execute-def-or-class]\tsends the current function or class definition
3188 \\[py-execute-string]\tsends an arbitrary string
3189 \\[py-shell]\tstarts a Python interpreter window; this will be used by
3190 \tsubsequent Python execution commands
3191 %c:py-execute-import-or-reload
3192 %c:py-execute-buffer
3193 %c:py-execute-region
3194 %c:py-execute-def-or-class
3195 %c:py-execute-string
3200 py-indent-offset\tindentation increment
3201 py-block-comment-prefix\tcomment string used by comment-region
3203 py-python-command\tshell command to invoke Python interpreter
3204 py-temp-directory\tdirectory used for temp files (if needed)
3206 py-beep-if-tab-change\tring the bell if tab-width is changed
3208 %v:py-block-comment-prefix
3209 %v:py-python-command
3210 %v:py-temp-directory
3211 %v:py-beep-if-tab-change
3215 Each physical line in the file is either a `continuation line' (the
3216 preceding line ends with a backslash that's not part of a comment, or
3217 the paren/bracket/brace nesting level at the start of the line is
3218 non-zero, or both) or an `initial line' (everything else).
3220 An initial line is in turn a `blank line' (contains nothing except
3221 possibly blanks or tabs), a `comment line' (leftmost non-blank
3222 character is `#'), or a `code line' (everything else).
3226 Although all comment lines are treated alike by Python, Python mode
3227 recognizes two kinds that act differently with respect to indentation.
3229 An `indenting comment line' is a comment line with a blank, tab or
3230 nothing after the initial `#'. The indentation commands (see below)
3231 treat these exactly as if they were code lines: a line following an
3232 indenting comment line will be indented like the comment line. All
3233 other comment lines (those with a non-whitespace character immediately
3234 following the initial `#') are `non-indenting comment lines', and
3235 their indentation is ignored by the indentation commands.
3237 Indenting comment lines are by far the usual case, and should be used
3238 whenever possible. Non-indenting comment lines are useful in cases
3241 \ta = b # a very wordy single-line comment that ends up being
3242 \t #... continued onto another line
3245 ##\t\tprint 'panic!' # old code we've `commented out'
3248 Since the `#...' and `##' comment lines have a non-whitespace
3249 character following the initial `#', Python mode ignores them when
3250 computing the proper indentation for the next line.
3252 Continuation Lines and Statements
3254 The Python-mode commands generally work on statements instead of on
3255 individual lines, where a `statement' is a comment or blank line, or a
3256 code line and all of its following continuation lines (if any)
3257 considered as a single logical unit. The commands in this mode
3258 generally (when it makes sense) automatically move to the start of the
3259 statement containing point, even if point happens to be in the middle
3260 of some continuation line.
3265 Primarily for entering new code:
3266 \t\\[indent-for-tab-command]\t indent line appropriately
3267 \t\\[py-newline-and-indent]\t insert newline, then indent
3268 \t\\[py-electric-backspace]\t reduce indentation, or delete single character
3270 Primarily for reindenting existing code:
3271 \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
3272 \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
3274 \t\\[py-indent-region]\t reindent region to match its context
3275 \t\\[py-shift-region-left]\t shift region left by py-indent-offset
3276 \t\\[py-shift-region-right]\t shift region right by py-indent-offset
3278 Unlike most programming languages, Python uses indentation, and only
3279 indentation, to specify block structure. Hence the indentation supplied
3280 automatically by Python-mode is just an educated guess: only you know
3281 the block structure you intend, so only you can supply correct
3284 The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
3285 the indentation of preceding statements. E.g., assuming
3286 py-indent-offset is 4, after you enter
3287 \tif a > 0: \\[py-newline-and-indent]
3288 the cursor will be moved to the position of the `_' (_ is not a
3289 character in the file, it's just used here to indicate the location of
3293 If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
3298 Python-mode cannot know whether that's what you intended, or whether
3302 was your intent. In general, Python-mode either reproduces the
3303 indentation of the (closest code or indenting-comment) preceding
3304 statement, or adds an extra py-indent-offset blanks if the preceding
3305 statement has `:' as its last significant (non-whitespace and non-
3306 comment) character. If the suggested indentation is too much, use
3307 \\[py-electric-backspace] to reduce it.
3309 Continuation lines are given extra indentation. If you don't like the
3310 suggested indentation, change it to something you do like, and Python-
3311 mode will strive to indent later lines of the statement in the same way.
3313 If a line is a continuation line by virtue of being in an unclosed
3314 paren/bracket/brace structure (`list', for short), the suggested
3315 indentation depends on whether the current line contains the first item
3316 in the list. If it does, it's indented py-indent-offset columns beyond
3317 the indentation of the line containing the open bracket. If you don't
3318 like that, change it by hand. The remaining items in the list will mimic
3319 whatever indentation you give to the first item.
3321 If a line is a continuation line because the line preceding it ends with
3322 a backslash, the third and following lines of the statement inherit their
3323 indentation from the line preceding them. The indentation of the second
3324 line in the statement depends on the form of the first (base) line: if
3325 the base line is an assignment statement with anything more interesting
3326 than the backslash following the leftmost assigning `=', the second line
3327 is indented two columns beyond that `='. Else it's indented to two
3328 columns beyond the leftmost solid chunk of non-whitespace characters on
3331 Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
3332 repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
3333 structure you intend.
3334 %c:indent-for-tab-command
3335 %c:py-newline-and-indent
3336 %c:py-electric-backspace
3339 The next function may be handy when editing code you didn't write:
3340 %c:py-guess-indent-offset
3343 The remaining `indent' functions apply to a region of Python code. They
3344 assume the block structure (equals indentation, in Python) of the region
3345 is correct, and alter the indentation in various ways while preserving
3346 the block structure:
3348 %c:py-shift-region-left
3349 %c:py-shift-region-right
3351 @MARKING & MANIPULATING REGIONS OF CODE
3353 \\[py-mark-block]\t mark block of lines
3354 \\[py-mark-def-or-class]\t mark smallest enclosing def
3355 \\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
3356 \\[comment-region]\t comment out region of code
3357 \\[universal-argument] \\[comment-region]\t uncomment region of code
3359 %c:py-mark-def-or-class
3364 \\[py-previous-statement]\t move to statement preceding point
3365 \\[py-next-statement]\t move to statement following point
3366 \\[py-goto-block-up]\t move up to start of current block
3367 \\[py-beginning-of-def-or-class]\t move to start of def
3368 \\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
3369 \\[py-end-of-def-or-class]\t move to end of def
3370 \\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
3372 The first two move to one statement beyond the statement that contains
3373 point. A numeric prefix argument tells them to move that many
3374 statements instead. Blank lines, comment lines, and continuation lines
3375 do not count as `statements' for these commands. So, e.g., you can go
3376 to the first code statement in a file by entering
3377 \t\\[beginning-of-buffer]\t to move to the top of the file
3378 \t\\[py-next-statement]\t to skip over initial comments and blank lines
3379 Or do `\\[py-previous-statement]' with a huge prefix argument.
3380 %c:py-previous-statement
3381 %c:py-next-statement
3383 %c:py-beginning-of-def-or-class
3384 %c:py-end-of-def-or-class
3386 @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
3388 `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
3390 `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
3391 overall class and def structure of a module.
3393 `\\[back-to-indentation]' moves point to a line's first non-blank character.
3395 `\\[indent-relative]' is handy for creating odd indentation.
3399 If you don't like the default value of a variable, change its value to
3400 whatever you do like by putting a `setq' line in your .emacs file.
3401 E.g., to set the indentation increment to 4, put this line in your
3403 \t(setq py-indent-offset 4)
3404 To see the value of a variable, do `\\[describe-variable]' and enter the variable
3407 When entering a key sequence like `C-c C-n', it is not necessary to
3408 release the CONTROL key after doing the `C-c' part -- it suffices to
3409 press the CONTROL key, press and release `c' (while still holding down
3410 CONTROL), press and release `n' (while still holding down CONTROL), &
3411 then release CONTROL.
3413 Entering Python mode calls with no arguments the value of the variable
3414 `python-mode-hook', if that value exists and is not nil; for backward
3415 compatibility it also tries `py-mode-hook'; see the `Hooks' section of
3416 the Elisp manual for details.
3418 Obscure: When python-mode is first loaded, it looks for all bindings
3419 to newline-and-indent in the global keymap, and shadows them with
3420 local bindings to py-newline-and-indent."))
3422 (require 'info-look)
3423 ;; The info-look package does not always provide this function (it
3424 ;; appears this is the case with XEmacs 21.1)
3425 (when (fboundp 'info-lookup-maybe-add-help)
3426 (info-lookup-maybe-add-help
3428 :regexp "[a-zA-Z0-9_]+"
3429 :doc-spec '(("(python-lib)Module Index")
3430 ("(python-lib)Class-Exception-Object Index")
3431 ("(python-lib)Function-Method-Variable Index")
3432 ("(python-lib)Miscellaneous Index")))
3437 (defvar py-parse-state-re
3439 "^[ \t]*\\(elif\\|else\\|while\\|def\\|class\\)\\>"
3443 (defun py-parse-state ()
3444 "Return the parse state at point (see `parse-partial-sexp' docs)."
3446 (let ((here (point))
3449 ;; back up to the first preceding line (if any; else start of
3450 ;; buffer) that begins with a popular Python keyword, or a
3451 ;; non- whitespace and non-comment character. These are good
3452 ;; places to start parsing to see whether where we started is
3453 ;; at a non-zero nesting level. It may be slow for people who
3454 ;; write huge code blocks or huge lists ... tough beans.
3455 (re-search-backward py-parse-state-re nil 'move)
3457 ;; In XEmacs, we have a much better way to test for whether
3458 ;; we're in a triple-quoted string or not. Emacs does not
3459 ;; have this built-in function, which is its loss because
3460 ;; without scanning from the beginning of the buffer, there's
3461 ;; no accurate way to determine this otherwise.
3462 (save-excursion (setq pps (parse-partial-sexp (point) here)))
3463 ;; make sure we don't land inside a triple-quoted string
3464 (setq done (or (not (nth 3 pps))
3466 ;; Just go ahead and short circuit the test back to the
3467 ;; beginning of the buffer. This will be slow, but not
3468 ;; nearly as slow as looping through many
3469 ;; re-search-backwards.
3471 (goto-char (point-min))))
3474 (defun py-nesting-level ()
3475 "Return the buffer position of the last unclosed enclosing list.
3476 If nesting level is zero, return nil."
3477 (let ((status (py-parse-state)))
3478 (if (zerop (car status))
3480 (car (cdr status))))) ; char# of open bracket
3482 (defun py-backslash-continuation-line-p ()
3483 "Return t iff preceding line ends with backslash that is not in a comment."
3487 ;; use a cheap test first to avoid the regexp if possible
3488 ;; use 'eq' because char-after may return nil
3489 (eq (char-after (- (point) 2)) ?\\ )
3490 ;; make sure; since eq test passed, there is a preceding line
3491 (forward-line -1) ; always true -- side effect
3492 (looking-at py-continued-re))))
3494 (defun py-continuation-line-p ()
3495 "Return t iff current line is a continuation line."
3498 (or (py-backslash-continuation-line-p)
3499 (py-nesting-level))))
3501 (defun py-goto-beginning-of-tqs (delim)
3502 "Go to the beginning of the triple quoted string we find ourselves in.
3503 DELIM is the TQS string delimiter character we're searching backwards
3505 (let ((skip (and delim (make-string 1 delim)))
3510 (py-safe (search-backward skip))
3511 (setq continue (and (not (bobp))
3512 (= (char-before) ?\\))))
3513 (if (and (= (char-before) delim)
3514 (= (char-before (1- (point))) delim))
3515 (setq skip (make-string 3 delim))))
3516 ;; we're looking at a triple-quoted string
3517 (py-safe (search-backward skip)))))
3519 (defun py-goto-initial-line ()
3520 "Go to the initial line of the current statement.
3521 Usually this is the line we're on, but if we're on the 2nd or
3522 following lines of a continuation block, we need to go up to the first
3524 ;; Tricky: We want to avoid quadratic-time behavior for long
3525 ;; continued blocks, whether of the backslash or open-bracket
3526 ;; varieties, or a mix of the two. The following manages to do that
3527 ;; in the usual cases.
3529 ;; Also, if we're sitting inside a triple quoted string, this will
3530 ;; drop us at the line that begins the string.
3531 (let (open-bracket-pos)
3532 (while (py-continuation-line-p)
3534 (if (py-backslash-continuation-line-p)
3535 (while (py-backslash-continuation-line-p)
3537 ;; else zip out of nested brackets/braces/parens
3538 (while (setq open-bracket-pos (py-nesting-level))
3539 (goto-char open-bracket-pos)))))
3540 (beginning-of-line))
3542 (defun py-goto-beyond-final-line ()
3543 "Go to the point just beyond the fine line of the current statement.
3544 Usually this is the start of the next line, but if this is a
3545 multi-line statement we need to skip over the continuation lines."
3546 ;; Tricky: Again we need to be clever to avoid quadratic time
3549 ;; XXX: Not quite the right solution, but deals with multi-line doc
3551 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
3552 (goto-char (match-end 0)))
3556 (while (and (py-continuation-line-p)
3558 ;; skip over the backslash flavor
3559 (while (and (py-backslash-continuation-line-p)
3562 ;; if in nest, zip to the end of the nest
3563 (setq state (py-parse-state))
3564 (if (and (not (zerop (car state)))
3567 (parse-partial-sexp (point) (point-max) 0 nil state)
3568 (forward-line 1))))))
3570 (defun py-statement-opens-block-p ()
3571 "Return t iff the current statement opens a block.
3572 I.e., iff it ends with a colon that is not in a comment. Point should
3573 be at the start of a statement."
3575 (let ((start (point))
3576 (finish (progn (py-goto-beyond-final-line) (1- (point))))
3582 ;; look for a colon with nothing after it except whitespace, and
3584 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
3586 (if (eq (point) finish) ; note: no `else' clause; just
3587 ; keep searching if we're not at
3589 ;; sure looks like it opens a block -- but it might
3592 (setq searching nil) ; search is done either way
3593 (setq state (parse-partial-sexp start
3594 (match-beginning 0)))
3595 (setq answer (not (nth 4 state)))))
3596 ;; search failed: couldn't find another interesting colon
3597 (setq searching nil)))
3600 (defun py-statement-closes-block-p ()
3601 "Return t iff the current statement closes a block.
3602 I.e., if the line starts with `return', `raise', `break', `continue',
3603 and `pass'. This doesn't catch embedded statements."
3604 (let ((here (point)))
3605 (py-goto-initial-line)
3606 (back-to-indentation)
3608 (looking-at (concat py-block-closing-keywords-re "\\>"))
3611 (defun py-goto-beyond-block ()
3612 "Go to point just beyond the final line of block begun by the current line.
3613 This is the same as where `py-goto-beyond-final-line' goes unless
3614 we're on colon line, in which case we go to the end of the block.
3615 Assumes point is at the beginning of the line."
3616 (if (py-statement-opens-block-p)
3617 (py-mark-block nil 'just-move)
3618 (py-goto-beyond-final-line)))
3620 (defun py-goto-statement-at-or-above ()
3621 "Go to the start of the first statement at or preceding point.
3622 Return t if there is such a statement, otherwise nil. `Statement'
3623 does not include blank lines, comments, or continuation lines."
3624 (py-goto-initial-line)
3625 (if (looking-at py-blank-or-comment-re)
3626 ;; skip back over blank & comment lines
3627 ;; note: will skip a blank or comment line that happens to be
3628 ;; a continuation line too
3629 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
3630 (progn (py-goto-initial-line) t)
3634 (defun py-goto-statement-below ()
3635 "Go to start of the first statement following the statement containing point.
3636 Return t if there is such a statement, otherwise nil. `Statement'
3637 does not include blank lines, comments, or continuation lines."
3639 (let ((start (point)))
3640 (py-goto-beyond-final-line)
3642 (or (looking-at py-blank-or-comment-re)
3647 (progn (goto-char start) nil)
3650 (defun py-go-up-tree-to-keyword (key)
3651 "Go to begining of statement starting with KEY, at or preceding point.
3653 KEY is a regular expression describing a Python keyword. Skip blank
3654 lines and non-indenting comments. If the statement found starts with
3655 KEY, then stop, otherwise go back to first enclosing block starting
3656 with KEY. If successful, leave point at the start of the KEY line and
3657 return t. Otherwise, leave point at an undefined place and return nil."
3658 ;; skip blanks and non-indenting #
3659 (py-goto-initial-line)
3661 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3662 (zerop (forward-line -1))) ; go back
3664 (py-goto-initial-line)
3665 (let* ((re (concat "[ \t]*" key "\\>"))
3666 (case-fold-search nil) ; let* so looking-at sees this
3667 (found (looking-at re))
3669 (while (not (or found dead))
3670 (condition-case nil ; in case no enclosing block
3671 (py-goto-block-up 'no-mark)
3672 (error (setq dead t)))
3673 (or dead (setq found (looking-at re))))
3677 (defun py-suck-up-leading-text ()
3678 "Return string in buffer from start of indentation to end of line.
3679 Prefix with \"...\" if leading whitespace was skipped."
3681 (back-to-indentation)
3683 (if (bolp) "" "...")
3684 (buffer-substring (point) (progn (end-of-line) (point))))))
3686 (defun py-suck-up-first-keyword ()
3687 "Return first keyword on the line as a Lisp symbol.
3688 `Keyword' is defined (essentially) as the regular expression
3689 ([a-z]+). Returns nil if none was found."
3690 (let ((case-fold-search nil))
3691 (if (looking-at "[ \t]*\\([a-z]+\\)\\>")
3692 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3695 (defun py-current-defun ()
3696 "Python value for `add-log-current-defun-function'.
3697 This tells add-log.el how to find the current function/method/variable."
3700 ;; Move back to start of the current statement.
3702 (py-goto-initial-line)
3703 (back-to-indentation)
3704 (while (and (or (looking-at py-blank-or-comment-re)
3707 (backward-to-indentation 1))
3708 (py-goto-initial-line)
3714 ;; Check for an assignment. If this assignment exists inside a
3715 ;; def, it will be overwritten inside the while loop. If it
3716 ;; exists at top lever or inside a class, it will be preserved.
3718 (when (looking-at "[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*=")
3719 (setq scopes (buffer-substring (match-beginning 1) (match-end 1)))
3723 ;; Prepend the name of each outer socpe (def or class).
3726 (if (and (py-go-up-tree-to-keyword "\\(class\\|def\\)")
3728 "[ \t]*\\(class\\|def\\)[ \t]*\\([a-zA-Z0-9_]+\\)[ \t]*"))
3729 (let ((name (buffer-substring (match-beginning 2) (match-end 2))))
3730 (if (and assignment (looking-at "[ \t]*def"))
3732 (setq scopes (concat name sep scopes))
3734 (setq assignment nil)
3735 (condition-case nil ; Terminate nicely at top level.
3736 (py-goto-block-up 'no-mark)
3737 (error (setq dead t))))
3738 (if (string= scopes "")
3744 (defconst py-help-address "python-mode@python.org"
3745 "Address accepting submission of bug reports.")
3747 (defun py-version ()
3748 "Echo the current version of `python-mode' in the minibuffer."
3750 (message "Using `python-mode' version %s" py-version)
3751 (py-keep-region-active))
3753 ;; only works under Emacs 19
3755 ; (require 'reporter))
3757 (defun py-submit-bug-report (enhancement-p)
3758 "Submit via mail a bug report on `python-mode'.
3759 With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3760 non-nil) just submit an enhancement request."
3762 (list (not (y-or-n-p
3763 "Is this a bug report (hit `n' to send other comments)? "))))
3764 (let ((reporter-prompt-for-summary-p (if enhancement-p
3765 "(Very) brief summary: "
3768 (reporter-submit-bug-report
3769 py-help-address ;address
3770 (concat "python-mode " py-version) ;pkgname
3772 (if enhancement-p nil
3775 py-block-comment-prefix
3777 py-beep-if-tab-change))
3780 "Dear Barry,") ;salutation
3781 (if enhancement-p nil
3784 "Please replace this text with a sufficiently large code sample\n\
3785 and an exact recipe so that I can reproduce your problem. Failure\n\
3786 to do so may mean a greater delay in fixing your bug.\n\n")
3787 (exchange-point-and-mark)
3788 (py-keep-region-active))))
3791 (defun py-kill-emacs-hook ()
3792 "Delete files in `py-file-queue'.
3793 These are Python temporary files awaiting execution."
3794 (mapc #'(lambda (filename)
3795 (py-safe (delete-file filename)))
3798 ;; arrange to kill temp files when Emacs exists
3799 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
3800 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
3802 ;; Add a designator to the minor mode strings
3803 (or (assq 'py-pdbtrack-is-tracking-p minor-mode-alist)
3804 (push '(py-pdbtrack-is-tracking-p py-pdbtrack-minor-mode-string)
3809 ;;; paragraph and string filling code from Bernhard Herzog
3810 ;;; see http://mail.python.org/pipermail/python-list/2002-May/103189.html
3812 (defun py-fill-comment (&optional justify)
3813 "Fill the comment paragraph around point"
3814 (let (;; Non-nil if the current line contains a comment.
3817 ;; If has-comment, the appropriate fill-prefix for the comment.
3818 comment-fill-prefix)
3820 ;; Figure out what kind of comment we are looking at.
3824 ;; A line with nothing but a comment on it?
3825 ((looking-at "[ \t]*#[# \t]*")
3827 comment-fill-prefix (buffer-substring (match-beginning 0)
3830 ;; A line with some code, followed by a comment? Remember that the hash
3831 ;; which starts the comment shouldn't be part of a string or character.
3833 (while (not (looking-at "#\\|$"))
3834 (skip-chars-forward "^#\n\"'\\")
3836 ((eq (char-after (point)) ?\\) (forward-char 2))
3837 ((memq (char-after (point)) '(?\" ?')) (forward-sexp 1))))
3838 (looking-at "#+[\t ]*"))
3839 (setq has-comment t)
3840 (setq comment-fill-prefix
3841 (concat (make-string (current-column) ? )
3842 (buffer-substring (match-beginning 0) (match-end 0)))))))
3844 (if (not has-comment)
3845 (fill-paragraph justify)
3847 ;; Narrow to include only the comment, and then fill the region.
3851 ;; Find the first line we should include in the region to fill.
3853 (while (and (zerop (forward-line -1))
3854 (looking-at "^[ \t]*#")))
3856 ;; We may have gone to far. Go forward again.
3857 (or (looking-at "^[ \t]*#")
3861 ;; Find the beginning of the first line past the region to fill.
3863 (while (progn (forward-line 1)
3864 (looking-at "^[ \t]*#")))
3867 ;; Lines with only hashes on them can be paragraph boundaries.
3868 (let ((paragraph-start (concat paragraph-start "\\|[ \t#]*$"))
3869 (paragraph-separate (concat paragraph-separate "\\|[ \t#]*$"))
3870 (fill-prefix comment-fill-prefix))
3871 ;;(message "paragraph-start %S paragraph-separate %S"
3872 ;;paragraph-start paragraph-separate)
3873 (fill-paragraph justify))))
3877 (defun py-fill-string (start &optional justify)
3878 "Fill the paragraph around (point) in the string starting at start"
3879 ;; basic strategy: narrow to the string and call the default
3881 (let (;; the start of the string's contents
3883 ;; the end of the string's contents
3885 ;; length of the string's delimiter
3887 ;; The string delimiter
3893 (if (looking-at "\\('''\\|\"\"\"\\|'\\|\"\\)\\\\?\n?")
3894 (setq string-start (match-end 0)
3895 delim-length (- (match-end 1) (match-beginning 1))
3896 delim (buffer-substring-no-properties (match-beginning 1)
3898 (error "The parameter start is not the beginning of a python string"))
3900 ;; if the string is the first token on a line and doesn't start with
3901 ;; a newline, fill as if the string starts at the beginning of the
3902 ;; line. this helps with one line docstrings
3905 (and (/= (char-before string-start) ?\n)
3906 (looking-at (concat "[ \t]*" delim))
3907 (setq string-start (point))))
3909 (forward-sexp (if (= delim-length 3) 2 1))
3911 ;; with both triple quoted strings and single/double quoted strings
3912 ;; we're now directly behind the first char of the end delimiter
3913 ;; (this doesn't work correctly when the triple quoted string
3914 ;; contains the quote mark itself). The end of the string's contents
3915 ;; is one less than point
3916 (setq string-end (1- (point))))
3918 ;; Narrow to the string's contents and fill the current paragraph
3920 (narrow-to-region string-start string-end)
3921 (let ((ends-with-newline (= (char-before (point-max)) ?\n)))
3922 (fill-paragraph justify)
3923 (if (and (not ends-with-newline)
3924 (= (char-before (point-max)) ?\n))
3925 ;; the default fill-paragraph implementation has inserted a
3926 ;; newline at the end. Remove it again.
3928 (goto-char (point-max))
3929 (delete-char -1)))))
3931 ;; return t to indicate that we've done our work
3934 (defun py-fill-paragraph (&optional justify)
3935 "Like \\[fill-paragraph], but handle Python comments and strings.
3936 If any of the current line is a comment, fill the comment or the
3937 paragraph of it that point is in, preserving the comment's indentation
3939 If point is inside a string, narrow to that string and fill.
3942 ;; fill-paragraph will narrow incorrectly
3945 (let* ((bod (py-point 'bod))
3946 (pps (parse-partial-sexp bod (point))))
3948 ;; are we inside a comment or on a line with only whitespace before
3949 ;; the comment start?
3951 (save-excursion (beginning-of-line) (looking-at "[ \t]*#")))
3952 (py-fill-comment justify))
3953 ;; are we inside a string?
3955 (py-fill-string (nth 8 pps)))
3956 ;; are we at the opening quote of a string, or in the indentation?
3959 (eq (py-in-literal) 'string))
3961 (py-fill-string (py-point 'boi))))
3962 ;; are we at or after the closing quote of a string?
3965 (eq (py-in-literal) 'string))
3967 (py-fill-string (py-point 'boi))))
3968 ;; otherwise use the default
3970 (fill-paragraph justify))))))
3972 (add-hook 'python-mode-hook '(lambda ()(set (make-local-variable 'beginning-of-defun-function) 'py-beginning-of-def-or-class)))
3974 (add-hook 'python-mode-hook '(lambda ()(set (make-local-variable 'end-of-defun-function) 'py-end-of-def-or-class)))
3978 (provide 'python-mode)
3979 ;;; python-mode.el ends here