1 ;;; python-mode.el --- Major mode for editing Python programs
3 ;; Copyright (C) 1992,1993,1994 Tim Peters
5 ;; Author: 1995-2001 Barry A. Warsaw
6 ;; 1992-1994 Tim Peters
7 ;; Maintainer: python-mode@python.org
9 ;; Keywords: python languages oop
11 (defconst py-version
"$Revision$"
12 "`python-mode' version number.")
14 ;; This software is provided as-is, without express or implied
15 ;; warranty. Permission to use, copy, modify, distribute or sell this
16 ;; software, without fee, for any purpose and by any individual or
17 ;; organization, is hereby granted, provided that the above copyright
18 ;; notice and this paragraph appear in all copies.
22 ;; This is a major mode for editing Python programs. It was developed
23 ;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24 ;; subsequently left the net; in 1995, Barry Warsaw inherited the mode
25 ;; and is the current maintainer. Tim's now back but disavows all
26 ;; responsibility for the mode. Smart Tim :-)
28 ;; pdbtrack support contributed by Ken Manheimer, April 2001.
30 ;; This version of python-mode.el has only been tested with XEmacs
31 ;; 21.1.14 and Emacs 20.7 as these are the latest versions of these
32 ;; Emacsen as of this writing (11-Apr-2001). I have no intent to test
33 ;; it with earlier Emacsen, but I will accept patches if they are
34 ;; small and reasonable. Please use the SourceForge Python project to
35 ;; submit bugs or patches:
37 ;; http://sourceforge.net/projects/python
39 ;; FOR MORE INFORMATION:
41 ;; There is some information on python-mode.el at
43 ;; http://www.python.org/emacs/python-mode/
45 ;; but this link is fairly out of date, due to the current difficulty
46 ;; in updating that site. It does contain links to other packages that
47 ;; you might find useful, such as pdb interfaces, OO-Browser links,
48 ;; etc. Eventually, we'll be able to update it much more easily.
52 ;; As mentioned above, please use the SourceForge Python project for
53 ;; submitting bug reports or patches. The old recommendation, to use
54 ;; C-c C-b will still work, but those reports have a higher chance of
55 ;; getting buried in my mailbox. Please include a complete, but
56 ;; concise code sample and a recipe for reproducing the bug. Send
57 ;; suggestions and other comments to python-mode@python.org.
59 ;; When in a Python mode buffer, do a C-h m for more help. It's
60 ;; doubtful that a texinfo manual would be very useful, but if you
61 ;; want to contribute one, I'll certainly accept it!
70 ;; user definable variables
71 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
74 "Support for the Python programming language, <http://www.python.org/>"
78 (defcustom py-python-command
"python"
79 "*Shell command used to start Python interpreter."
83 (defcustom py-jpython-command
"jpython"
84 "*Shell command used to start the JPython interpreter."
87 :tag
"JPython Command")
89 (defcustom py-default-interpreter
'cpython
90 "*Which Python interpreter is used by default.
91 The value for this variable can be either `cpython' or `jpython'.
93 When the value is `cpython', the variables `py-python-command' and
94 `py-python-command-args' are consulted to determine the interpreter
97 When the value is `jpython', the variables `py-jpython-command' and
98 `py-jpython-command-args' are consulted to determine the interpreter
101 Note that this variable is consulted only the first time that a Python
102 mode buffer is visited during an Emacs session. After that, use
103 \\[py-toggle-shells] to change the interpreter shell."
104 :type
'(choice (const :tag
"Python (a.k.a. CPython)" cpython
)
105 (const :tag
"JPython" jpython
))
108 (defcustom py-python-command-args
'("-i")
109 "*List of string arguments to be used when starting a Python shell."
110 :type
'(repeat string
)
113 (defcustom py-jpython-command-args
'("-i")
114 "*List of string arguments to be used when starting a JPython shell."
115 :type
'(repeat string
)
117 :tag
"JPython Command Args")
119 (defcustom py-indent-offset
4
120 "*Amount of offset per level of indentation.
121 `\\[py-guess-indent-offset]' can usually guess a good value when
122 you're editing someone else's Python code."
126 (defcustom py-continuation-offset
4
127 "*Additional amount of offset to give for some continuation lines.
128 Continuation lines are those that immediately follow a backslash
129 terminated line. Only those continuation lines for a block opening
130 statement are given this extra offset."
134 (defcustom py-smart-indentation t
135 "*Should `python-mode' try to automagically set some indentation variables?
136 When this variable is non-nil, two things happen when a buffer is set
139 1. `py-indent-offset' is guessed from existing code in the buffer.
140 Only guessed values between 2 and 8 are considered. If a valid
141 guess can't be made (perhaps because you are visiting a new
142 file), then the value in `py-indent-offset' is used.
144 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
145 equal `tab-width' (`indent-tabs-mode' is never turned on by
146 Python mode). This means that for newly written code, tabs are
147 only inserted in indentation if one tab is one indentation
148 level, otherwise only spaces are used.
150 Note that both these settings occur *after* `python-mode-hook' is run,
151 so if you want to defeat the automagic configuration, you must also
152 set `py-smart-indentation' to nil in your `python-mode-hook'."
156 (defcustom py-align-multiline-strings-p t
157 "*Flag describing how multi-line triple quoted strings are aligned.
158 When this flag is non-nil, continuation lines are lined up under the
159 preceding line's indentation. When this flag is nil, continuation
160 lines are aligned to column zero."
161 :type
'(choice (const :tag
"Align under preceding line" t
)
162 (const :tag
"Align to column zero" nil
))
165 (defcustom py-block-comment-prefix
"##"
166 "*String used by \\[comment-region] to comment out a block of code.
167 This should follow the convention for non-indenting comment lines so
168 that the indentation commands won't get confused (i.e., the string
169 should be of the form `#x...' where `x' is not a blank or a tab, and
170 `...' is arbitrary). However, this string should not end in whitespace."
174 (defcustom py-honor-comment-indentation t
175 "*Controls how comment lines influence subsequent indentation.
177 When nil, all comment lines are skipped for indentation purposes, and
178 if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
180 When t, lines that begin with a single `#' are a hint to subsequent
181 line indentation. If the previous line is such a comment line (as
182 opposed to one that starts with `py-block-comment-prefix'), then its
183 indentation is used as a hint for this line's indentation. Lines that
184 begin with `py-block-comment-prefix' are ignored for indentation
187 When not nil or t, comment lines that begin with a `#' are used as
188 indentation hints, unless the comment character is in column zero."
190 (const :tag
"Skip all comment lines (fast)" nil
)
191 (const :tag
"Single # `sets' indentation for next line" t
)
192 (const :tag
"Single # `sets' indentation except at column zero"
197 (defcustom py-temp-directory
198 (let ((ok '(lambda (x)
200 (setq x
(expand-file-name x
)) ; always true
204 (or (funcall ok
(getenv "TMPDIR"))
205 (funcall ok
"/usr/tmp")
209 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
210 "*Directory used for temp files created by a *Python* process.
211 By default, the first directory from this list that exists and that you
212 can write into: the value (if any) of the environment variable TMPDIR,
213 /usr/tmp, /tmp, or the current directory."
217 (defcustom py-beep-if-tab-change t
218 "*Ring the bell if `tab-width' is changed.
219 If a comment of the form
221 \t# vi:set tabsize=<number>:
223 is found before the first code line when the file is entered, and the
224 current value of (the general Emacs variable) `tab-width' does not
225 equal <number>, `tab-width' is set to <number>, a message saying so is
226 displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
227 the Emacs bell is also rung as a warning."
231 (defcustom py-jump-on-exception t
232 "*Jump to innermost exception frame in *Python Output* buffer.
233 When this variable is non-nil and an exception occurs when running
234 Python code synchronously in a subprocess, jump immediately to the
235 source code of the innermost traceback frame."
239 (defcustom py-ask-about-save t
240 "If not nil, ask about which buffers to save before executing some code.
241 Otherwise, all modified buffers are saved without asking."
245 (defcustom py-backspace-function
'backward-delete-char-untabify
246 "*Function called by `py-electric-backspace' when deleting backwards."
250 (defcustom py-delete-function
'delete-char
251 "*Function called by `py-electric-delete' when deleting forwards."
255 (defcustom py-imenu-show-method-args-p nil
256 "*Controls echoing of arguments of functions & methods in the Imenu buffer.
257 When non-nil, arguments are printed."
260 (make-variable-buffer-local 'py-indent-offset
)
262 (defcustom py-pdbtrack-do-tracking-p t
263 "*Controls whether the pdbtrack feature is enabled or not.
264 When non-nil, pdbtrack is enabled in all comint-based buffers,
265 e.g. shell buffers and the *Python* buffer. When using pdb to debug a
266 Python program, pdbtrack notices the pdb prompt and displays the
267 source file and line that the program is stopped at, much the same way
268 as gud-mode does for debugging C programs with gdb."
271 (make-variable-buffer-local 'py-pdbtrack-do-tracking-p
)
273 (defcustom py-pdbtrack-minor-mode-string
" PDB"
274 "*String to use in the minor mode list when pdbtrack is enabled."
279 (defvar py-master-file nil
280 "If non-nil, execute the named file instead of the buffer's file.
281 The intent is to allow you to set this variable in the file's local
282 variable section, e.g.:
285 # py-master-file: \"master.py\"
288 so that typing \\[py-execute-buffer] in that buffer executes the named
289 master file instead of the buffer's file. If the file name has a
290 relative path, the value of variable `default-directory' for the
291 buffer is prepended to come up with a file name.")
292 (make-variable-buffer-local 'py-master-file
)
296 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
297 ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
299 (defconst py-emacs-features
302 "A list of features extant in the Emacs you are using.
303 There are many flavors of Emacs out there, with different levels of
304 support for features needed by `python-mode'.")
306 (defvar python-font-lock-keywords
307 (let ((kw1 (mapconcat 'identity
308 '("and" "assert" "break" "class"
309 "continue" "def" "del" "elif"
310 "else" "except" "exec" "for"
311 "from" "global" "if" "import"
312 "in" "is" "lambda" "not"
313 "or" "pass" "print" "raise"
314 "return" "while" "yield"
317 (kw2 (mapconcat 'identity
318 '("else:" "except:" "finally:" "try:")
323 (cons (concat "\\b\\(" kw1
"\\)\\b[ \n\t(]") 1)
324 ;; block introducing keywords with immediately following colons.
325 ;; Yes "except" is in both lists.
326 (cons (concat "\\b\\(" kw2
"\\)[ \n\t(]") 1)
327 ;; `as' but only in "import foo as bar"
328 '("[ \t]*\\(\\bfrom\\b.*\\)?\\bimport\\b.*\\b\\(as\\)\\b" .
2)
330 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
331 1 font-lock-type-face
)
333 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
334 1 font-lock-function-name-face
)
336 "Additional expressions to highlight in Python mode.")
337 (put 'python-mode
'font-lock-defaults
'(python-font-lock-keywords))
339 ;; have to bind py-file-queue before installing the kill-emacs-hook
340 (defvar py-file-queue nil
341 "Queue of Python temp files awaiting execution.
342 Currently-active file is at the head of the list.")
344 (defvar py-pdbtrack-is-tracking-p nil
)
350 (defconst py-stringlit-re
352 ;; These fail if backslash-quote ends the string (not worth
353 ;; fixing?). They precede the short versions so that the first two
354 ;; quotes don't look like an empty short string.
356 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
357 ;; with potential embedded single quotes
358 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
360 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
361 ;; with potential embedded double quotes
362 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
364 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
366 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
368 "Regular expression matching a Python string literal.")
370 (defconst py-continued-re
371 ;; This is tricky because a trailing backslash does not mean
372 ;; continuation if it's in a comment
374 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re
"\\)*"
376 "Regular expression matching Python backslash continuation lines.")
378 (defconst py-blank-or-comment-re
"[ \t]*\\($\\|#\\)"
379 "Regular expression matching a blank or comment line.")
381 (defconst py-outdent-re
382 (concat "\\(" (mapconcat 'identity
384 "except\\(\\s +.*\\)?:"
389 "Regular expression matching statements to be dedented one level.")
391 (defconst py-block-closing-keywords-re
392 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
393 "Regular expression matching keywords which typically close a block.")
395 (defconst py-no-outdent-re
400 "except\\(\\s +.*\\)?:"
405 (concat py-block-closing-keywords-re
"[ \t\n]")
409 "Regular expression matching lines not to dedent after.")
411 (defconst py-defun-start-re
412 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
413 ;; If you change this, you probably have to change py-current-defun
414 ;; as well. This is only used by py-current-defun to find the name
416 "Regular expression matching a function, method, or variable assignment.")
418 (defconst py-class-start-re
"^class[ \t]*\\([a-zA-Z_0-9]+\\)"
419 ;; If you change this, you probably have to change py-current-defun
420 ;; as well. This is only used by py-current-defun to find the name
422 "Regular expression for finding a class name.")
424 (defconst py-traceback-line-re
425 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
426 "Regular expression that describes tracebacks.")
429 (defconst py-pdbtrack-stack-entry-regexp
430 "> \\([^(]+\\)(\\([0-9]+\\))[?a-zA-Z0-9_]+()"
431 "Regular expression pdbtrack uses to find a stack trace entry.")
433 (defconst py-pdbtrack-input-prompt
"\n[(<]?pdb[>)]? "
434 "Regular expression pdbtrack uses to recognize a pdb prompt.")
436 (defconst py-pdbtrack-track-range
10000
437 "Max number of characters from end of buffer to search for stack entry.")
441 ;; Major mode boilerplate
443 ;; define a mode-specific abbrev table for those who use such things
444 (defvar python-mode-abbrev-table nil
445 "Abbrev table in use in `python-mode' buffers.")
446 (define-abbrev-table 'python-mode-abbrev-table nil
)
448 (defvar python-mode-hook nil
449 "*Hook called by `python-mode'.")
451 ;; In previous version of python-mode.el, the hook was incorrectly
452 ;; called py-mode-hook, and was not defvar'd. Deprecate its use.
453 (and (fboundp 'make-obsolete-variable
)
454 (make-obsolete-variable 'py-mode-hook
'python-mode-hook
))
456 (defvar py-mode-map
()
457 "Keymap used in `python-mode' buffers.")
460 (setq py-mode-map
(make-sparse-keymap))
462 (define-key py-mode-map
":" 'py-electric-colon
)
463 ;; indentation level modifiers
464 (define-key py-mode-map
"\C-c\C-l" 'py-shift-region-left
)
465 (define-key py-mode-map
"\C-c\C-r" 'py-shift-region-right
)
466 (define-key py-mode-map
"\C-c<" 'py-shift-region-left
)
467 (define-key py-mode-map
"\C-c>" 'py-shift-region-right
)
468 ;; subprocess commands
469 (define-key py-mode-map
"\C-c\C-c" 'py-execute-buffer
)
470 (define-key py-mode-map
"\C-c\C-m" 'py-execute-import-or-reload
)
471 (define-key py-mode-map
"\C-c\C-s" 'py-execute-string
)
472 (define-key py-mode-map
"\C-c|" 'py-execute-region
)
473 (define-key py-mode-map
"\e\C-x" 'py-execute-def-or-class
)
474 (define-key py-mode-map
"\C-c!" 'py-shell
)
475 (define-key py-mode-map
"\C-c\C-t" 'py-toggle-shells
)
476 ;; Caution! Enter here at your own risk. We are trying to support
477 ;; several behaviors and it gets disgusting. :-( This logic ripped
478 ;; largely from CC Mode.
480 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
481 ;; backwards deletion behavior to DEL, which both Delete and
482 ;; Backspace get translated to. There's no way to separate this
483 ;; behavior in a clean way, so deal with it! Besides, it's been
484 ;; this way since the dawn of time.
485 (if (not (boundp 'delete-key-deletes-forward
))
486 (define-key py-mode-map
"\177" 'py-electric-backspace
)
487 ;; However, XEmacs 20 actually achieved enlightenment. It is
488 ;; possible to sanely define both backward and forward deletion
489 ;; behavior under X separately (TTYs are forever beyond hope, but
490 ;; who cares? XEmacs 20 does the right thing with these too).
491 (define-key py-mode-map
[delete] 'py-electric-delete)
492 (define-key py-mode-map [backspace] 'py-electric-backspace))
493 ;; Separate M-BS from C-M-h. The former should remain
494 ;; backward-kill-word.
495 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
496 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
498 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
499 (define-key py-mode-map "\C-c\t" 'py-indent-region)
500 (define-key py-mode-map "\C-c\C-d" 'py-pdbtrack-toggle-stack-tracking)
501 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
502 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
503 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
504 (define-key py-mode-map "\C-c#" 'py-comment-region)
505 (define-key py-mode-map "\C-c?" 'py-describe-mode)
506 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
507 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
508 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
509 (define-key py-mode-map "\C-c-" 'py-up-exception)
510 (define-key py-mode-map "\C-c=" 'py-down-exception)
511 ;; stuff that is `standard' but doesn't interface well with
512 ;; python-mode, which forces us to rebind to special commands
513 (define-key py-mode-map "\C-xnd" 'py-narrow-to-defun)
515 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
516 (define-key py-mode-map "\C-c\C-v" 'py-version)
517 ;; shadow global bindings for newline-and-indent w/ the py- version.
518 ;; BAW - this is extremely bad form, but I'm not going to change it
520 (mapcar #'(lambda (key)
521 (define-key py-mode-map key 'py-newline-and-indent))
522 (where-is-internal 'newline-and-indent))
523 ;; Force RET to be py-newline-and-indent even if it didn't get
524 ;; mapped by the above code. motivation: Emacs' default binding for
525 ;; RET is `newline' and C-j is `newline-and-indent'. Most Pythoneers
526 ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
527 ;; dislike this are probably knowledgeable enough to do a rebind.
528 ;; However, we do *not* change C-j since many Emacsers have already
529 ;; swapped RET and C-j and they don't want C-j bound to `newline' to
531 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
534 (defvar py-mode-output-map nil
535 "Keymap used in *Python Output* buffers.")
536 (if py-mode-output-map
538 (setq py-mode-output-map (make-sparse-keymap))
539 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
540 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
541 ;; TBD: Disable all self-inserting keys. This is bogus, we should
542 ;; really implement this as *Python Output* buffer being read-only
543 (mapcar #' (lambda (key)
544 (define-key py-mode-output-map key
545 #'(lambda () (interactive) (beep))))
546 (where-is-internal 'self-insert-command))
549 (defvar py-shell-map nil
550 "Keymap used in *Python* shell buffers.")
553 (setq py-shell-map (copy-keymap comint-mode-map))
554 (define-key py-shell-map [tab] 'tab-to-tab-stop)
555 (define-key py-shell-map "\C-c-" 'py-up-exception)
556 (define-key py-shell-map "\C-c=" 'py-down-exception)
559 (defvar py-mode-syntax-table nil
560 "Syntax table used in `python-mode' buffers.")
561 (if py-mode-syntax-table
563 (setq py-mode-syntax-table (make-syntax-table))
564 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
565 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
566 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
567 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
568 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
569 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
570 ;; Add operator symbols misassigned in the std table
571 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
572 (modify-syntax-entry ?\% "." py-mode-syntax-table)
573 (modify-syntax-entry ?\& "." py-mode-syntax-table)
574 (modify-syntax-entry ?\* "." py-mode-syntax-table)
575 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
576 (modify-syntax-entry ?\- "." py-mode-syntax-table)
577 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
578 (modify-syntax-entry ?\< "." py-mode-syntax-table)
579 (modify-syntax-entry ?\= "." py-mode-syntax-table)
580 (modify-syntax-entry ?\> "." py-mode-syntax-table)
581 (modify-syntax-entry ?\| "." py-mode-syntax-table)
582 ;; For historical reasons, underscore is word class instead of
583 ;; symbol class. GNU conventions say it should be symbol class, but
584 ;; there's a natural conflict between what major mode authors want
585 ;; and what users expect from `forward-word' and `backward-word'.
586 ;; Guido and I have hashed this out and have decided to keep
587 ;; underscore in word class. If you're tempted to change it, try
588 ;; binding M-f and M-b to py-forward-into-nomenclature and
589 ;; py-backward-into-nomenclature instead. This doesn't help in all
590 ;; situations where you'd want the different behavior
591 ;; (e.g. backward-kill-word).
592 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
593 ;; Both single quote and double quote are string delimiters
594 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
595 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
596 ;; backquote is open and close paren
597 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
598 ;; comment delimiters
599 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
600 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
607 (defmacro py-safe (&rest body)
608 "Safely execute BODY, return nil if an error occurred."
609 (` (condition-case nil
613 (defsubst py-keep-region-active ()
614 "Keep the region active in XEmacs."
615 ;; Ignore byte-compiler warnings you might see. Also note that
616 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
617 ;; to take explicit action.
618 (and (boundp 'zmacs-region-stays)
619 (setq zmacs-region-stays t)))
621 (defsubst py-point (position)
622 "Returns the value of point at certain commonly referenced POSITIONs.
623 POSITION can be one of the following symbols:
625 bol -- beginning of line
627 bod -- beginning of def or class
628 eod -- end of def or class
629 bob -- beginning of buffer
631 boi -- back to indentation
632 bos -- beginning of statement
634 This function does not modify point or mark."
635 (let ((here (point)))
637 ((eq position 'bol) (beginning-of-line))
638 ((eq position 'eol) (end-of-line))
639 ((eq position 'bod) (py-beginning-of-def-or-class))
640 ((eq position 'eod) (py-end-of-def-or-class))
641 ;; Kind of funny, I know, but useful for py-up-exception.
642 ((eq position 'bob) (beginning-of-buffer))
643 ((eq position 'eob) (end-of-buffer))
644 ((eq position 'boi) (back-to-indentation))
645 ((eq position 'bos) (py-goto-initial-line))
646 (t (error "Unknown buffer position requested: %s" position))
652 (defsubst py-highlight-line (from to file line)
654 ((fboundp 'make-extent)
656 (let ((e (make-extent from to)))
657 (set-extent-property e 'mouse-face 'highlight)
658 (set-extent-property e 'py-exc-info (cons file line))
659 (set-extent-property e 'keymap py-mode-output-map)))
661 ;; Emacs -- Please port this!
665 (defun py-in-literal (&optional lim)
666 "Return non-nil if point is in a Python literal (a comment or string).
667 Optional argument LIM indicates the beginning of the containing form,
668 i.e. the limit on how far back to scan."
669 ;; This is the version used for non-XEmacs, which has a nicer
672 ;; WARNING: Watch out for infinite recursion.
673 (let* ((lim (or lim (py-point 'bod)))
674 (state (parse-partial-sexp lim (point))))
676 ((nth 3 state) 'string)
677 ((nth 4 state) 'comment)
680 ;; XEmacs has a built-in function that should make this much quicker.
681 ;; In this case, lim is ignored
682 (defun py-fast-in-literal (&optional lim)
683 "Fast version of `py-in-literal', used only by XEmacs.
684 Optional LIM is ignored."
685 ;; don't have to worry about context == 'block-comment
686 (buffer-syntactic-context))
688 (if (fboundp 'buffer-syntactic-context)
689 (defalias 'py-in-literal 'py-fast-in-literal))
693 ;; Menu definitions, only relevent if you have the easymenu.el package
694 ;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
696 "Menu for Python Mode.
697 This menu will get created automatically if you have the `easymenu'
698 package. Note that the latest X/Emacs releases contain this package.")
700 (and (py-safe (require 'easymenu) t)
702 py-menu py-mode-map "Python Mode menu"
704 ["Comment Out Region" py-comment-region (mark)]
705 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
707 ["Mark current block" py-mark-block t]
708 ["Mark current def" py-mark-def-or-class t]
709 ["Mark current class" (py-mark-def-or-class t) t]
711 ["Shift region left" py-shift-region-left (mark)]
712 ["Shift region right" py-shift-region-right (mark)]
714 ["Import/reload file" py-execute-import-or-reload t]
715 ["Execute buffer" py-execute-buffer t]
716 ["Execute region" py-execute-region (mark)]
717 ["Execute def or class" py-execute-def-or-class (mark)]
718 ["Execute string" py-execute-string t]
719 ["Start interpreter..." py-shell t]
721 ["Go to start of block" py-goto-block-up t]
722 ["Go to start of class" (py-beginning-of-def-or-class t) t]
723 ["Move to end of class" (py-end-of-def-or-class t) t]
724 ["Move to start of def" py-beginning-of-def-or-class t]
725 ["Move to end of def" py-end-of-def-or-class t]
727 ["Describe mode" py-describe-mode t]
733 (defvar py-imenu-class-regexp
734 (concat ; <<classes>>
736 "^[ \t]*" ; newline and maybe whitespace
737 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
738 ; possibly multiple superclasses
739 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
740 "[ \t]*:" ; and the final :
743 "Regexp for Python classes for use with the Imenu package."
746 (defvar py-imenu-method-regexp
747 (concat ; <<methods and functions>>
749 "^[ \t]*" ; new line and maybe whitespace
750 "\\(def[ \t]+" ; function definitions start with def
751 "\\([a-zA-Z0-9_]+\\)" ; name is here
752 ; function arguments...
753 ;; "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
754 "[ \t]*(\\([^:#]*\\))"
756 "[ \t]*:" ; and then the :
757 "\\)" ; >>methods and functions<<
759 "Regexp for Python methods/functions for use with the Imenu package."
762 (defvar py-imenu-method-no-arg-parens '(2 8)
763 "Indices into groups of the Python regexp for use with Imenu.
765 Using these values will result in smaller Imenu lists, as arguments to
766 functions are not listed.
768 See the variable `py-imenu-show-method-args-p' for more
771 (defvar py-imenu-method-arg-parens '(2 7)
772 "Indices into groups of the Python regexp for use with imenu.
773 Using these values will result in large Imenu lists, as arguments to
774 functions are listed.
776 See the variable `py-imenu-show-method-args-p' for more
779 ;; Note that in this format, this variable can still be used with the
780 ;; imenu--generic-function. Otherwise, there is no real reason to have
782 (defvar py-imenu-generic-expression
785 py-imenu-class-regexp
787 py-imenu-method-regexp
789 py-imenu-method-no-arg-parens)
790 "Generic Python expression which may be used directly with Imenu.
791 Used by setting the variable `imenu-generic-expression' to this value.
792 Also, see the function \\[py-imenu-create-index] for a better
793 alternative for finding the index.")
795 ;; These next two variables are used when searching for the Python
796 ;; class/definitions. Just saving some time in accessing the
797 ;; generic-python-expression, really.
798 (defvar py-imenu-generic-regexp nil)
799 (defvar py-imenu-generic-parens nil)
802 (defun py-imenu-create-index-function ()
803 "Python interface function for the Imenu package.
804 Finds all Python classes and functions/methods. Calls function
805 \\[py-imenu-create-index-engine]. See that function for the details
807 (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
808 py-imenu-generic-parens (if py-imenu-show-method-args-p
809 py-imenu-method-arg-parens
810 py-imenu-method-no-arg-parens))
811 (goto-char (point-min))
812 ;; Warning: When the buffer has no classes or functions, this will
813 ;; return nil, which seems proper according to the Imenu API, but
814 ;; causes an error in the XEmacs port of Imenu. Sigh.
815 (py-imenu-create-index-engine nil))
817 (defun py-imenu-create-index-engine (&optional start-indent)
818 "Function for finding Imenu definitions in Python.
820 Finds all definitions (classes, methods, or functions) in a Python
821 file for the Imenu package.
823 Returns a possibly nested alist of the form
825 (INDEX-NAME . INDEX-POSITION)
827 The second element of the alist may be an alist, producing a nested
830 (INDEX-NAME . INDEX-ALIST)
832 This function should not be called directly, as it calls itself
833 recursively and requires some setup. Rather this is the engine for
834 the function \\[py-imenu-create-index-function].
836 It works recursively by looking for all definitions at the current
837 indention level. When it finds one, it adds it to the alist. If it
838 finds a definition at a greater indentation level, it removes the
839 previous definition from the alist. In its place it adds all
840 definitions found at the next indentation level. When it finds a
841 definition that is less indented then the current level, it returns
842 the alist it has created thus far.
844 The optional argument START-INDENT indicates the starting indentation
845 at which to continue looking for Python classes, methods, or
846 functions. If this is not supplied, the function uses the indentation
847 of the first definition found."
853 (class-paren (first py-imenu-generic-parens))
854 (def-paren (second py-imenu-generic-parens)))
856 (re-search-forward py-imenu-generic-regexp (point-max) t))
859 ;; used to set def-name to this value but generic-extract-name
860 ;; is new to imenu-1.14. this way it still works with
862 ;;(imenu--generic-extract-name py-imenu-generic-parens))
863 (let ((cur-paren (if (match-beginning class-paren)
864 class-paren def-paren)))
866 (buffer-substring-no-properties (match-beginning cur-paren)
867 (match-end cur-paren))))
869 (py-beginning-of-def-or-class 'either))
871 (setq cur-indent (current-indentation)))
872 ;; HACK: want to go to the next correct definition location. We
873 ;; explicitly list them here but it would be better to have them
876 (or (match-beginning class-paren)
877 (match-beginning def-paren)))
878 ;; if we don't have a starting indent level, take this one
880 (setq start-indent cur-indent))
881 ;; if we don't have class name yet, take this one
883 (setq prev-name def-name))
884 ;; what level is the next definition on? must be same, deeper
885 ;; or shallower indentation
887 ;; at the same indent level, add it to the list...
888 ((= start-indent cur-indent)
889 (push (cons def-name def-pos) index-alist))
890 ;; deeper indented expression, recurse
891 ((< start-indent cur-indent)
892 ;; the point is currently on the expression we're supposed to
893 ;; start on, so go back to the last expression. The recursive
894 ;; call will find this place again and add it to the correct
896 (re-search-backward py-imenu-generic-regexp (point-min) 'move)
897 (setq sub-method-alist (py-imenu-create-index-engine cur-indent))
899 ;; we put the last element on the index-alist on the start
900 ;; of the submethod alist so the user can still get to it.
901 (let ((save-elmt (pop index-alist)))
902 (push (cons prev-name
903 (cons save-elmt sub-method-alist))
905 ;; found less indented expression, we're done.
908 (re-search-backward py-imenu-generic-regexp (point-min) t)))
910 (setq prev-name def-name)
913 (re-search-forward py-imenu-generic-regexp
914 (point-max) 'move))))
915 (nreverse index-alist)))
919 (defun python-mode ()
920 "Major mode for editing Python files.
921 To submit a problem report, enter `\\[py-submit-bug-report]' from a
922 `python-mode' buffer. Do `\\[py-describe-mode]' for detailed
923 documentation. To see what version of `python-mode' you are running,
924 enter `\\[py-version]'.
926 This mode knows about Python indentation, tokens, comments and
927 continuation lines. Paragraphs are separated by blank lines only.
933 py-indent-offset\t\tindentation increment
934 py-block-comment-prefix\t\tcomment string used by `comment-region'
935 py-python-command\t\tshell command to invoke Python interpreter
936 py-temp-directory\t\tdirectory used for temp files (if needed)
937 py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
939 ;; set up local variables
940 (kill-all-local-variables)
941 (make-local-variable 'font-lock-defaults)
942 (make-local-variable 'paragraph-separate)
943 (make-local-variable 'paragraph-start)
944 (make-local-variable 'require-final-newline)
945 (make-local-variable 'comment-start)
946 (make-local-variable 'comment-end)
947 (make-local-variable 'comment-start-skip)
948 (make-local-variable 'comment-column)
949 (make-local-variable 'comment-indent-function)
950 (make-local-variable 'indent-region-function)
951 (make-local-variable 'indent-line-function)
952 (make-local-variable 'add-log-current-defun-function)
954 (set-syntax-table py-mode-syntax-table)
955 (setq major-mode 'python-mode
957 local-abbrev-table python-mode-abbrev-table
958 font-lock-defaults '(python-font-lock-keywords)
959 paragraph-separate "^[ \t]*$"
960 paragraph-start "^[ \t]*$"
961 require-final-newline t
964 comment-start-skip "# *"
966 comment-indent-function 'py-comment-indent-function
967 indent-region-function 'py-indent-region
968 indent-line-function 'py-indent-line
969 ;; tell add-log.el how to find the current function/method/variable
970 add-log-current-defun-function 'py-current-defun
972 (use-local-map py-mode-map)
975 (easy-menu-add py-menu))
976 ;; Emacs 19 requires this
977 (if (boundp 'comment-multi-line)
978 (setq comment-multi-line nil))
979 ;; Install Imenu if available
980 (when (py-safe (require 'imenu))
981 (setq imenu-create-index-function #'py-imenu-create-index-function)
982 (setq imenu-generic-expression py-imenu-generic-expression)
983 (if (fboundp 'imenu-add-to-menubar)
984 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
986 ;; Run the mode hook. Note that py-mode-hook is deprecated.
988 (run-hooks 'python-mode-hook)
989 (run-hooks 'py-mode-hook))
990 ;; Now do the automagical guessing
991 (if py-smart-indentation
992 (let ((offset py-indent-offset))
993 ;; It's okay if this fails to guess a good value
994 (if (and (py-safe (py-guess-indent-offset))
995 (<= py-indent-offset 8)
996 (>= py-indent-offset 2))
997 (setq offset py-indent-offset))
998 (setq py-indent-offset offset)
999 ;; Only turn indent-tabs-mode off if tab-width !=
1000 ;; py-indent-offset. Never turn it on, because the user must
1001 ;; have explicitly turned it off.
1002 (if (/= tab-width py-indent-offset)
1003 (setq indent-tabs-mode nil))
1005 ;; Set the default shell if not already set
1006 (when (null py-which-shell)
1007 (py-toggle-shells py-default-interpreter))
1011 ;; electric characters
1012 (defun py-outdent-p ()
1013 "Returns non-nil if the current line should dedent one level."
1015 (and (progn (back-to-indentation)
1016 (looking-at py-outdent-re))
1017 ;; short circuit infloop on illegal construct
1019 (progn (forward-line -1)
1020 (py-goto-initial-line)
1021 (back-to-indentation)
1022 (while (or (looking-at py-blank-or-comment-re)
1024 (backward-to-indentation 1))
1025 (not (looking-at py-no-outdent-re)))
1028 (defun py-electric-colon (arg)
1030 In certain cases the line is dedented appropriately. If a numeric
1031 argument ARG is provided, that many colons are inserted
1032 non-electrically. Electric behavior is inhibited inside a string or
1035 (self-insert-command (prefix-numeric-value arg))
1036 ;; are we in a string or comment?
1038 (let ((pps (parse-partial-sexp (save-excursion
1039 (py-beginning-of-def-or-class)
1042 (not (or (nth 3 pps) (nth 4 pps)))))
1044 (let ((here (point))
1046 (indent (py-compute-indentation t)))
1049 (= indent (save-excursion
1050 (py-next-statement -1)
1051 (py-compute-indentation t)))
1053 (setq outdent py-indent-offset))
1054 ;; Don't indent, only dedent. This assumes that any lines
1055 ;; that are already dedented relative to
1056 ;; py-compute-indentation were put there on purpose. It's
1057 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1058 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1059 ;; determine this???
1060 (if (< (current-indentation) indent) nil
1063 (delete-horizontal-space)
1064 (indent-to (- indent outdent))
1068 ;; Python subprocess utilities and filters
1069 (defun py-execute-file (proc filename)
1070 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1071 Make that process's buffer visible and force display. Also make
1072 comint believe the user typed this string so that
1073 `kill-output-from-shell' does The Right Thing."
1074 (let ((curbuf (current-buffer))
1075 (procbuf (process-buffer proc))
1076 ; (comint-scroll-to-bottom-on-output t)
1077 (msg (format "## working on region in file %s...\n" filename))
1078 (cmd (format "execfile(r'%s')\n" filename)))
1081 (set-buffer procbuf)
1082 (goto-char (point-max))
1083 (move-marker (process-mark proc) (point))
1084 (funcall (process-filter proc) proc msg))
1085 (set-buffer curbuf))
1086 (process-send-string proc cmd)))
1088 (defun py-comint-output-filter-function (string)
1089 "Watch output for Python prompt and exec next file waiting in queue.
1090 This function is appropriate for `comint-output-filter-functions'."
1091 ;; TBD: this should probably use split-string
1092 (when (and (or (string-equal string ">>> ")
1093 (and (>= (length string) 5)
1094 (string-equal (substring string -5) "\n>>> ")))
1096 (py-safe (delete-file (car py-file-queue)))
1097 (setq py-file-queue (cdr py-file-queue))
1099 (let ((pyproc (get-buffer-process (current-buffer))))
1100 (py-execute-file pyproc (car py-file-queue))))
1103 (defun py-pdbtrack-overlay-arrow (activation)
1104 "Activate or de arrow at beginning-of-line in current buffer."
1105 ;; This was derived/simplified from edebug-overlay-arrow
1107 (setq overlay-arrow-position (make-marker))
1108 (setq overlay-arrow-string "=>")
1109 (set-marker overlay-arrow-position (py-point 'bol) (current-buffer))
1110 (setq py-pdbtrack-is-tracking-p t))
1111 (overlay-arrow-position
1112 (setq overlay-arrow-position nil)
1113 (setq py-pdbtrack-is-tracking-p nil))
1116 (defun py-pdbtrack-track-stack-file (text)
1117 "Show the file indicated by the pdb stack entry line, in a separate window.
1119 Activity is disabled if the buffer-local variable
1120 `py-pdbtrack-do-tracking-p' is nil.
1122 We depend on the pdb input prompt matching `py-pdbtrack-input-prompt'
1123 at the beginning of the line."
1124 ;; Instead of trying to piece things together from partial text
1125 ;; (which can be almost useless depending on Emacs version), we
1126 ;; monitor to the point where we have the next pdb prompt, and then
1127 ;; check all text from comint-last-input-end to process-mark.
1129 ;; KLM: It might be nice to provide an optional override, so this
1130 ;; routine could be fed debugger output strings as the text
1131 ;; argument, for deliberate application elsewhere.
1133 ;; KLM: We're very conservative about clearing the overlay arrow, to
1134 ;; minimize residue. This means, for instance, that executing other
1135 ;; pdb commands wipes out the highlight.
1136 (let* ((origbuf (current-buffer))
1137 (currproc (get-buffer-process origbuf)))
1138 (if (not (and currproc py-pdbtrack-do-tracking-p))
1139 (py-pdbtrack-overlay-arrow nil)
1140 (let* (;(origdir default-directory)
1141 (procmark (process-mark currproc))
1142 (block (buffer-substring (max comint-last-input-end
1144 py-pdbtrack-track-range))
1147 (if (not (string-match (concat py-pdbtrack-input-prompt "$") block))
1148 (py-pdbtrack-overlay-arrow nil)
1149 (if (not (string-match
1150 (concat ".*" py-pdbtrack-stack-entry-regexp ".*")
1152 (py-pdbtrack-overlay-arrow nil)
1153 (setq fname (match-string 1 block)
1154 lineno (match-string 2 block))
1155 (if (file-exists-p fname)
1157 (find-file-other-window fname)
1158 (goto-line (string-to-int lineno))
1159 (message "pdbtrack: line %s, file %s" lineno fname)
1160 (py-pdbtrack-overlay-arrow t)
1161 (pop-to-buffer origbuf t) )
1162 (if (= (elt fname 0) ?\<)
1163 (message "pdbtrack: (Non-file source: '%s')" fname)
1164 (message "pdbtrack: File not found: %s" fname))
1167 (defun py-postprocess-output-buffer (buf)
1168 "Highlight exceptions found in BUF.
1169 If an exception occurred return t, otherwise return nil. BUF must exist."
1170 (let (line file bol err-p)
1173 (beginning-of-buffer)
1174 (while (re-search-forward py-traceback-line-re nil t)
1175 (setq file (match-string 1)
1176 line (string-to-int (match-string 2))
1177 bol (py-point 'bol))
1178 (py-highlight-line bol (py-point 'eol) file line)))
1179 (when (and py-jump-on-exception line)
1181 (py-jump-to-exception file line)
1187 ;;; Subprocess commands
1189 ;; only used when (memq 'broken-temp-names py-emacs-features)
1190 (defvar py-serial-number 0)
1191 (defvar py-exception-buffer nil)
1192 (defconst py-output-buffer "*Python Output*")
1193 (make-variable-buffer-local 'py-output-buffer)
1195 ;; for toggling between CPython and JPython
1196 (defvar py-which-shell nil)
1197 (defvar py-which-args py-python-command-args)
1198 (defvar py-which-bufname "Python")
1199 (make-variable-buffer-local 'py-which-shell)
1200 (make-variable-buffer-local 'py-which-args)
1201 (make-variable-buffer-local 'py-which-bufname)
1203 (defun py-toggle-shells (arg)
1204 "Toggles between the CPython and JPython shells.
1206 With positive argument ARG (interactively \\[universal-argument]),
1207 uses the CPython shell, with negative ARG uses the JPython shell, and
1208 with a zero argument, toggles the shell.
1210 Programmatically, ARG can also be one of the symbols `cpython' or
1211 `jpython', equivalent to positive arg and negative arg respectively."
1213 ;; default is to toggle
1220 (if (string-equal py-which-bufname "Python")
1223 ((equal arg 'cpython) (setq arg 1))
1224 ((equal arg 'jpython) (setq arg -1)))
1229 (setq py-which-shell py-python-command
1230 py-which-args py-python-command-args
1231 py-which-bufname "Python"
1233 mode-name "Python"))
1235 (setq py-which-shell py-jpython-command
1236 py-which-args py-jpython-command-args
1237 py-which-bufname "JPython"
1239 mode-name "JPython"))
1241 (message "Using the %s shell" msg)
1242 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
1245 (defun py-shell (&optional argprompt)
1246 "Start an interactive Python interpreter in another window.
1247 This is like Shell mode, except that Python is running in the window
1248 instead of a shell. See the `Interactive Shell' and `Shell Mode'
1249 sections of the Emacs manual for details, especially for the key
1250 bindings active in the `*Python*' buffer.
1252 With optional \\[universal-argument], the user is prompted for the
1253 flags to pass to the Python interpreter. This has no effect when this
1254 command is used to switch to an existing process, only when a new
1255 process is started. If you use this, you will probably want to ensure
1256 that the current arguments are retained (they will be included in the
1257 prompt). This argument is ignored when this function is called
1258 programmatically, or when running in Emacs 19.34 or older.
1260 Note: You can toggle between using the CPython interpreter and the
1261 JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1262 buffer local variables which control whether all your subshell
1263 interactions happen to the `*JPython*' or `*Python*' buffers (the
1264 latter is the name used for the CPython buffer).
1266 Warning: Don't use an interactive Python if you change sys.ps1 or
1267 sys.ps2 from their default values, or if you're running code that
1268 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1269 distinguish your output from Python's output, and assumes that `>>> '
1270 at the start of a line is a prompt from Python. Similarly, the Emacs
1271 Shell mode code assumes that both `>>> ' and `... ' at the start of a
1272 line are Python prompts. Bad things can happen if you fool either
1275 Warning: If you do any editing *in* the process buffer *while* the
1276 buffer is accepting output from Python, do NOT attempt to `undo' the
1277 changes. Some of the output (nowhere near the parts you changed!) may
1278 be lost if you do. This appears to be an Emacs bug, an unfortunate
1279 interaction between undo and process filters; the same problem exists in
1280 non-Python process buffers using the default (Emacs-supplied) process
1283 ;; Set the default shell if not already set
1284 (when (null py-which-shell)
1285 (py-toggle-shells py-default-interpreter))
1286 (let ((args py-which-args))
1287 (when (and argprompt
1289 (fboundp 'split-string))
1290 ;; TBD: Perhaps force "-i" in the final list?
1291 (setq args (split-string
1292 (read-string (concat py-which-bufname
1295 (mapconcat 'identity py-which-args " ") " ")
1297 (switch-to-buffer-other-window
1298 (apply 'make-comint py-which-bufname py-which-shell nil args))
1299 (make-local-variable 'comint-prompt-regexp)
1300 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
1301 (add-hook 'comint-output-filter-functions
1302 'py-comint-output-filter-function)
1304 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
1305 (setq py-pdbtrack-do-tracking-p t)
1306 (set-syntax-table py-mode-syntax-table)
1307 (use-local-map py-shell-map)
1310 (defun py-clear-queue ()
1311 "Clear the queue of temporary files waiting to execute."
1313 (let ((n (length py-file-queue)))
1314 (mapcar 'delete-file py-file-queue)
1315 (setq py-file-queue nil)
1316 (message "%d pending files de-queued." n)))
1319 (defun py-execute-region (start end &optional async)
1320 "Execute the region in a Python interpreter.
1322 The region is first copied into a temporary file (in the directory
1323 `py-temp-directory'). If there is no Python interpreter shell
1324 running, this file is executed synchronously using
1325 `shell-command-on-region'. If the program is long running, use
1326 \\[universal-argument] to run the command asynchronously in its own
1329 When this function is used programmatically, arguments START and END
1330 specify the region to execute, and optional third argument ASYNC, if
1331 non-nil, specifies to run the command asynchronously in its own
1334 If the Python interpreter shell is running, the region is execfile()'d
1335 in that shell. If you try to execute regions too quickly,
1336 `python-mode' will queue them up and execute them one at a time when
1337 it sees a `>>> ' prompt from Python. Each time this happens, the
1338 process buffer is popped into a window (if it's not already in some
1339 window) so you can see it, and a comment of the form
1341 \t## working on region in file <name>...
1343 is inserted at the end. See also the command `py-clear-queue'."
1344 (interactive "r\nP")
1346 (error "Region is empty"))
1347 (let* ((proc (get-process py-which-bufname))
1348 (temp (if (memq 'broken-temp-names py-emacs-features)
1350 ((sn py-serial-number)
1351 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1352 (setq py-serial-number (1+ py-serial-number))
1354 (format "python-%d-%d" sn pid)
1355 (format "python-%d" sn)))
1356 (make-temp-name "python-")))
1357 (file (expand-file-name temp py-temp-directory))
1358 (cur (current-buffer))
1359 (buf (get-buffer-create file)))
1360 ;; Write the contents of the buffer, watching out for indented regions.
1363 (let ((needs-if (/= (py-point 'bol) (py-point 'boi))))
1367 (insert-buffer-substring cur start end)))
1369 ;; always run the code in its own asynchronous subprocess
1371 ;; User explicitly wants this to run in its own async subprocess
1374 (write-region (point-min) (point-max) file nil 'nomsg))
1375 (let* ((buf (generate-new-buffer-name py-output-buffer))
1376 ;; TBD: a horrible hack, but why create new Custom variables?
1377 (arg (if (string-equal py-which-bufname "Python")
1379 (start-process py-which-bufname buf py-which-shell arg file)
1381 (py-postprocess-output-buffer buf)
1382 ;; TBD: clean up the temporary file!
1384 ;; if the Python interpreter shell is running, queue it up for
1387 ;; use the existing python shell
1390 (write-region (point-min) (point-max) file nil 'nomsg))
1391 (if (not py-file-queue)
1392 (py-execute-file proc file)
1393 (message "File %s queued for execution" file))
1394 (setq py-file-queue (append py-file-queue (list file)))
1395 (setq py-exception-buffer (cons file (current-buffer))))
1397 ;; TBD: a horrible hack, buy why create new Custom variables?
1398 (let ((cmd (concat py-which-shell
1399 (if (string-equal py-which-bufname "JPython")
1401 ;; otherwise either run it synchronously in a subprocess
1404 (shell-command-on-region (point-min) (point-max)
1405 cmd py-output-buffer))
1406 ;; shell-command-on-region kills the output buffer if it never
1407 ;; existed and there's no output from the command
1408 (if (not (get-buffer py-output-buffer))
1409 (message "No output.")
1410 (setq py-exception-buffer (current-buffer))
1411 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1412 (pop-to-buffer py-output-buffer)
1414 (pop-to-buffer py-exception-buffer)))
1416 ;; TBD: delete the buffer
1419 ;; Clean up after ourselves.
1423 ;; Code execution commands
1424 (defun py-execute-buffer (&optional async)
1425 "Send the contents of the buffer to a Python interpreter.
1426 If the file local variable `py-master-file' is non-nil, execute the
1427 named file instead of the buffer's file.
1429 If there is a *Python* process buffer it is used. If a clipping
1430 restriction is in effect, only the accessible portion of the buffer is
1431 sent. A trailing newline will be supplied if needed.
1433 See the `\\[py-execute-region]' docs for an account of some
1434 subtleties, including the use of the optional ASYNC argument."
1437 (let* ((filename (expand-file-name py-master-file))
1438 (buffer (or (get-file-buffer filename)
1439 (find-file-noselect filename))))
1440 (set-buffer buffer)))
1441 (py-execute-region (point-min) (point-max) async))
1443 (defun py-execute-import-or-reload (&optional async)
1444 "Import the current buffer's file in a Python interpreter.
1446 If the file has already been imported, then do reload instead to get
1449 If the file's name does not end in \".py\", then do execfile instead.
1451 If the current buffer is not visiting a file, do `py-execute-buffer'
1454 If the file local variable `py-master-file' is non-nil, import or
1455 reload the named file instead of the buffer's file. The file may be
1456 saved based on the value of `py-execute-import-or-reload-save-p'.
1458 See the `\\[py-execute-region]' docs for an account of some
1459 subtleties, including the use of the optional ASYNC argument.
1461 This may be preferable to `\\[py-execute-buffer]' because:
1463 - Definitions stay in their module rather than appearing at top
1464 level, where they would clutter the global namespace and not affect
1465 uses of qualified names (MODULE.NAME).
1467 - The Python debugger gets line number information about the functions."
1469 ;; Check file local variable py-master-file
1471 (let* ((filename (expand-file-name py-master-file))
1472 (buffer (or (get-file-buffer filename)
1473 (find-file-noselect filename))))
1474 (set-buffer buffer)))
1475 (let ((file (buffer-file-name (current-buffer))))
1478 ;; Maybe save some buffers
1479 (save-some-buffers (not py-ask-about-save) nil)
1481 (if (string-match "\\.py$" file)
1482 (let ((f (file-name-sans-extension
1483 (file-name-nondirectory file))))
1484 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1486 (format "execfile(r'%s')\n" file))
1489 (py-execute-buffer async))))
1492 (defun py-execute-def-or-class (&optional async)
1493 "Send the current function or class definition to a Python interpreter.
1495 If there is a *Python* process buffer it is used.
1497 See the `\\[py-execute-region]' docs for an account of some
1498 subtleties, including the use of the optional ASYNC argument."
1501 (py-mark-def-or-class)
1502 ;; mark is before point
1503 (py-execute-region (mark) (point) async)))
1506 (defun py-execute-string (string &optional async)
1507 "Send the argument STRING to a Python interpreter.
1509 If there is a *Python* process buffer it is used.
1511 See the `\\[py-execute-region]' docs for an account of some
1512 subtleties, including the use of the optional ASYNC argument."
1513 (interactive "sExecute Python command: ")
1515 (set-buffer (get-buffer-create
1516 (generate-new-buffer-name " *Python Command*")))
1518 (py-execute-region (point-min) (point-max) async)))
1522 (defun py-jump-to-exception (file line)
1523 "Jump to the Python code in FILE at LINE."
1524 (let ((buffer (cond ((string-equal file "<stdin>")
1525 (if (consp py-exception-buffer)
1526 (cdr py-exception-buffer)
1527 py-exception-buffer))
1528 ((and (consp py-exception-buffer)
1529 (string-equal file (car py-exception-buffer)))
1530 (cdr py-exception-buffer))
1531 ((py-safe (find-file-noselect file)))
1532 ;; could not figure out what file the exception
1533 ;; is pointing to, so prompt for it
1534 (t (find-file (read-file-name "Exception file: "
1537 (pop-to-buffer buffer)
1538 ;; Force Python mode
1539 (if (not (eq major-mode 'python-mode))
1542 (message "Jumping to exception in file %s on line %d" file line)))
1544 (defun py-mouseto-exception (event)
1545 "Jump to the code which caused the Python exception at EVENT.
1546 EVENT is usually a mouse click."
1549 ((fboundp 'event-point)
1551 (let* ((point (event-point event))
1552 (buffer (event-buffer event))
1553 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1554 (info (and e (extent-property e 'py-exc-info))))
1555 (message "Event point: %d, info: %s" point info)
1557 (py-jump-to-exception (car info) (cdr info)))
1559 ;; Emacs -- Please port this!
1562 (defun py-goto-exception ()
1563 "Go to the line indicated by the traceback."
1568 (if (looking-at py-traceback-line-re)
1569 (setq file (match-string 1)
1570 line (string-to-int (match-string 2)))))
1572 (error "Not on a traceback line"))
1573 (py-jump-to-exception file line)))
1575 (defun py-find-next-exception (start buffer searchdir errwhere)
1576 "Find the next Python exception and jump to the code that caused it.
1577 START is the buffer position in BUFFER from which to begin searching
1578 for an exception. SEARCHDIR is a function, either
1579 `re-search-backward' or `re-search-forward' indicating the direction
1580 to search. ERRWHERE is used in an error message if the limit (top or
1581 bottom) of the trackback stack is encountered."
1585 (goto-char (py-point start))
1586 (if (funcall searchdir py-traceback-line-re nil t)
1587 (setq file (match-string 1)
1588 line (string-to-int (match-string 2)))))
1590 (py-jump-to-exception file line)
1591 (error "%s of traceback" errwhere))))
1593 (defun py-down-exception (&optional bottom)
1594 "Go to the next line down in the traceback.
1595 With \\[univeral-argument] (programmatically, optional argument
1596 BOTTOM), jump to the bottom (innermost) exception in the exception
1599 (let* ((proc (get-process "Python"))
1600 (buffer (if proc "*Python*" py-output-buffer)))
1602 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1603 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1605 (defun py-up-exception (&optional top)
1606 "Go to the previous line up in the traceback.
1607 With \\[universal-argument] (programmatically, optional argument TOP)
1608 jump to the top (outermost) exception in the exception stack."
1610 (let* ((proc (get-process "Python"))
1611 (buffer (if proc "*Python*" py-output-buffer)))
1613 (py-find-next-exception 'bob buffer 're-search-forward "Top")
1614 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
1617 ;; Electric deletion
1618 (defun py-electric-backspace (arg)
1619 "Delete preceding character or levels of indentation.
1620 Deletion is performed by calling the function in `py-backspace-function'
1621 with a single argument (the number of characters to delete).
1623 If point is at the leftmost column, delete the preceding newline.
1625 Otherwise, if point is at the leftmost non-whitespace character of a
1626 line that is neither a continuation line nor a non-indenting comment
1627 line, or if point is at the end of a blank line, this command reduces
1628 the indentation to match that of the line that opened the current
1629 block of code. The line that opened the block is displayed in the
1630 echo area to help you keep track of where you are. With
1631 \\[universal-argument] dedents that many blocks (but not past column
1634 Otherwise the preceding character is deleted, converting a tab to
1635 spaces if needed so that only a single column position is deleted.
1636 \\[universal-argument] specifies how many characters to delete;
1639 When used programmatically, argument ARG specifies the number of
1640 blocks to dedent, or the number of characters to delete, as indicated
1643 (if (or (/= (current-indentation) (current-column))
1645 (py-continuation-line-p)
1646 ; (not py-honor-comment-indentation)
1647 ; (looking-at "#[^ \t\n]") ; non-indenting #
1649 (funcall py-backspace-function arg)
1650 ;; else indent the same as the colon line that opened the block
1651 ;; force non-blank so py-goto-block-up doesn't ignore it
1654 (let ((base-indent 0) ; indentation of base line
1655 (base-text "") ; and text of base line
1659 (condition-case nil ; in case no enclosing block
1661 (py-goto-block-up 'no-mark)
1662 (setq base-indent (current-indentation)
1663 base-text (py-suck-up-leading-text)
1666 (setq arg (1- arg))))
1667 (delete-char 1) ; toss the dummy character
1668 (delete-horizontal-space)
1669 (indent-to base-indent)
1671 (message "Closes block: %s" base-text)))))
1674 (defun py-electric-delete (arg)
1675 "Delete preceding or following character or levels of whitespace.
1677 The behavior of this function depends on the variable
1678 `delete-key-deletes-forward'. If this variable is nil (or does not
1679 exist, as in older Emacsen and non-XEmacs versions), then this
1680 function behaves identically to \\[c-electric-backspace].
1682 If `delete-key-deletes-forward' is non-nil and is supported in your
1683 Emacs, then deletion occurs in the forward direction, by calling the
1684 function in `py-delete-function'.
1686 \\[universal-argument] (programmatically, argument ARG) specifies the
1687 number of characters to delete (default is 1)."
1689 (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
1691 (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
1692 delete-key-deletes-forward))
1693 (funcall py-delete-function arg)
1694 (py-electric-backspace arg)))
1696 ;; required for pending-del and delsel modes
1697 (put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1698 (put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1699 (put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1700 (put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1704 (defun py-indent-line (&optional arg)
1705 "Fix the indentation of the current line according to Python rules.
1706 With \\[universal-argument] (programmatically, the optional argument
1707 ARG non-nil), ignore dedenting rules for block closing statements
1708 (e.g. return, raise, break, continue, pass)
1710 This function is normally bound to `indent-line-function' so
1711 \\[indent-for-tab-command] will call it."
1713 (let* ((ci (current-indentation))
1714 (move-to-indentation-p (<= (current-column) ci))
1715 (need (py-compute-indentation (not arg))))
1716 ;; see if we need to dedent
1718 (setq need (- need py-indent-offset)))
1722 (delete-horizontal-space)
1724 (if move-to-indentation-p (back-to-indentation))))
1726 (defun py-newline-and-indent ()
1727 "Strives to act like the Emacs `newline-and-indent'.
1728 This is just `strives to' because correct indentation can't be computed
1729 from scratch for Python code. In general, deletes the whitespace before
1730 point, inserts a newline, and takes an educated guess as to how you want
1731 the new line indented."
1733 (let ((ci (current-indentation)))
1734 (if (< ci (current-column)) ; if point beyond indentation
1735 (newline-and-indent)
1736 ;; else try to act like newline-and-indent "normally" acts
1739 (move-to-column ci))))
1741 (defun py-compute-indentation (honor-block-close-p)
1742 "Compute Python indentation.
1743 When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1744 `raise', `break', `continue', and `pass' force one level of
1748 (let* ((bod (py-point 'bod))
1749 (pps (parse-partial-sexp bod (point)))
1750 (boipps (parse-partial-sexp bod (py-point 'boi)))
1753 ;; are we inside a multi-line string or comment?
1754 ((or (and (nth 3 pps) (nth 3 boipps))
1755 (and (nth 4 pps) (nth 4 boipps)))
1757 (if (not py-align-multiline-strings-p) 0
1758 ;; skip back over blank & non-indenting comment lines
1759 ;; note: will skip a blank or non-indenting comment line
1760 ;; that happens to be a continuation line too
1761 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1762 (back-to-indentation)
1764 ;; are we on a continuation line?
1765 ((py-continuation-line-p)
1766 (let ((startpos (point))
1767 (open-bracket-pos (py-nesting-level))
1768 endpos searching found state)
1769 (if open-bracket-pos
1771 ;; align with first item in list; else a normal
1772 ;; indent beyond the line with the open bracket
1773 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1774 ;; is the first list item on the same line?
1775 (skip-chars-forward " \t")
1776 (if (null (memq (following-char) '(?\n ?# ?\\)))
1777 ; yes, so line up with it
1779 ;; first list item on another line, or doesn't exist yet
1781 (while (and (< (point) startpos)
1782 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1784 (if (and (< (point) startpos)
1787 (goto-char (1+ open-bracket-pos))
1788 (forward-comment (point-max))
1790 ;; again mimic the first list item
1791 (current-indentation)
1792 ;; else they're about to enter the first item
1793 (goto-char open-bracket-pos)
1794 (setq placeholder (point))
1795 (py-goto-initial-line)
1796 (py-goto-beginning-of-tqs
1797 (save-excursion (nth 3 (parse-partial-sexp
1798 placeholder (point)))))
1799 (+ (current-indentation) py-indent-offset))))
1801 ;; else on backslash continuation line
1803 (if (py-continuation-line-p) ; on at least 3rd line in block
1804 (current-indentation) ; so just continue the pattern
1805 ;; else started on 2nd line in block, so indent more.
1806 ;; if base line is an assignment with a start on a RHS,
1807 ;; indent to 2 beyond the leftmost "="; else skip first
1808 ;; chunk of non-whitespace characters on base line, + 1 more
1811 (setq endpos (point)
1813 (back-to-indentation)
1814 (setq startpos (point))
1815 ;; look at all "=" from left to right, stopping at first
1816 ;; one not nested in a list or string
1818 (skip-chars-forward "^=" endpos)
1819 (if (= (point) endpos)
1820 (setq searching nil)
1822 (setq state (parse-partial-sexp startpos (point)))
1823 (if (and (zerop (car state)) ; not in a bracket
1824 (null (nth 3 state))) ; & not in a string
1826 (setq searching nil) ; done searching in any case
1829 (eq (following-char) ?=)
1830 (memq (char-after (- (point) 2))
1832 (if (or (not found) ; not an assignment
1833 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1835 (goto-char startpos)
1836 (skip-chars-forward "^ \t\n")))
1837 ;; if this is a continuation for a block opening
1838 ;; statement, add some extra offset.
1839 (+ (current-column) (if (py-statement-opens-block-p)
1840 py-continuation-offset 0)
1844 ;; not on a continuation line
1845 ((bobp) (current-indentation))
1847 ;; Dfn: "Indenting comment line". A line containing only a
1848 ;; comment, but which is treated like a statement for
1849 ;; indentation calculation purposes. Such lines are only
1850 ;; treated specially by the mode; they are not treated
1851 ;; specially by the Python interpreter.
1853 ;; The rules for indenting comment lines are a line where:
1854 ;; - the first non-whitespace character is `#', and
1855 ;; - the character following the `#' is whitespace, and
1856 ;; - the line is dedented with respect to (i.e. to the left
1857 ;; of) the indentation of the preceding non-blank line.
1859 ;; The first non-blank line following an indenting comment
1860 ;; line is given the same amount of indentation as the
1861 ;; indenting comment line.
1863 ;; All other comment-only lines are ignored for indentation
1866 ;; Are we looking at a comment-only line which is *not* an
1867 ;; indenting comment line? If so, we assume that it's been
1868 ;; placed at the desired indentation, so leave it alone.
1869 ;; Indenting comment lines are aligned as statements down
1871 ((and (looking-at "[ \t]*#[^ \t\n]")
1872 ;; NOTE: this test will not be performed in older Emacsen
1873 (fboundp 'forward-comment)
1874 (<= (current-indentation)
1876 (forward-comment (- (point-max)))
1877 (current-indentation))))
1878 (current-indentation))
1880 ;; else indentation based on that of the statement that
1881 ;; precedes us; use the first line of that statement to
1882 ;; establish the base, in case the user forced a non-std
1883 ;; indentation for the continuation lines (if any)
1885 ;; skip back over blank & non-indenting comment lines note:
1886 ;; will skip a blank or non-indenting comment line that
1887 ;; happens to be a continuation line too. use fast Emacs 19
1888 ;; function if it's there.
1889 (if (and (eq py-honor-comment-indentation nil)
1890 (fboundp 'forward-comment))
1891 (forward-comment (- (point-max)))
1892 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
1895 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1896 (setq done (or (bobp)
1897 (and (eq py-honor-comment-indentation t)
1899 (back-to-indentation)
1900 (not (looking-at prefix-re))
1902 (and (not (eq py-honor-comment-indentation t))
1904 (back-to-indentation)
1905 (not (zerop (current-column)))))
1908 ;; if we landed inside a string, go to the beginning of that
1909 ;; string. this handles triple quoted, multi-line spanning
1911 (py-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
1912 ;; now skip backward over continued lines
1913 (setq placeholder (point))
1914 (py-goto-initial-line)
1915 ;; we may *now* have landed in a TQS, so find the beginning of
1917 (py-goto-beginning-of-tqs
1918 (save-excursion (nth 3 (parse-partial-sexp
1919 placeholder (point)))))
1920 (+ (current-indentation)
1921 (if (py-statement-opens-block-p)
1923 (if (and honor-block-close-p (py-statement-closes-block-p))
1924 (- py-indent-offset)
1928 (defun py-guess-indent-offset (&optional global)
1929 "Guess a good value for, and change, `py-indent-offset'.
1931 By default, make a buffer-local copy of `py-indent-offset' with the
1932 new value, so that other Python buffers are not affected. With
1933 \\[universal-argument] (programmatically, optional argument GLOBAL),
1934 change the global value of `py-indent-offset'. This affects all
1935 Python buffers (that don't have their own buffer-local copy), both
1936 those currently existing and those created later in the Emacs session.
1938 Some people use a different value for `py-indent-offset' than you use.
1939 There's no excuse for such foolishness, but sometimes you have to deal
1940 with their ugly code anyway. This function examines the file and sets
1941 `py-indent-offset' to what it thinks it was when they created the
1944 Specifically, it searches forward from the statement containing point,
1945 looking for a line that opens a block of code. `py-indent-offset' is
1946 set to the difference in indentation between that line and the Python
1947 statement following it. If the search doesn't succeed going forward,
1948 it's tried again going backward."
1949 (interactive "P") ; raw prefix arg
1955 (py-goto-initial-line)
1956 (while (not (or found (eobp)))
1957 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1958 (not (py-in-literal restart)))
1959 (setq restart (point))
1960 (py-goto-initial-line)
1961 (if (py-statement-opens-block-p)
1963 (goto-char restart))))
1966 (py-goto-initial-line)
1967 (while (not (or found (bobp)))
1969 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1970 (or (py-goto-initial-line) t) ; always true -- side effect
1971 (py-statement-opens-block-p)))))
1972 (setq colon-indent (current-indentation)
1973 found (and found (zerop (py-next-statement 1)))
1974 new-value (- (current-indentation) colon-indent))
1977 (error "Sorry, couldn't guess a value for py-indent-offset")
1978 (funcall (if global 'kill-local-variable 'make-local-variable)
1980 (setq py-indent-offset new-value)
1982 (message "%s value of py-indent-offset set to %d"
1983 (if global "Global" "Local")
1987 (defun py-comment-indent-function ()
1988 "Python version of `comment-indent-function'."
1989 ;; This is required when filladapt is turned off. Without it, when
1990 ;; filladapt is not used, comments which start in column zero
1991 ;; cascade one character to the right
1994 (let ((eol (py-point 'eol)))
1995 (and comment-start-skip
1996 (re-search-forward comment-start-skip eol t)
1997 (setq eol (match-beginning 0)))
1999 (skip-chars-backward " \t")
2000 (max comment-column (+ (current-column) (if (bolp) 0 1)))
2003 (defun py-narrow-to-defun (&optional class)
2004 "Make text outside current defun invisible.
2005 The defun visible is the one that contains point or follows point.
2006 Optional CLASS is passed directly to `py-beginning-of-def-or-class'."
2010 (py-end-of-def-or-class class)
2011 (let ((end (point)))
2012 (py-beginning-of-def-or-class class)
2013 (narrow-to-region (point) end))))
2016 (defun py-shift-region (start end count)
2017 "Indent lines from START to END by COUNT spaces."
2024 (setq start (point))
2025 (indent-rigidly start end count)))
2027 (defun py-shift-region-left (start end &optional count)
2028 "Shift region of Python code to the left.
2029 The lines from the line containing the start of the current region up
2030 to (but not including) the line containing the end of the region are
2031 shifted to the left, by `py-indent-offset' columns.
2033 If a prefix argument is given, the region is instead shifted by that
2034 many columns. With no active region, dedent only the current line.
2035 You cannot dedent the region if any line is already at column zero."
2039 (arg current-prefix-arg))
2041 (list (min p m) (max p m) arg)
2042 (list p (save-excursion (forward-line 1) (point)) arg))))
2043 ;; if any line is at column zero, don't shift the region
2046 (while (< (point) end)
2047 (back-to-indentation)
2048 (if (and (zerop (current-column))
2049 (not (looking-at "\\s *$")))
2050 (error "Region is at left edge"))
2052 (py-shift-region start end (- (prefix-numeric-value
2053 (or count py-indent-offset))))
2054 (py-keep-region-active))
2056 (defun py-shift-region-right (start end &optional count)
2057 "Shift region of Python code to the right.
2058 The lines from the line containing the start of the current region up
2059 to (but not including) the line containing the end of the region are
2060 shifted to the right, by `py-indent-offset' columns.
2062 If a prefix argument is given, the region is instead shifted by that
2063 many columns. With no active region, indent only the current line."
2067 (arg current-prefix-arg))
2069 (list (min p m) (max p m) arg)
2070 (list p (save-excursion (forward-line 1) (point)) arg))))
2071 (py-shift-region start end (prefix-numeric-value
2072 (or count py-indent-offset)))
2073 (py-keep-region-active))
2075 (defun py-indent-region (start end &optional indent-offset)
2076 "Reindent a region of Python code.
2078 The lines from the line containing the start of the current region up
2079 to (but not including) the line containing the end of the region are
2080 reindented. If the first line of the region has a non-whitespace
2081 character in the first column, the first line is left alone and the
2082 rest of the region is reindented with respect to it. Else the entire
2083 region is reindented with respect to the (closest code or indenting
2084 comment) statement immediately preceding the region.
2086 This is useful when code blocks are moved or yanked, when enclosing
2087 control structures are introduced or removed, or to reformat code
2088 using a new value for the indentation offset.
2090 If a numeric prefix argument is given, it will be used as the value of
2091 the indentation offset. Else the value of `py-indent-offset' will be
2094 Warning: The region must be consistently indented before this function
2095 is called! This function does not compute proper indentation from
2096 scratch (that's impossible in Python), it merely adjusts the existing
2097 indentation to be correct in context.
2099 Warning: This function really has no idea what to do with
2100 non-indenting comment lines, and shifts them as if they were indenting
2101 comment lines. Fixing this appears to require telepathy.
2103 Special cases: whitespace is deleted from blank lines; continuation
2104 lines are shifted by the same amount their initial line was shifted,
2105 in order to preserve their relative indentation with respect to their
2106 initial line; and comment lines beginning in column 1 are ignored."
2107 (interactive "*r\nP") ; region; raw prefix arg
2109 (goto-char end) (beginning-of-line) (setq end (point-marker))
2110 (goto-char start) (beginning-of-line)
2111 (let ((py-indent-offset (prefix-numeric-value
2112 (or indent-offset py-indent-offset)))
2113 (indents '(-1)) ; stack of active indent levels
2114 (target-column 0) ; column to which to indent
2115 (base-shifted-by 0) ; amount last base line was shifted
2116 (indent-base (if (looking-at "[ \t\n]")
2117 (py-compute-indentation t)
2120 (while (< (point) end)
2121 (setq ci (current-indentation))
2122 ;; figure out appropriate target column
2124 ((or (eq (following-char) ?#) ; comment in column 1
2125 (looking-at "[ \t]*$")) ; entirely blank
2126 (setq target-column 0))
2127 ((py-continuation-line-p) ; shift relative to base line
2128 (setq target-column (+ ci base-shifted-by)))
2130 (if (> ci (car indents)) ; going deeper; push it
2131 (setq indents (cons ci indents))
2132 ;; else we should have seen this indent before
2133 (setq indents (memq ci indents)) ; pop deeper indents
2135 (error "Bad indentation in region, at line %d"
2138 (1+ (count-lines 1 (point)))))))
2139 (setq target-column (+ indent-base
2141 (- (length indents) 2))))
2142 (setq base-shifted-by (- target-column ci))))
2144 (if (/= ci target-column)
2146 (delete-horizontal-space)
2147 (indent-to target-column)))
2149 (set-marker end nil))
2151 (defun py-comment-region (beg end &optional arg)
2152 "Like `comment-region' but uses double hash (`#') comment starter."
2153 (interactive "r\nP")
2154 (let ((comment-start py-block-comment-prefix))
2155 (comment-region beg end arg)))
2158 ;; Functions for moving point
2159 (defun py-previous-statement (count)
2160 "Go to the start of the COUNTth preceding Python statement.
2161 By default, goes to the previous statement. If there is no such
2162 statement, goes to the first statement. Return count of statements
2163 left to move. `Statements' do not include blank, comment, or
2164 continuation lines."
2165 (interactive "p") ; numeric prefix arg
2166 (if (< count 0) (py-next-statement (- count))
2167 (py-goto-initial-line)
2170 (setq start (point)) ; always true -- side effect
2172 (zerop (forward-line -1))
2173 (py-goto-statement-at-or-above))
2174 (setq count (1- count)))
2175 (if (> count 0) (goto-char start)))
2178 (defun py-next-statement (count)
2179 "Go to the start of next Python statement.
2180 If the statement at point is the i'th Python statement, goes to the
2181 start of statement i+COUNT. If there is no such statement, goes to the
2182 last statement. Returns count of statements left to move. `Statements'
2183 do not include blank, comment, or continuation lines."
2184 (interactive "p") ; numeric prefix arg
2185 (if (< count 0) (py-previous-statement (- count))
2189 (setq start (point)) ; always true -- side effect
2191 (py-goto-statement-below))
2192 (setq count (1- count)))
2193 (if (> count 0) (goto-char start)))
2196 (defun py-goto-block-up (&optional nomark)
2197 "Move up to start of current block.
2198 Go to the statement that starts the smallest enclosing block; roughly
2199 speaking, this will be the closest preceding statement that ends with a
2200 colon and is indented less than the statement you started on. If
2201 successful, also sets the mark to the starting point.
2203 `\\[py-mark-block]' can be used afterward to mark the whole code
2206 If called from a program, the mark will not be set if optional argument
2209 (let ((start (point))
2212 (py-goto-initial-line)
2213 ;; if on blank or non-indenting comment line, use the preceding stmt
2214 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2216 (py-goto-statement-at-or-above)
2217 (setq found (py-statement-opens-block-p))))
2218 ;; search back for colon line indented less
2219 (setq initial-indent (current-indentation))
2220 (if (zerop initial-indent)
2222 (goto-char (point-min)))
2223 (while (not (or found (bobp)))
2226 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2227 (or (py-goto-initial-line) t) ; always true -- side effect
2228 (< (current-indentation) initial-indent)
2229 (py-statement-opens-block-p))))
2232 (or nomark (push-mark start))
2233 (back-to-indentation))
2235 (error "Enclosing block not found"))))
2237 (defun py-beginning-of-def-or-class (&optional class count)
2238 "Move point to start of `def' or `class'.
2240 Searches back for the closest preceding `def'. If you supply a prefix
2241 arg, looks for a `class' instead. The docs below assume the `def'
2242 case; just substitute `class' for `def' for the other case.
2243 Programmatically, if CLASS is `either', then moves to either `class'
2246 When second optional argument is given programmatically, move to the
2247 COUNTth start of `def'.
2249 If point is in a `def' statement already, and after the `d', simply
2250 moves point to the start of the statement.
2252 Otherwise (i.e. when point is not in a `def' statement, or at or
2253 before the `d' of a `def' statement), searches for the closest
2254 preceding `def' statement, and leaves point at its start. If no such
2255 statement can be found, leaves point at the start of the buffer.
2257 Returns t iff a `def' statement is found by these rules.
2259 Note that doing this command repeatedly will take you closer to the
2260 start of the buffer each time.
2262 To mark the current `def', see `\\[py-mark-def-or-class]'."
2263 (interactive "P") ; raw prefix arg
2264 (setq count (or count 1))
2265 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2266 (start-of-line (goto-char (py-point 'bol)))
2267 (start-of-stmt (goto-char (py-point 'bos)))
2268 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2269 (class "^[ \t]*class\\>")
2270 (t "^[ \t]*def\\>")))
2272 ;; searching backward
2273 (if (and (< 0 count)
2274 (or (/= start-of-stmt start-of-line)
2275 (not at-or-before-p)))
2278 (if (and (> 0 count)
2279 (zerop (current-column))
2280 (looking-at start-re))
2282 (if (re-search-backward start-re nil 'move count)
2283 (goto-char (match-beginning 0)))))
2285 ;; Backwards compatibility
2286 (defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
2288 (defun py-end-of-def-or-class (&optional class count)
2289 "Move point beyond end of `def' or `class' body.
2291 By default, looks for an appropriate `def'. If you supply a prefix
2292 arg, looks for a `class' instead. The docs below assume the `def'
2293 case; just substitute `class' for `def' for the other case.
2294 Programmatically, if CLASS is `either', then moves to either `class'
2297 When second optional argument is given programmatically, move to the
2298 COUNTth end of `def'.
2300 If point is in a `def' statement already, this is the `def' we use.
2302 Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2303 contains the statement you started on, that's the `def' we use.
2305 Otherwise, we search forward for the closest following `def', and use that.
2307 If a `def' can be found by these rules, point is moved to the start of
2308 the line immediately following the `def' block, and the position of the
2309 start of the `def' is returned.
2311 Else point is moved to the end of the buffer, and nil is returned.
2313 Note that doing this command repeatedly will take you closer to the
2314 end of the buffer each time.
2316 To mark the current `def', see `\\[py-mark-def-or-class]'."
2317 (interactive "P") ; raw prefix arg
2318 (if (and count (/= count 1))
2319 (py-beginning-of-def-or-class (- 1 count)))
2320 (let ((start (progn (py-goto-initial-line) (point)))
2321 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2325 ;; move point to start of appropriate def/class
2326 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2327 (setq state 'at-beginning)
2328 ;; else see if py-beginning-of-def-or-class hits container
2329 (if (and (py-beginning-of-def-or-class class)
2330 (progn (py-goto-beyond-block)
2332 (setq state 'at-end)
2333 ;; else search forward
2335 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2336 (progn (setq state 'at-beginning)
2337 (beginning-of-line)))))
2339 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2340 ((eq state 'at-end) t)
2341 ((eq state 'not-found) nil)
2342 (t (error "Internal error in `py-end-of-def-or-class'")))))
2344 ;; Backwards compabitility
2345 (defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
2348 ;; Functions for marking regions
2349 (defun py-mark-block (&optional extend just-move)
2350 "Mark following block of lines. With prefix arg, mark structure.
2351 Easier to use than explain. It sets the region to an `interesting'
2352 block of succeeding lines. If point is on a blank line, it goes down to
2353 the next non-blank line. That will be the start of the region. The end
2354 of the region depends on the kind of line at the start:
2356 - If a comment, the region will include all succeeding comment lines up
2357 to (but not including) the next non-comment line (if any).
2359 - Else if a prefix arg is given, and the line begins one of these
2362 if elif else try except finally for while def class
2364 the region will be set to the body of the structure, including
2365 following blocks that `belong' to it, but excluding trailing blank
2366 and comment lines. E.g., if on a `try' statement, the `try' block
2367 and all (if any) of the following `except' and `finally' blocks
2368 that belong to the `try' structure will be in the region. Ditto
2369 for if/elif/else, for/else and while/else structures, and (a bit
2370 degenerate, since they're always one-block structures) def and
2373 - Else if no prefix argument is given, and the line begins a Python
2374 block (see list above), and the block is not a `one-liner' (i.e.,
2375 the statement ends with a colon, not with code), the region will
2376 include all succeeding lines up to (but not including) the next
2377 code statement (if any) that's indented no more than the starting
2378 line, except that trailing blank and comment lines are excluded.
2379 E.g., if the starting line begins a multi-statement `def'
2380 structure, the region will be set to the full function definition,
2381 but without any trailing `noise' lines.
2383 - Else the region will include all succeeding lines up to (but not
2384 including) the next blank line, or code or indenting-comment line
2385 indented strictly less than the starting line. Trailing indenting
2386 comment lines are included in this case, but not trailing blank
2389 A msg identifying the location of the mark is displayed in the echo
2390 area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2392 If called from a program, optional argument EXTEND plays the role of
2393 the prefix arg, and if optional argument JUST-MOVE is not nil, just
2394 moves to the end of the block (& does not set mark or display a msg)."
2395 (interactive "P") ; raw prefix arg
2396 (py-goto-initial-line)
2397 ;; skip over blank lines
2399 (looking-at "[ \t]*$") ; while blank line
2400 (not (eobp))) ; & somewhere to go
2403 (error "Hit end of buffer without finding a non-blank stmt"))
2404 (let ((initial-pos (point))
2405 (initial-indent (current-indentation))
2406 last-pos ; position of last stmt in region
2408 '((if elif else) (elif elif else) (else)
2409 (try except finally) (except except) (finally)
2410 (for else) (while else)
2412 first-symbol next-symbol)
2415 ;; if comment line, suck up the following comment lines
2416 ((looking-at "[ \t]*#")
2417 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2418 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2419 (setq last-pos (point)))
2421 ;; else if line is a block line and EXTEND given, suck up
2422 ;; the whole structure
2424 (setq first-symbol (py-suck-up-first-keyword) )
2425 (assq first-symbol followers))
2427 (or (py-goto-beyond-block) t) ; side effect
2428 (forward-line -1) ; side effect
2429 (setq last-pos (point)) ; side effect
2430 (py-goto-statement-below)
2431 (= (current-indentation) initial-indent)
2432 (setq next-symbol (py-suck-up-first-keyword))
2433 (memq next-symbol (cdr (assq first-symbol followers))))
2434 (setq first-symbol next-symbol)))
2436 ;; else if line *opens* a block, search for next stmt indented <=
2437 ((py-statement-opens-block-p)
2439 (setq last-pos (point)) ; always true -- side effect
2440 (py-goto-statement-below)
2441 (> (current-indentation) initial-indent))
2444 ;; else plain code line; stop at next blank line, or stmt or
2445 ;; indenting comment line indented <
2448 (setq last-pos (point)) ; always true -- side effect
2449 (or (py-goto-beyond-final-line) t)
2450 (not (looking-at "[ \t]*$")) ; stop at blank line
2452 (>= (current-indentation) initial-indent)
2453 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2456 ;; skip to end of last stmt
2457 (goto-char last-pos)
2458 (py-goto-beyond-final-line)
2460 ;; set mark & display
2463 (push-mark (point) 'no-msg)
2465 (message "Mark set after: %s" (py-suck-up-leading-text))
2466 (goto-char initial-pos))))
2468 (defun py-mark-def-or-class (&optional class)
2469 "Set region to body of def (or class, with prefix arg) enclosing point.
2470 Pushes the current mark, then point, on the mark ring (all language
2471 modes do this, but although it's handy it's never documented ...).
2473 In most Emacs language modes, this function bears at least a
2474 hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2475 `\\[py-beginning-of-def-or-class]'.
2477 And in earlier versions of Python mode, all 3 were tightly connected.
2478 Turned out that was more confusing than useful: the `goto start' and
2479 `goto end' commands are usually used to search through a file, and
2480 people expect them to act a lot like `search backward' and `search
2481 forward' string-search commands. But because Python `def' and `class'
2482 can nest to arbitrary levels, finding the smallest def containing
2483 point cannot be done via a simple backward search: the def containing
2484 point may not be the closest preceding def, or even the closest
2485 preceding def that's indented less. The fancy algorithm required is
2486 appropriate for the usual uses of this `mark' command, but not for the
2489 So the def marked by this command may not be the one either of the
2490 `goto' commands find: If point is on a blank or non-indenting comment
2491 line, moves back to start of the closest preceding code statement or
2492 indenting comment line. If this is a `def' statement, that's the def
2493 we use. Else searches for the smallest enclosing `def' block and uses
2494 that. Else signals an error.
2496 When an enclosing def is found: The mark is left immediately beyond
2497 the last line of the def block. Point is left at the start of the
2498 def, except that: if the def is preceded by a number of comment lines
2499 followed by (at most) one optional blank line, point is left at the
2500 start of the comments; else if the def is preceded by a blank line,
2501 point is left at its start.
2503 The intent is to mark the containing def/class and its associated
2504 documentation, to make moving and duplicating functions and classes
2506 (interactive "P") ; raw prefix arg
2507 (let ((start (point))
2508 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2512 (if (not (py-go-up-tree-to-keyword which))
2513 (progn (goto-char start)
2514 (error "Enclosing %s not found"
2515 (if (eq class 'either)
2518 ;; else enclosing def/class found
2519 (setq start (point))
2520 (py-goto-beyond-block)
2523 (if (zerop (forward-line -1)) ; if there is a preceding line
2525 (if (looking-at "[ \t]*$") ; it's blank
2526 (setq start (point)) ; so reset start point
2527 (goto-char start)) ; else try again
2528 (if (zerop (forward-line -1))
2529 (if (looking-at "[ \t]*#") ; a comment
2530 ;; look back for non-comment line
2531 ;; tricky: note that the regexp matches a blank
2532 ;; line, cuz \n is in the 2nd character class
2534 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2536 ;; no comment, so go back
2537 (goto-char start)))))))
2538 (exchange-point-and-mark)
2539 (py-keep-region-active))
2541 ;; ripped from cc-mode
2542 (defun py-forward-into-nomenclature (&optional arg)
2543 "Move forward to end of a nomenclature section or word.
2544 With \\[universal-argument] (programmatically, optional argument ARG),
2545 do it that many times.
2547 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2549 (let ((case-fold-search nil))
2552 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2554 (while (and (< arg 0)
2556 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
2559 (setq arg (1+ arg)))))
2560 (py-keep-region-active))
2562 (defun py-backward-into-nomenclature (&optional arg)
2563 "Move backward to beginning of a nomenclature section or word.
2564 With optional ARG, move that many times. If ARG is negative, move
2567 A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2569 (py-forward-into-nomenclature (- arg))
2570 (py-keep-region-active))
2574 ;; pdbtrack functions
2575 (defun py-pdbtrack-toggle-stack-tracking (arg)
2577 (if (not (get-buffer-process (current-buffer)))
2578 (error "No process associated with buffer '%s'" (current-buffer)))
2579 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2581 (zerop (setq arg (prefix-numeric-value arg))))
2582 (setq py-pdbtrack-do-tracking-p (not py-pdbtrack-do-tracking-p))
2583 (setq py-pdbtrack-do-tracking-p (> arg 0)))
2584 (message "%sabled Python's pdbtrack"
2585 (if py-pdbtrack-do-tracking-p "En" "Dis")))
2587 (defun turn-on-pdbtrack ()
2589 (py-pdbtrack-toggle-stack-tracking 1))
2591 (defun turn-off-pdbtrack ()
2593 (py-pdbtrack-toggle-stack-tracking 0))
2597 ;; Documentation functions
2599 ;; dump the long form of the mode blurb; does the usual doc escapes,
2600 ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2601 ;; out of the right places, along with the keys they're on & current
2603 (defun py-dump-help-string (str)
2604 (with-output-to-temp-buffer "*Help*"
2605 (let ((locals (buffer-local-variables))
2606 funckind funcname func funcdoc
2607 (start 0) mstart end
2609 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2610 (setq mstart (match-beginning 0) end (match-end 0)
2611 funckind (substring str (match-beginning 1) (match-end 1))
2612 funcname (substring str (match-beginning 2) (match-end 2))
2613 func (intern funcname))
2614 (princ (substitute-command-keys (substring str start mstart)))
2616 ((equal funckind "c") ; command
2617 (setq funcdoc (documentation func)
2620 (mapconcat 'key-description
2621 (where-is-internal func py-mode-map)
2623 ((equal funckind "v") ; variable
2624 (setq funcdoc (documentation-property func 'variable-documentation)
2625 keys (if (assq func locals)
2627 "Local/Global values: "
2628 (prin1-to-string (symbol-value func))
2630 (prin1-to-string (default-value func)))
2633 (prin1-to-string (symbol-value func))))))
2635 (error "Error in py-dump-help-string, tag `%s'" funckind)))
2636 (princ (format "\n-> %s:\t%s\t%s\n\n"
2637 (if (equal funckind "c") "Command" "Variable")
2642 (princ (substitute-command-keys (substring str start))))
2643 (print-help-return-message)))
2645 (defun py-describe-mode ()
2646 "Dump long form of Python-mode docs."
2648 (py-dump-help-string "Major mode for editing Python files.
2649 Knows about Python indentation, tokens, comments and continuation lines.
2650 Paragraphs are separated by blank lines only.
2652 Major sections below begin with the string `@'; specific function and
2653 variable docs begin with `->'.
2655 @EXECUTING PYTHON CODE
2657 \\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
2658 \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2659 \\[py-execute-region]\tsends the current region
2660 \\[py-execute-def-or-class]\tsends the current function or class definition
2661 \\[py-execute-string]\tsends an arbitrary string
2662 \\[py-shell]\tstarts a Python interpreter window; this will be used by
2663 \tsubsequent Python execution commands
2664 %c:py-execute-import-or-reload
2665 %c:py-execute-buffer
2666 %c:py-execute-region
2667 %c:py-execute-def-or-class
2668 %c:py-execute-string
2673 py-indent-offset\tindentation increment
2674 py-block-comment-prefix\tcomment string used by comment-region
2676 py-python-command\tshell command to invoke Python interpreter
2677 py-temp-directory\tdirectory used for temp files (if needed)
2679 py-beep-if-tab-change\tring the bell if tab-width is changed
2681 %v:py-block-comment-prefix
2682 %v:py-python-command
2683 %v:py-temp-directory
2684 %v:py-beep-if-tab-change
2688 Each physical line in the file is either a `continuation line' (the
2689 preceding line ends with a backslash that's not part of a comment, or
2690 the paren/bracket/brace nesting level at the start of the line is
2691 non-zero, or both) or an `initial line' (everything else).
2693 An initial line is in turn a `blank line' (contains nothing except
2694 possibly blanks or tabs), a `comment line' (leftmost non-blank
2695 character is `#'), or a `code line' (everything else).
2699 Although all comment lines are treated alike by Python, Python mode
2700 recognizes two kinds that act differently with respect to indentation.
2702 An `indenting comment line' is a comment line with a blank, tab or
2703 nothing after the initial `#'. The indentation commands (see below)
2704 treat these exactly as if they were code lines: a line following an
2705 indenting comment line will be indented like the comment line. All
2706 other comment lines (those with a non-whitespace character immediately
2707 following the initial `#') are `non-indenting comment lines', and
2708 their indentation is ignored by the indentation commands.
2710 Indenting comment lines are by far the usual case, and should be used
2711 whenever possible. Non-indenting comment lines are useful in cases
2714 \ta = b # a very wordy single-line comment that ends up being
2715 \t #... continued onto another line
2718 ##\t\tprint 'panic!' # old code we've `commented out'
2721 Since the `#...' and `##' comment lines have a non-whitespace
2722 character following the initial `#', Python mode ignores them when
2723 computing the proper indentation for the next line.
2725 Continuation Lines and Statements
2727 The Python-mode commands generally work on statements instead of on
2728 individual lines, where a `statement' is a comment or blank line, or a
2729 code line and all of its following continuation lines (if any)
2730 considered as a single logical unit. The commands in this mode
2731 generally (when it makes sense) automatically move to the start of the
2732 statement containing point, even if point happens to be in the middle
2733 of some continuation line.
2738 Primarily for entering new code:
2739 \t\\[indent-for-tab-command]\t indent line appropriately
2740 \t\\[py-newline-and-indent]\t insert newline, then indent
2741 \t\\[py-electric-backspace]\t reduce indentation, or delete single character
2743 Primarily for reindenting existing code:
2744 \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2745 \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2747 \t\\[py-indent-region]\t reindent region to match its context
2748 \t\\[py-shift-region-left]\t shift region left by py-indent-offset
2749 \t\\[py-shift-region-right]\t shift region right by py-indent-offset
2751 Unlike most programming languages, Python uses indentation, and only
2752 indentation, to specify block structure. Hence the indentation supplied
2753 automatically by Python-mode is just an educated guess: only you know
2754 the block structure you intend, so only you can supply correct
2757 The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2758 the indentation of preceding statements. E.g., assuming
2759 py-indent-offset is 4, after you enter
2760 \tif a > 0: \\[py-newline-and-indent]
2761 the cursor will be moved to the position of the `_' (_ is not a
2762 character in the file, it's just used here to indicate the location of
2766 If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2771 Python-mode cannot know whether that's what you intended, or whether
2775 was your intent. In general, Python-mode either reproduces the
2776 indentation of the (closest code or indenting-comment) preceding
2777 statement, or adds an extra py-indent-offset blanks if the preceding
2778 statement has `:' as its last significant (non-whitespace and non-
2779 comment) character. If the suggested indentation is too much, use
2780 \\[py-electric-backspace] to reduce it.
2782 Continuation lines are given extra indentation. If you don't like the
2783 suggested indentation, change it to something you do like, and Python-
2784 mode will strive to indent later lines of the statement in the same way.
2786 If a line is a continuation line by virtue of being in an unclosed
2787 paren/bracket/brace structure (`list', for short), the suggested
2788 indentation depends on whether the current line contains the first item
2789 in the list. If it does, it's indented py-indent-offset columns beyond
2790 the indentation of the line containing the open bracket. If you don't
2791 like that, change it by hand. The remaining items in the list will mimic
2792 whatever indentation you give to the first item.
2794 If a line is a continuation line because the line preceding it ends with
2795 a backslash, the third and following lines of the statement inherit their
2796 indentation from the line preceding them. The indentation of the second
2797 line in the statement depends on the form of the first (base) line: if
2798 the base line is an assignment statement with anything more interesting
2799 than the backslash following the leftmost assigning `=', the second line
2800 is indented two columns beyond that `='. Else it's indented to two
2801 columns beyond the leftmost solid chunk of non-whitespace characters on
2804 Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2805 repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2806 structure you intend.
2807 %c:indent-for-tab-command
2808 %c:py-newline-and-indent
2809 %c:py-electric-backspace
2812 The next function may be handy when editing code you didn't write:
2813 %c:py-guess-indent-offset
2816 The remaining `indent' functions apply to a region of Python code. They
2817 assume the block structure (equals indentation, in Python) of the region
2818 is correct, and alter the indentation in various ways while preserving
2819 the block structure:
2821 %c:py-shift-region-left
2822 %c:py-shift-region-right
2824 @MARKING & MANIPULATING REGIONS OF CODE
2826 \\[py-mark-block]\t mark block of lines
2827 \\[py-mark-def-or-class]\t mark smallest enclosing def
2828 \\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
2829 \\[comment-region]\t comment out region of code
2830 \\[universal-argument] \\[comment-region]\t uncomment region of code
2832 %c:py-mark-def-or-class
2837 \\[py-previous-statement]\t move to statement preceding point
2838 \\[py-next-statement]\t move to statement following point
2839 \\[py-goto-block-up]\t move up to start of current block
2840 \\[py-beginning-of-def-or-class]\t move to start of def
2841 \\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2842 \\[py-end-of-def-or-class]\t move to end of def
2843 \\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
2845 The first two move to one statement beyond the statement that contains
2846 point. A numeric prefix argument tells them to move that many
2847 statements instead. Blank lines, comment lines, and continuation lines
2848 do not count as `statements' for these commands. So, e.g., you can go
2849 to the first code statement in a file by entering
2850 \t\\[beginning-of-buffer]\t to move to the top of the file
2851 \t\\[py-next-statement]\t to skip over initial comments and blank lines
2852 Or do `\\[py-previous-statement]' with a huge prefix argument.
2853 %c:py-previous-statement
2854 %c:py-next-statement
2856 %c:py-beginning-of-def-or-class
2857 %c:py-end-of-def-or-class
2859 @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2861 `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2863 `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2864 overall class and def structure of a module.
2866 `\\[back-to-indentation]' moves point to a line's first non-blank character.
2868 `\\[indent-relative]' is handy for creating odd indentation.
2872 If you don't like the default value of a variable, change its value to
2873 whatever you do like by putting a `setq' line in your .emacs file.
2874 E.g., to set the indentation increment to 4, put this line in your
2876 \t(setq py-indent-offset 4)
2877 To see the value of a variable, do `\\[describe-variable]' and enter the variable
2880 When entering a key sequence like `C-c C-n', it is not necessary to
2881 release the CONTROL key after doing the `C-c' part -- it suffices to
2882 press the CONTROL key, press and release `c' (while still holding down
2883 CONTROL), press and release `n' (while still holding down CONTROL), &
2884 then release CONTROL.
2886 Entering Python mode calls with no arguments the value of the variable
2887 `python-mode-hook', if that value exists and is not nil; for backward
2888 compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2889 the Elisp manual for details.
2891 Obscure: When python-mode is first loaded, it looks for all bindings
2892 to newline-and-indent in the global keymap, and shadows them with
2893 local bindings to py-newline-and-indent."))
2897 (defvar py-parse-state-re
2899 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2903 (defun py-parse-state ()
2904 "Return the parse state at point (see `parse-partial-sexp' docs)."
2906 (let ((here (point))
2907 in-listcomp pps done)
2909 ;; back up to the first preceding line (if any; else start of
2910 ;; buffer) that begins with a popular Python keyword, or a
2911 ;; non- whitespace and non-comment character. These are good
2912 ;; places to start parsing to see whether where we started is
2913 ;; at a non-zero nesting level. It may be slow for people who
2914 ;; write huge code blocks or huge lists ... tough beans.
2915 (re-search-backward py-parse-state-re nil 'move)
2916 ;; Watch out for landing inside a list comprehension
2918 (if (and (looking-at "[ \t]*\\<\\(if\\|for\\)\\>")
2919 (py-safe (progn (up-list -1) t))
2920 (eq (char-after) ?\[))
2921 (setq in-listcomp (point))
2922 (setq in-listcomp nil)))
2924 ;; In XEmacs, we have a much better way to test for whether
2925 ;; we're in a triple-quoted string or not. Emacs does not
2926 ;; have this built-in function, which is its loss because
2927 ;; without scanning from the beginning of the buffer, there's
2928 ;; no accurate way to determine this otherwise.
2929 (if (not (fboundp 'buffer-syntactic-context))
2932 (save-excursion (setq pps (parse-partial-sexp (point) here)))
2933 ;; make sure we don't land inside a triple-quoted string
2934 (setq done (or (not (nth 3 pps))
2936 ;; Just go ahead and short circuit the test back to the
2937 ;; beginning of the buffer. This will be slow, but not
2938 ;; nearly as slow as looping through many
2939 ;; re-search-backwards.
2941 (goto-char (point-min))))
2943 (setq done (or (not (buffer-syntactic-context))
2946 (goto-char in-listcomp)
2949 (setq pps (parse-partial-sexp (point) here)))
2953 (defun py-nesting-level ()
2954 "Return the buffer position of the last unclosed enclosing list.
2955 If nesting level is zero, return nil."
2956 (let ((status (py-parse-state)))
2957 (if (zerop (car status))
2959 (car (cdr status))))) ; char# of open bracket
2961 (defun py-backslash-continuation-line-p ()
2962 "Return t iff preceding line ends with backslash that is not in a comment."
2966 ;; use a cheap test first to avoid the regexp if possible
2967 ;; use 'eq' because char-after may return nil
2968 (eq (char-after (- (point) 2)) ?\\ )
2969 ;; make sure; since eq test passed, there is a preceding line
2970 (forward-line -1) ; always true -- side effect
2971 (looking-at py-continued-re))))
2973 (defun py-continuation-line-p ()
2974 "Return t iff current line is a continuation line."
2977 (or (py-backslash-continuation-line-p)
2978 (py-nesting-level))))
2980 (defun py-goto-beginning-of-tqs (delim)
2981 "Go to the beginning of the triple quoted string we find ourselves in.
2982 DELIM is the TQS string delimiter character we're searching backwards
2984 (let ((skip (and delim (make-string 1 delim)))
2989 (py-safe (search-backward skip))
2990 (setq continue (and (not (bobp))
2991 (= (char-before) ?\\))))
2992 (if (and (= (char-before) delim)
2993 (= (char-before (1- (point))) delim))
2994 (setq skip (make-string 3 delim))))
2995 ;; we're looking at a triple-quoted string
2996 (py-safe (search-backward skip)))))
2998 (defun py-goto-initial-line ()
2999 "Go to the initial line of the current statement.
3000 Usually this is the line we're on, but if we're on the 2nd or
3001 following lines of a continuation block, we need to go up to the first
3003 ;; Tricky: We want to avoid quadratic-time behavior for long
3004 ;; continued blocks, whether of the backslash or open-bracket
3005 ;; varieties, or a mix of the two. The following manages to do that
3006 ;; in the usual cases.
3008 ;; Also, if we're sitting inside a triple quoted string, this will
3009 ;; drop us at the line that begins the string.
3010 (let (open-bracket-pos)
3011 (while (py-continuation-line-p)
3013 (if (py-backslash-continuation-line-p)
3014 (while (py-backslash-continuation-line-p)
3016 ;; else zip out of nested brackets/braces/parens
3017 (while (setq open-bracket-pos (py-nesting-level))
3018 (goto-char open-bracket-pos)))))
3019 (beginning-of-line))
3021 (defun py-goto-beyond-final-line ()
3022 "Go to the point just beyond the fine line of the current statement.
3023 Usually this is the start of the next line, but if this is a
3024 multi-line statement we need to skip over the continuation lines."
3025 ;; Tricky: Again we need to be clever to avoid quadratic time
3028 ;; XXX: Not quite the right solution, but deals with multi-line doc
3030 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
3031 (goto-char (match-end 0)))
3035 (while (and (py-continuation-line-p)
3037 ;; skip over the backslash flavor
3038 (while (and (py-backslash-continuation-line-p)
3041 ;; if in nest, zip to the end of the nest
3042 (setq state (py-parse-state))
3043 (if (and (not (zerop (car state)))
3046 (parse-partial-sexp (point) (point-max) 0 nil state)
3047 (forward-line 1))))))
3049 (defun py-statement-opens-block-p ()
3050 "Return t iff the current statement opens a block.
3051 I.e., iff it ends with a colon that is not in a comment. Point should
3052 be at the start of a statement."
3054 (let ((start (point))
3055 (finish (progn (py-goto-beyond-final-line) (1- (point))))
3061 ;; look for a colon with nothing after it except whitespace, and
3063 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
3065 (if (eq (point) finish) ; note: no `else' clause; just
3066 ; keep searching if we're not at
3068 ;; sure looks like it opens a block -- but it might
3071 (setq searching nil) ; search is done either way
3072 (setq state (parse-partial-sexp start
3073 (match-beginning 0)))
3074 (setq answer (not (nth 4 state)))))
3075 ;; search failed: couldn't find another interesting colon
3076 (setq searching nil)))
3079 (defun py-statement-closes-block-p ()
3080 "Return t iff the current statement closes a block.
3081 I.e., if the line starts with `return', `raise', `break', `continue',
3082 and `pass'. This doesn't catch embedded statements."
3083 (let ((here (point)))
3084 (py-goto-initial-line)
3085 (back-to-indentation)
3087 (looking-at (concat py-block-closing-keywords-re "\\>"))
3090 (defun py-goto-beyond-block ()
3091 "Go to point just beyond the final line of block begun by the current line.
3092 This is the same as where `py-goto-beyond-final-line' goes unless
3093 we're on colon line, in which case we go to the end of the block.
3094 Assumes point is at the beginning of the line."
3095 (if (py-statement-opens-block-p)
3096 (py-mark-block nil 'just-move)
3097 (py-goto-beyond-final-line)))
3099 (defun py-goto-statement-at-or-above ()
3100 "Go to the start of the first statement at or preceding point.
3101 Return t if there is such a statement, otherwise nil. `Statement'
3102 does not include blank lines, comments, or continuation lines."
3103 (py-goto-initial-line)
3104 (if (looking-at py-blank-or-comment-re)
3105 ;; skip back over blank & comment lines
3106 ;; note: will skip a blank or comment line that happens to be
3107 ;; a continuation line too
3108 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
3109 (progn (py-goto-initial-line) t)
3113 (defun py-goto-statement-below ()
3114 "Go to start of the first statement following the statement containing point.
3115 Return t if there is such a statement, otherwise nil. `Statement'
3116 does not include blank lines, comments, or continuation lines."
3118 (let ((start (point)))
3119 (py-goto-beyond-final-line)
3121 (looking-at py-blank-or-comment-re)
3125 (progn (goto-char start) nil)
3128 (defun py-go-up-tree-to-keyword (key)
3129 "Go to begining of statement starting with KEY, at or preceding point.
3131 KEY is a regular expression describing a Python keyword. Skip blank
3132 lines and non-indenting comments. If the statement found starts with
3133 KEY, then stop, otherwise go back to first enclosing block starting
3134 with KEY. If successful, leave point at the start of the KEY line and
3135 return t. Otherwise, leav point at an undefined place and return nil."
3136 ;; skip blanks and non-indenting #
3137 (py-goto-initial-line)
3139 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3140 (zerop (forward-line -1))) ; go back
3142 (py-goto-initial-line)
3143 (let* ((re (concat "[ \t]*" key "\\b"))
3144 (case-fold-search nil) ; let* so looking-at sees this
3145 (found (looking-at re))
3147 (while (not (or found dead))
3148 (condition-case nil ; in case no enclosing block
3149 (py-goto-block-up 'no-mark)
3150 (error (setq dead t)))
3151 (or dead (setq found (looking-at re))))
3155 (defun py-suck-up-leading-text ()
3156 "Return string in buffer from start of indentation to end of line.
3157 Prefix with \"...\" if leading whitespace was skipped."
3159 (back-to-indentation)
3161 (if (bolp) "" "...")
3162 (buffer-substring (point) (progn (end-of-line) (point))))))
3164 (defun py-suck-up-first-keyword ()
3165 "Return first keyword on the line as a Lisp symbol.
3166 `Keyword' is defined (essentially) as the regular expression
3167 ([a-z]+). Returns nil if none was found."
3168 (let ((case-fold-search nil))
3169 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
3170 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3173 (defun py-current-defun ()
3174 "Python value for `add-log-current-defun-function'.
3175 This tells add-log.el how to find the current function/method/variable."
3177 (if (re-search-backward py-defun-start-re nil t)
3178 (or (match-string 3)
3179 (let ((method (match-string 2)))
3180 (if (and (not (zerop (length (match-string 1))))
3181 (re-search-backward py-class-start-re nil t))
3182 (concat (match-string 1) "." method)
3187 (defconst py-help-address "python-mode@python.org"
3188 "Address accepting submission of bug reports.")
3190 (defun py-version ()
3191 "Echo the current version of `python-mode' in the minibuffer."
3193 (message "Using `python-mode' version %s" py-version)
3194 (py-keep-region-active))
3196 ;; only works under Emacs 19
3198 ; (require 'reporter))
3200 (defun py-submit-bug-report (enhancement-p)
3201 "Submit via mail a bug report on `python-mode'.
3202 With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3203 non-nil) just submit an enhancement request."
3205 (list (not (y-or-n-p
3206 "Is this a bug report (hit `n' to send other comments)? "))))
3207 (let ((reporter-prompt-for-summary-p (if enhancement-p
3208 "(Very) brief summary: "
3211 (reporter-submit-bug-report
3212 py-help-address ;address
3213 (concat "python-mode " py-version) ;pkgname
3215 (if enhancement-p nil
3218 py-block-comment-prefix
3220 py-beep-if-tab-change))
3223 "Dear Barry,") ;salutation
3224 (if enhancement-p nil
3227 "Please replace this text with a sufficiently large code sample\n\
3228 and an exact recipe so that I can reproduce your problem. Failure\n\
3229 to do so may mean a greater delay in fixing your bug.\n\n")
3230 (exchange-point-and-mark)
3231 (py-keep-region-active))))
3234 (defun py-kill-emacs-hook ()
3235 "Delete files in `py-file-queue'.
3236 These are Python temporary files awaiting execution."
3237 (mapcar #'(lambda (filename)
3238 (py-safe (delete-file filename)))
3241 ;; arrange to kill temp files when Emacs exists
3242 (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
3243 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
3245 ;; Add a designator to the minor mode strings
3246 (or (assq 'py-pdbtrack-minor-mode-string minor-mode-alist)
3247 (push '(py-pdbtrack-is-tracking-p py-pdbtrack-minor-mode-string)
3252 (provide 'python-mode)
3253 ;;; python-mode.el ends here