home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Misc / python-mode.el < prev    next >
Encoding:
Text File  |  2000-10-25  |  115.4 KB  |  3,127 lines

  1. ;;; python-mode.el --- Major mode for editing Python programs
  2.  
  3. ;; Copyright (C) 1992,1993,1994  Tim Peters
  4.  
  5. ;; Author: 1995-1998 Barry A. Warsaw
  6. ;;         1992-1994 Tim Peters
  7. ;; Maintainer: python-mode@python.org
  8. ;; Created:    Feb 1992
  9. ;; Keywords:   python languages oop
  10.  
  11. (defconst py-version "$Revision: 3.107 $"
  12.   "`python-mode' version number.")
  13.  
  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.
  19.  
  20. ;;; Commentary:
  21.  
  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 :-)
  27.  
  28. ;; This version of python-mode.el is no longer compatible with Emacs
  29. ;; 18.  I am striving to maintain compatibility with the X/Emacs 19
  30. ;; lineage but as time goes on that becomes more and more difficult.
  31. ;; I current recommend that you upgrade to the latest stable released
  32. ;; version of your favorite branch: Emacs 20.3 or better, or XEmacs
  33. ;; 20.4 or better (XEmacs 21.0 is in beta testing as of this writing
  34. ;; 27-Oct-1998 appears to work fine with this version of
  35. ;; python-mode.el).  Even Windows users should be using at least
  36. ;; NTEmacs 20.3, and XEmacs 21.0 will work very nicely on Windows when
  37. ;; it is released.
  38.  
  39. ;; FOR MORE INFORMATION:
  40.  
  41. ;; For more information on installing python-mode.el, especially with
  42. ;; respect to compatibility information, please see
  43. ;;
  44. ;;     http://www.python.org/emacs/python-mode/
  45. ;;
  46. ;; This site also contains links to other packages that you might find 
  47. ;; useful, such as pdb interfaces, OO-Browser links, etc.
  48.  
  49. ;; BUG REPORTING:
  50.  
  51. ;; To submit bug reports, use C-c C-b.  Please include a complete, but
  52. ;; concise code sample and a recipe for reproducing the bug.  Send
  53. ;; suggestions and other comments to python-mode@python.org.
  54.  
  55. ;; When in a Python mode buffer, do a C-h m for more help.  It's
  56. ;; doubtful that a texinfo manual would be very useful, but if you
  57. ;; want to contribute one, I'll certainly accept it!
  58.  
  59. ;; TO DO LIST:
  60.  
  61. ;; - Better integration with pdb.py and gud-mode for debugging.
  62. ;; - Rewrite according to GNU Emacs Lisp standards.
  63. ;; - have py-execute-region on indented code act as if the region is
  64. ;;   left justified.  Avoids syntax errors.
  65. ;; - add a py-goto-block-down, bound to C-c C-d
  66.  
  67. ;;; Code:
  68.  
  69. (require 'comint)
  70. (require 'custom)
  71. (eval-when-compile
  72.   (require 'cl)
  73.   (if (not (and (condition-case nil
  74.             (require 'custom)
  75.           (error nil))
  76.         ;; Stock Emacs 19.34 has a broken/old Custom library
  77.         ;; that does more harm than good.  Fortunately, it is
  78.         ;; missing defcustom
  79.         (fboundp 'defcustom)))
  80.       (error "STOP! STOP! STOP! STOP!
  81.  
  82. The Custom library was not found or is out of date.  A more current
  83. version is required.  Please download and install the latest version
  84. of the Custom library from:
  85.  
  86.     <http://www.dina.kvl.dk/~abraham/custom/>
  87.  
  88. See the Python Mode home page for details:
  89.  
  90.     <http://www.python.org/emacs/python-mode>
  91. ")))
  92.  
  93.  
  94.  
  95. ;; user definable variables
  96. ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  97.  
  98. (defgroup python nil
  99.   "Support for the Python programming language, <http://www.python.org/>"
  100.   :group 'languages
  101.   :prefix "py-")
  102.  
  103. (defcustom py-python-command "python"
  104.   "*Shell command used to start Python interpreter."
  105.   :type 'string
  106.   :group 'python)
  107.  
  108. (defcustom py-jpython-command "jpython"
  109.   "*Shell command used to start the JPython interpreter."
  110.   :type 'string
  111.   :group 'python
  112.   :tag "JPython Command")
  113.  
  114. (defcustom py-default-interpreter 'cpython
  115.   "*Which Python interpreter is used by default.
  116. The value for this variable can be either `cpython' or `jpython'.
  117.  
  118. When the value is `cpython', the variables `py-python-command' and
  119. `py-python-command-args' are consulted to determine the interpreter
  120. and arguments to use.
  121.  
  122. When the value is `jpython', the variables `py-jpython-command' and
  123. `py-jpython-command-args' are consulted to determine the interpreter
  124. and arguments to use.
  125.  
  126. Note that this variable is consulted only the first time that a Python
  127. mode buffer is visited during an Emacs session.  After that, use
  128. \\[py-toggle-shells] to change the interpreter shell."
  129.   :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
  130.          (const :tag "JPython" jpython))
  131.   :group 'python)
  132.  
  133. (defcustom py-python-command-args '("-i")
  134.   "*List of string arguments to be used when starting a Python shell."
  135.   :type '(repeat string)
  136.   :group 'python)
  137.  
  138. (defcustom py-jpython-command-args '("-i")
  139.   "*List of string arguments to be used when starting a JPython shell."
  140.   :type '(repeat string)
  141.   :group 'python
  142.   :tag "JPython Command Args")
  143.  
  144. (defcustom py-indent-offset 4
  145.   "*Amount of offset per level of indentation.
  146. `\\[py-guess-indent-offset]' can usually guess a good value when
  147. you're editing someone else's Python code."
  148.   :type 'integer
  149.   :group 'python)
  150.  
  151. (defcustom py-smart-indentation t
  152.   "*Should `python-mode' try to automagically set some indentation variables?
  153. When this variable is non-nil, two things happen when a buffer is set
  154. to `python-mode':
  155.  
  156.     1. `py-indent-offset' is guessed from existing code in the buffer.
  157.        Only guessed values between 2 and 8 are considered.  If a valid
  158.        guess can't be made (perhaps because you are visiting a new
  159.        file), then the value in `py-indent-offset' is used.
  160.  
  161.     2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
  162.        equal `tab-width' (`indent-tabs-mode' is never turned on by
  163.        Python mode).  This means that for newly written code, tabs are
  164.        only inserted in indentation if one tab is one indentation
  165.        level, otherwise only spaces are used.
  166.  
  167. Note that both these settings occur *after* `python-mode-hook' is run,
  168. so if you want to defeat the automagic configuration, you must also
  169. set `py-smart-indentation' to nil in your `python-mode-hook'."
  170.   :type 'boolean
  171.   :group 'python)
  172.  
  173. (defcustom py-align-multiline-strings-p t
  174.   "*Flag describing how multi-line triple quoted strings are aligned.
  175. When this flag is non-nil, continuation lines are lined up under the
  176. preceding line's indentation.  When this flag is nil, continuation
  177. lines are aligned to column zero."
  178.   :type '(choice (const :tag "Align under preceding line" t)
  179.          (const :tag "Align to column zero" nil))
  180.   :group 'python)
  181.  
  182. (defcustom py-block-comment-prefix "##"
  183.   "*String used by \\[comment-region] to comment out a block of code.
  184. This should follow the convention for non-indenting comment lines so
  185. that the indentation commands won't get confused (i.e., the string
  186. should be of the form `#x...' where `x' is not a blank or a tab, and
  187. `...' is arbitrary).  However, this string should not end in whitespace."
  188.   :type 'string
  189.   :group 'python)
  190.  
  191. (defcustom py-honor-comment-indentation t
  192.   "*Controls how comment lines influence subsequent indentation.
  193.  
  194. When nil, all comment lines are skipped for indentation purposes, and
  195. if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
  196.  
  197. When t, lines that begin with a single `#' are a hint to subsequent
  198. line indentation.  If the previous line is such a comment line (as
  199. opposed to one that starts with `py-block-comment-prefix'), then its
  200. indentation is used as a hint for this line's indentation.  Lines that
  201. begin with `py-block-comment-prefix' are ignored for indentation
  202. purposes.
  203.  
  204. When not nil or t, comment lines that begin with a `#' are used as
  205. indentation hints, unless the comment character is in column zero."
  206.   :type '(choice
  207.       (const :tag "Skip all comment lines (fast)" nil)
  208.       (const :tag "Single # `sets' indentation for next line" t)
  209.       (const :tag "Single # `sets' indentation except at column zero"
  210.          other)
  211.       )
  212.   :group 'python)
  213.  
  214. (defcustom py-temp-directory
  215.   (let ((ok '(lambda (x)
  216.            (and x
  217.             (setq x (expand-file-name x)) ; always true
  218.             (file-directory-p x)
  219.             (file-writable-p x)
  220.             x))))
  221.     (or (funcall ok (getenv "TMPDIR"))
  222.     (funcall ok "/usr/tmp")
  223.     (funcall ok "/tmp")
  224.     (funcall ok  ".")
  225.     (error
  226.      "Couldn't find a usable temp directory -- set `py-temp-directory'")))
  227.   "*Directory used for temp files created by a *Python* process.
  228. By default, the first directory from this list that exists and that you
  229. can write into:  the value (if any) of the environment variable TMPDIR,
  230. /usr/tmp, /tmp, or the current directory."
  231.   :type 'string
  232.   :group 'python)
  233.  
  234. (defcustom py-beep-if-tab-change t
  235.   "*Ring the bell if `tab-width' is changed.
  236. If a comment of the form
  237.  
  238.   \t# vi:set tabsize=<number>:
  239.  
  240. is found before the first code line when the file is entered, and the
  241. current value of (the general Emacs variable) `tab-width' does not
  242. equal <number>, `tab-width' is set to <number>, a message saying so is
  243. displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
  244. the Emacs bell is also rung as a warning."
  245.   :type 'boolean
  246.   :group 'python)
  247.  
  248. (defcustom py-jump-on-exception t
  249.   "*Jump to innermost exception frame in *Python Output* buffer.
  250. When this variable is non-nil and an exception occurs when running
  251. Python code synchronously in a subprocess, jump immediately to the
  252. source code of the innermost traceback frame."
  253.   :type 'boolean
  254.   :group 'python)
  255.  
  256. (defcustom py-ask-about-save t
  257.   "If not nil, ask about which buffers to save before executing some code.
  258. Otherwise, all modified buffers are saved without asking."
  259.   :type 'boolean
  260.   :group 'python)
  261.  
  262. (defcustom py-backspace-function 'backward-delete-char-untabify
  263.   "*Function called by `py-electric-backspace' when deleting backwards."
  264.   :type 'function
  265.   :group 'python)
  266.  
  267. (defcustom py-delete-function 'delete-char
  268.   "*Function called by `py-electric-delete' when deleting forwards."
  269.   :type 'function
  270.   :group 'python)
  271.  
  272. (defcustom py-imenu-show-method-args-p nil 
  273.   "*Controls echoing of arguments of functions & methods in the Imenu buffer.
  274. When non-nil, arguments are printed."
  275.   :type 'boolean
  276.   :group 'python)
  277. (make-variable-buffer-local 'py-indent-offset)
  278.  
  279. ;; Not customizable
  280. (defvar py-master-file nil
  281.   "If non-nil, execute the named file instead of the buffer's file.
  282. The intent is to allow you to set this variable in the file's local
  283. variable section, e.g.:
  284.  
  285.     # Local Variables:
  286.     # py-master-file: \"master.py\"
  287.     # End:
  288.  
  289. so that typing \\[py-execute-buffer] in that buffer executes the named
  290. master file instead of the buffer's file.  If the file name has a
  291. relative path, the value of variable `default-directory' for the
  292. buffer is prepended to come up with a file name.")
  293. (make-variable-buffer-local 'py-master-file)
  294.  
  295.  
  296.  
  297. ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  298. ;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
  299.  
  300. (defconst py-emacs-features
  301.   (let (features)
  302.    ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
  303.    ;; the same string.
  304.    (let ((tmp1 (make-temp-name ""))
  305.      (tmp2 (make-temp-name "")))
  306.      (if (string-equal tmp1 tmp2)
  307.      (push 'broken-temp-names features)))
  308.    ;; return the features
  309.    features)
  310.   "A list of features extant in the Emacs you are using.
  311. There are many flavors of Emacs out there, with different levels of
  312. support for features needed by `python-mode'.")
  313.  
  314. (defvar python-font-lock-keywords
  315.   (let ((kw1 (mapconcat 'identity
  316.             '("and"      "assert"   "break"   "class"
  317.               "continue" "def"      "del"     "elif"
  318.               "else"     "except"   "exec"    "for"
  319.               "from"     "global"   "if"      "import"
  320.               "in"       "is"       "lambda"  "not"
  321.               "or"       "pass"     "print"   "raise"
  322.               "return"   "while"
  323.               )
  324.             "\\|"))
  325.     (kw2 (mapconcat 'identity
  326.             '("else:" "except:" "finally:" "try:")
  327.             "\\|"))
  328.     )
  329.     (list
  330.      ;; keywords
  331.      (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
  332.      ;; block introducing keywords with immediately following colons.
  333.      ;; Yes "except" is in both lists.
  334.      (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
  335.      ;; classes
  336.      '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
  337.        1 font-lock-type-face)
  338.      ;; functions
  339.      '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
  340.        1 font-lock-function-name-face)
  341.      ))
  342.   "Additional expressions to highlight in Python mode.")
  343. (put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
  344.  
  345. ;; have to bind py-file-queue before installing the kill-emacs-hook
  346. (defvar py-file-queue nil
  347.   "Queue of Python temp files awaiting execution.
  348. Currently-active file is at the head of the list.")
  349.  
  350.  
  351. ;; Constants
  352.  
  353. (defconst py-stringlit-re
  354.   (concat
  355.    ;; These fail if backslash-quote ends the string (not worth
  356.    ;; fixing?).  They precede the short versions so that the first two
  357.    ;; quotes don't look like an empty short string.
  358.    ;;
  359.    ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
  360.    ;; with potential embedded single quotes
  361.    "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
  362.    "\\|"
  363.    ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
  364.    ;; with potential embedded double quotes
  365.    "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
  366.    "\\|"
  367.    "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'"    ; single-quoted
  368.    "\\|"                ; or
  369.    "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\""    ; double-quoted
  370.    )
  371.   "Regular expression matching a Python string literal.")
  372.  
  373. (defconst py-continued-re
  374.   ;; This is tricky because a trailing backslash does not mean
  375.   ;; continuation if it's in a comment
  376.   (concat
  377.    "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
  378.    "\\\\$")
  379.   "Regular expression matching Python backslash continuation lines.")
  380.   
  381. (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
  382.   "Regular expression matching a blank or comment line.")
  383.  
  384. (defconst py-outdent-re
  385.   (concat "\\(" (mapconcat 'identity
  386.                '("else:"
  387.                  "except\\(\\s +.*\\)?:"
  388.                  "finally:"
  389.                  "elif\\s +.*:")
  390.                "\\|")
  391.       "\\)")
  392.   "Regular expression matching statements to be dedented one level.")
  393.   
  394. (defconst py-block-closing-keywords-re
  395.   "\\(return\\|raise\\|break\\|continue\\|pass\\)"
  396.   "Regular expression matching keywords which typically close a block.")
  397.  
  398. (defconst py-no-outdent-re
  399.   (concat
  400.    "\\("
  401.    (mapconcat 'identity
  402.           (list "try:"
  403.             "except\\(\\s +.*\\)?:"
  404.             "while\\s +.*:"
  405.             "for\\s +.*:"
  406.             "if\\s +.*:"
  407.             "elif\\s +.*:"
  408.             (concat py-block-closing-keywords-re "[ \t\n]")
  409.             )
  410.           "\\|")
  411.       "\\)")
  412.   "Regular expression matching lines not to dedent after.")
  413.  
  414. (defconst py-defun-start-re
  415.   "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
  416.   ;; If you change this, you probably have to change py-current-defun
  417.   ;; as well.  This is only used by py-current-defun to find the name
  418.   ;; for add-log.el.
  419.   "Regular expression matching a function, method, or variable assignment.")
  420.  
  421. (defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
  422.   ;; If you change this, you probably have to change py-current-defun
  423.   ;; as well.  This is only used by py-current-defun to find the name
  424.   ;; for add-log.el.
  425.   "Regular expression for finding a class name.")
  426.  
  427. (defconst py-traceback-line-re
  428.   "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
  429.   "Regular expression that describes tracebacks.")
  430.  
  431.  
  432.  
  433. ;; Major mode boilerplate
  434.  
  435. ;; define a mode-specific abbrev table for those who use such things
  436. (defvar python-mode-abbrev-table nil
  437.   "Abbrev table in use in `python-mode' buffers.")
  438. (define-abbrev-table 'python-mode-abbrev-table nil)
  439.  
  440. (defvar python-mode-hook nil
  441.   "*Hook called by `python-mode'.")
  442.  
  443. ;; In previous version of python-mode.el, the hook was incorrectly
  444. ;; called py-mode-hook, and was not defvar'd.  Deprecate its use.
  445. (and (fboundp 'make-obsolete-variable)
  446.      (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
  447.  
  448. (defvar py-mode-map ()
  449.   "Keymap used in `python-mode' buffers.")
  450. (if py-mode-map
  451.     nil
  452.   (setq py-mode-map (make-sparse-keymap))
  453.   ;; electric keys
  454.   (define-key py-mode-map ":" 'py-electric-colon)
  455.   ;; indentation level modifiers
  456.   (define-key py-mode-map "\C-c\C-l"  'py-shift-region-left)
  457.   (define-key py-mode-map "\C-c\C-r"  'py-shift-region-right)
  458.   (define-key py-mode-map "\C-c<"     'py-shift-region-left)
  459.   (define-key py-mode-map "\C-c>"     'py-shift-region-right)
  460.   ;; subprocess commands
  461.   (define-key py-mode-map "\C-c\C-c"  'py-execute-buffer)
  462.   (define-key py-mode-map "\C-c\C-m"  'py-execute-import-or-reload)
  463.   (define-key py-mode-map "\C-c\C-s"  'py-execute-string)
  464.   (define-key py-mode-map "\C-c|"     'py-execute-region)
  465.   (define-key py-mode-map "\e\C-x"    'py-execute-def-or-class)
  466.   (define-key py-mode-map "\C-c!"     'py-shell)
  467.   (define-key py-mode-map "\C-c\C-t"  'py-toggle-shells)
  468.   ;; Caution!  Enter here at your own risk.  We are trying to support
  469.   ;; several behaviors and it gets disgusting. :-( This logic ripped
  470.   ;; largely from CC Mode.
  471.   ;;
  472.   ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
  473.   ;; backwards deletion behavior to DEL, which both Delete and
  474.   ;; Backspace get translated to.  There's no way to separate this
  475.   ;; behavior in a clean way, so deal with it!  Besides, it's been
  476.   ;; this way since the dawn of time.
  477.   (if (not (boundp 'delete-key-deletes-forward))
  478.       (define-key py-mode-map "\177" 'py-electric-backspace)
  479.     ;; However, XEmacs 20 actually achieved enlightenment.  It is
  480.     ;; possible to sanely define both backward and forward deletion
  481.     ;; behavior under X separately (TTYs are forever beyond hope, but
  482.     ;; who cares?  XEmacs 20 does the right thing with these too).
  483.     (define-key py-mode-map [delete]    'py-electric-delete)
  484.     (define-key py-mode-map [backspace] 'py-electric-backspace))
  485.   ;; Separate M-BS from C-M-h.  The former should remain
  486.   ;; backward-kill-word.
  487.   (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
  488.   (define-key py-mode-map "\C-c\C-k"  'py-mark-block)
  489.   ;; Miscellaneous
  490.   (define-key py-mode-map "\C-c:"     'py-guess-indent-offset)
  491.   (define-key py-mode-map "\C-c\t"    'py-indent-region)
  492.   (define-key py-mode-map "\C-c\C-n"  'py-next-statement)
  493.   (define-key py-mode-map "\C-c\C-p"  'py-previous-statement)
  494.   (define-key py-mode-map "\C-c\C-u"  'py-goto-block-up)
  495.   (define-key py-mode-map "\C-c#"     'py-comment-region)
  496.   (define-key py-mode-map "\C-c?"     'py-describe-mode)
  497.   (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
  498.   (define-key py-mode-map "\e\C-a"    'py-beginning-of-def-or-class)
  499.   (define-key py-mode-map "\e\C-e"    'py-end-of-def-or-class)
  500.   (define-key py-mode-map "\C-c-"     'py-up-exception)
  501.   (define-key py-mode-map "\C-c="     'py-down-exception)
  502.   ;; stuff that is `standard' but doesn't interface well with
  503.   ;; python-mode, which forces us to rebind to special commands
  504.   (define-key py-mode-map "\C-xnd"    'py-narrow-to-defun)
  505.   ;; information
  506.   (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
  507.   (define-key py-mode-map "\C-c\C-v" 'py-version)
  508.   ;; shadow global bindings for newline-and-indent w/ the py- version.
  509.   ;; BAW - this is extremely bad form, but I'm not going to change it
  510.   ;; for now.
  511.   (mapcar #'(lambda (key)
  512.           (define-key py-mode-map key 'py-newline-and-indent))
  513.       (where-is-internal 'newline-and-indent))
  514.   ;; Force RET to be py-newline-and-indent even if it didn't get
  515.   ;; mapped by the above code.  motivation: Emacs' default binding for
  516.   ;; RET is `newline' and C-j is `newline-and-indent'.  Most Pythoneers
  517.   ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
  518.   ;; dislike this are probably knowledgeable enough to do a rebind.
  519.   ;; However, we do *not* change C-j since many Emacsers have already
  520.   ;; swapped RET and C-j and they don't want C-j bound to `newline' to 
  521.   ;; change.
  522.   (define-key py-mode-map "\C-m" 'py-newline-and-indent)
  523.   )
  524.  
  525. (defvar py-mode-output-map nil
  526.   "Keymap used in *Python Output* buffers.")
  527. (if py-mode-output-map
  528.     nil
  529.   (setq py-mode-output-map (make-sparse-keymap))
  530.   (define-key py-mode-output-map [button2]  'py-mouseto-exception)
  531.   (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
  532.   ;; TBD: Disable all self-inserting keys.  This is bogus, we should
  533.   ;; really implement this as *Python Output* buffer being read-only
  534.   (mapcar #' (lambda (key)
  535.            (define-key py-mode-output-map key
  536.          #'(lambda () (interactive) (beep))))
  537.          (where-is-internal 'self-insert-command))
  538.   )
  539.  
  540. (defvar py-shell-map nil
  541.   "Keymap used in *Python* shell buffers.")
  542. (if py-shell-map
  543.     nil
  544.   (setq py-shell-map (copy-keymap comint-mode-map))
  545.   (define-key py-shell-map [tab]   'tab-to-tab-stop)
  546.   (define-key py-shell-map "\C-c-" 'py-up-exception)
  547.   (define-key py-shell-map "\C-c=" 'py-down-exception)
  548.   )
  549.  
  550. (defvar py-mode-syntax-table nil
  551.   "Syntax table used in `python-mode' buffers.")
  552. (if py-mode-syntax-table
  553.     nil
  554.   (setq py-mode-syntax-table (make-syntax-table))
  555.   (modify-syntax-entry ?\( "()" py-mode-syntax-table)
  556.   (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
  557.   (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
  558.   (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
  559.   (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
  560.   (modify-syntax-entry ?\} "){" py-mode-syntax-table)
  561.   ;; Add operator symbols misassigned in the std table
  562.   (modify-syntax-entry ?\$ "."  py-mode-syntax-table)
  563.   (modify-syntax-entry ?\% "."  py-mode-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.   (modify-syntax-entry ?\= "."  py-mode-syntax-table)
  571.   (modify-syntax-entry ?\> "."  py-mode-syntax-table)
  572.   (modify-syntax-entry ?\| "."  py-mode-syntax-table)
  573.   ;; For historical reasons, underscore is word class instead of
  574.   ;; symbol class.  GNU conventions say it should be symbol class, but
  575.   ;; there's a natural conflict between what major mode authors want
  576.   ;; and what users expect from `forward-word' and `backward-word'.
  577.   ;; Guido and I have hashed this out and have decided to keep
  578.   ;; underscore in word class.  If you're tempted to change it, try
  579.   ;; binding M-f and M-b to py-forward-into-nomenclature and
  580.   ;; py-backward-into-nomenclature instead.  This doesn't help in all
  581.   ;; situations where you'd want the different behavior
  582.   ;; (e.g. backward-kill-word).
  583.   (modify-syntax-entry ?\_ "w"  py-mode-syntax-table)
  584.   ;; Both single quote and double quote are string delimiters
  585.   (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
  586.   (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
  587.   ;; backquote is open and close paren
  588.   (modify-syntax-entry ?\` "$"  py-mode-syntax-table)
  589.   ;; comment delimiters
  590.   (modify-syntax-entry ?\# "<"  py-mode-syntax-table)
  591.   (modify-syntax-entry ?\n ">"  py-mode-syntax-table)
  592.   )
  593.  
  594.  
  595.  
  596. ;; Utilities
  597.  
  598. (defmacro py-safe (&rest body)
  599.   "Safely execute BODY, return nil if an error occurred."
  600.   (` (condition-case nil
  601.      (progn (,@ body))
  602.        (error nil))))
  603.  
  604. (defsubst py-keep-region-active ()
  605.   "Keep the region active in XEmacs."
  606.   ;; Ignore byte-compiler warnings you might see.  Also note that
  607.   ;; FSF's Emacs 19 does it differently; its policy doesn't require us
  608.   ;; to take explicit action.
  609.   (and (boundp 'zmacs-region-stays)
  610.        (setq zmacs-region-stays t)))
  611.  
  612. (defsubst py-point (position)
  613.   "Returns the value of point at certain commonly referenced POSITIONs.
  614. POSITION can be one of the following symbols:
  615.  
  616.   bol  -- beginning of line
  617.   eol  -- end of line
  618.   bod  -- beginning of def or class
  619.   eod  -- end of def or class
  620.   bob  -- beginning of buffer
  621.   eob  -- end of buffer
  622.   boi  -- back to indentation
  623.   bos  -- beginning of statement
  624.  
  625. This function does not modify point or mark."
  626.   (let ((here (point)))
  627.     (cond
  628.      ((eq position 'bol) (beginning-of-line))
  629.      ((eq position 'eol) (end-of-line))
  630.      ((eq position 'bod) (py-beginning-of-def-or-class))
  631.      ((eq position 'eod) (py-end-of-def-or-class))
  632.      ;; Kind of funny, I know, but useful for py-up-exception.
  633.      ((eq position 'bob) (beginning-of-buffer))
  634.      ((eq position 'eob) (end-of-buffer))
  635.      ((eq position 'boi) (back-to-indentation))
  636.      ((eq position 'bos) (py-goto-initial-line))
  637.      (t (error "Unknown buffer position requested: %s" position))
  638.      )
  639.     (prog1
  640.     (point)
  641.       (goto-char here))))
  642.  
  643. (defsubst py-highlight-line (from to file line)
  644.   (cond
  645.    ((fboundp 'make-extent)
  646.     ;; XEmacs
  647.     (let ((e (make-extent from to)))
  648.       (set-extent-property e 'mouse-face 'highlight)
  649.       (set-extent-property e 'py-exc-info (cons file line))
  650.       (set-extent-property e 'keymap py-mode-output-map)))
  651.    (t
  652.     ;; Emacs -- Please port this!
  653.     )
  654.    ))
  655.  
  656. (defun py-in-literal (&optional lim)
  657.   "Return non-nil if point is in a Python literal (a comment or string).
  658. Optional argument LIM indicates the beginning of the containing form,
  659. i.e. the limit on how far back to scan."
  660.   ;; This is the version used for non-XEmacs, which has a nicer
  661.   ;; interface.
  662.   ;;
  663.   ;; WARNING: Watch out for infinite recursion.
  664.   (let* ((lim (or lim (py-point 'bod)))
  665.      (state (parse-partial-sexp lim (point))))
  666.     (cond
  667.      ((nth 3 state) 'string)
  668.      ((nth 4 state) 'comment)
  669.      (t nil))))
  670.  
  671. ;; XEmacs has a built-in function that should make this much quicker.
  672. ;; In this case, lim is ignored
  673. (defun py-fast-in-literal (&optional lim)
  674.   "Fast version of `py-in-literal', used only by XEmacs.
  675. Optional LIM is ignored."
  676.   ;; don't have to worry about context == 'block-comment
  677.   (buffer-syntactic-context))
  678.  
  679. (if (fboundp 'buffer-syntactic-context)
  680.     (defalias 'py-in-literal 'py-fast-in-literal))
  681.  
  682.  
  683.  
  684. ;; Menu definitions, only relevent if you have the easymenu.el package
  685. ;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
  686. (defvar py-menu nil
  687.   "Menu for Python Mode.
  688. This menu will get created automatically if you have the `easymenu'
  689. package.  Note that the latest X/Emacs releases contain this package.")
  690.  
  691. (and (py-safe (require 'easymenu) t)
  692.      (easy-menu-define
  693.       py-menu py-mode-map "Python Mode menu"
  694.       '("Python"
  695.     ["Comment Out Region"   py-comment-region  (mark)]
  696.     ["Uncomment Region"     (py-comment-region (point) (mark) '(4)) (mark)]
  697.     "-"
  698.     ["Mark current block"   py-mark-block t]
  699.     ["Mark current def"     py-mark-def-or-class t]
  700.     ["Mark current class"   (py-mark-def-or-class t) t]
  701.     "-"
  702.     ["Shift region left"    py-shift-region-left (mark)]
  703.     ["Shift region right"   py-shift-region-right (mark)]
  704.     "-"
  705.     ["Import/reload file"   py-execute-import-or-reload t]
  706.     ["Execute buffer"       py-execute-buffer t]
  707.     ["Execute region"       py-execute-region (mark)]
  708.     ["Execute def or class" py-execute-def-or-class (mark)]
  709.     ["Execute string"       py-execute-string t]
  710.     ["Start interpreter..." py-shell t]
  711.     "-"
  712.     ["Go to start of block" py-goto-block-up t]
  713.     ["Go to start of class" (py-beginning-of-def-or-class t) t]
  714.     ["Move to end of class" (py-end-of-def-or-class t) t]
  715.     ["Move to start of def" py-beginning-of-def-or-class t]
  716.     ["Move to end of def"   py-end-of-def-or-class t]
  717.     "-"
  718.     ["Describe mode"        py-describe-mode t]
  719.     )))
  720.  
  721.  
  722.  
  723. ;; Imenu definitions
  724. (defvar py-imenu-class-regexp
  725.   (concat                ; <<classes>>
  726.    "\\("                ;
  727.    "^[ \t]*"                ; newline and maybe whitespace
  728.    "\\(class[ \t]+[a-zA-Z0-9_]+\\)"    ; class name
  729.                     ; possibly multiple superclasses
  730.    "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
  731.    "[ \t]*:"                ; and the final :
  732.    "\\)"                ; >>classes<<
  733.    )
  734.   "Regexp for Python classes for use with the Imenu package."
  735.   )
  736.  
  737. (defvar py-imenu-method-regexp
  738.   (concat                               ; <<methods and functions>>
  739.    "\\("                                ; 
  740.    "^[ \t]*"                            ; new line and maybe whitespace
  741.    "\\(def[ \t]+"                       ; function definitions start with def
  742.    "\\([a-zA-Z0-9_]+\\)"                ;   name is here
  743.                     ;   function arguments...
  744. ;;   "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
  745.    "[ \t]*(\\([^:#]*\\))"
  746.    "\\)"                                ; end of def
  747.    "[ \t]*:"                            ; and then the :
  748.    "\\)"                                ; >>methods and functions<<
  749.    )
  750.   "Regexp for Python methods/functions for use with the Imenu package."
  751.   )
  752.  
  753. (defvar py-imenu-method-no-arg-parens '(2 8)
  754.   "Indices into groups of the Python regexp for use with Imenu.
  755.  
  756. Using these values will result in smaller Imenu lists, as arguments to
  757. functions are not listed.
  758.  
  759. See the variable `py-imenu-show-method-args-p' for more
  760. information.")
  761.  
  762. (defvar py-imenu-method-arg-parens '(2 7)
  763.   "Indices into groups of the Python regexp for use with imenu.
  764. Using these values will result in large Imenu lists, as arguments to
  765. functions are listed.
  766.  
  767. See the variable `py-imenu-show-method-args-p' for more
  768. information.")
  769.  
  770. ;; Note that in this format, this variable can still be used with the
  771. ;; imenu--generic-function. Otherwise, there is no real reason to have
  772. ;; it.
  773. (defvar py-imenu-generic-expression
  774.   (cons
  775.    (concat 
  776.     py-imenu-class-regexp
  777.     "\\|"                ; or...
  778.     py-imenu-method-regexp
  779.     )
  780.    py-imenu-method-no-arg-parens)
  781.   "Generic Python expression which may be used directly with Imenu.
  782. Used by setting the variable `imenu-generic-expression' to this value.
  783. Also, see the function \\[py-imenu-create-index] for a better
  784. alternative for finding the index.")
  785.  
  786. ;; These next two variables are used when searching for the Python
  787. ;; class/definitions. Just saving some time in accessing the
  788. ;; generic-python-expression, really.
  789. (defvar py-imenu-generic-regexp nil)
  790. (defvar py-imenu-generic-parens nil)
  791.  
  792.  
  793. (defun py-imenu-create-index-function ()
  794.   "Python interface function for the Imenu package.
  795. Finds all Python classes and functions/methods. Calls function
  796. \\[py-imenu-create-index-engine].  See that function for the details
  797. of how this works."
  798.   (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
  799.     py-imenu-generic-parens (if py-imenu-show-method-args-p
  800.                     py-imenu-method-arg-parens
  801.                   py-imenu-method-no-arg-parens))
  802.   (goto-char (point-min))
  803.   ;; Warning: When the buffer has no classes or functions, this will
  804.   ;; return nil, which seems proper according to the Imenu API, but
  805.   ;; causes an error in the XEmacs port of Imenu.  Sigh.
  806.   (py-imenu-create-index-engine nil))
  807.  
  808. (defun py-imenu-create-index-engine (&optional start-indent)
  809.   "Function for finding Imenu definitions in Python.
  810.  
  811. Finds all definitions (classes, methods, or functions) in a Python
  812. file for the Imenu package.
  813.  
  814. Returns a possibly nested alist of the form
  815.  
  816.     (INDEX-NAME . INDEX-POSITION)
  817.  
  818. The second element of the alist may be an alist, producing a nested
  819. list as in
  820.  
  821.     (INDEX-NAME . INDEX-ALIST)
  822.  
  823. This function should not be called directly, as it calls itself
  824. recursively and requires some setup.  Rather this is the engine for
  825. the function \\[py-imenu-create-index-function].
  826.  
  827. It works recursively by looking for all definitions at the current
  828. indention level.  When it finds one, it adds it to the alist.  If it
  829. finds a definition at a greater indentation level, it removes the
  830. previous definition from the alist. In its place it adds all
  831. definitions found at the next indentation level.  When it finds a
  832. definition that is less indented then the current level, it returns
  833. the alist it has created thus far.
  834.  
  835. The optional argument START-INDENT indicates the starting indentation
  836. at which to continue looking for Python classes, methods, or
  837. functions.  If this is not supplied, the function uses the indentation
  838. of the first definition found."
  839.   (let (index-alist
  840.     sub-method-alist
  841.     looking-p
  842.     def-name prev-name
  843.     cur-indent def-pos
  844.     (class-paren (first  py-imenu-generic-parens)) 
  845.     (def-paren   (second py-imenu-generic-parens)))
  846.     (setq looking-p
  847.       (re-search-forward py-imenu-generic-regexp (point-max) t))
  848.     (while looking-p
  849.       (save-excursion
  850.     ;; used to set def-name to this value but generic-extract-name
  851.     ;; is new to imenu-1.14. this way it still works with
  852.     ;; imenu-1.11
  853.     ;;(imenu--generic-extract-name py-imenu-generic-parens))
  854.     (let ((cur-paren (if (match-beginning class-paren)
  855.                  class-paren def-paren)))
  856.       (setq def-name
  857.         (buffer-substring-no-properties (match-beginning cur-paren)
  858.                         (match-end cur-paren))))
  859.     (save-match-data
  860.       (py-beginning-of-def-or-class 'either))
  861.     (beginning-of-line)
  862.     (setq cur-indent (current-indentation)))
  863.       ;; HACK: want to go to the next correct definition location.  We
  864.       ;; explicitly list them here but it would be better to have them
  865.       ;; in a list.
  866.       (setq def-pos
  867.         (or (match-beginning class-paren)
  868.         (match-beginning def-paren)))
  869.       ;; if we don't have a starting indent level, take this one
  870.       (or start-indent
  871.       (setq start-indent cur-indent))
  872.       ;; if we don't have class name yet, take this one
  873.       (or prev-name
  874.       (setq prev-name def-name))
  875.       ;; what level is the next definition on?  must be same, deeper
  876.       ;; or shallower indentation
  877.       (cond
  878.        ;; at the same indent level, add it to the list...
  879.        ((= start-indent cur-indent)
  880.     (push (cons def-name def-pos) index-alist))
  881.        ;; deeper indented expression, recurse
  882.        ((< start-indent cur-indent)
  883.     ;; the point is currently on the expression we're supposed to
  884.     ;; start on, so go back to the last expression. The recursive
  885.     ;; call will find this place again and add it to the correct
  886.     ;; list
  887.     (re-search-backward py-imenu-generic-regexp (point-min) 'move)
  888.     (setq sub-method-alist (py-imenu-create-index-engine cur-indent))
  889.     (if sub-method-alist
  890.         ;; we put the last element on the index-alist on the start
  891.         ;; of the submethod alist so the user can still get to it.
  892.         (let ((save-elmt (pop index-alist)))
  893.           (push (cons prev-name
  894.               (cons save-elmt sub-method-alist))
  895.             index-alist))))
  896.        ;; found less indented expression, we're done.
  897.        (t 
  898.     (setq looking-p nil)
  899.     (re-search-backward py-imenu-generic-regexp (point-min) t)))
  900.       ;; end-cond
  901.       (setq prev-name def-name)
  902.       (and looking-p
  903.        (setq looking-p
  904.          (re-search-forward py-imenu-generic-regexp
  905.                     (point-max) 'move))))
  906.     (nreverse index-alist)))
  907.  
  908.  
  909. ;;;###autoload
  910. (defun python-mode ()
  911.   "Major mode for editing Python files.
  912. To submit a problem report, enter `\\[py-submit-bug-report]' from a
  913. `python-mode' buffer.  Do `\\[py-describe-mode]' for detailed
  914. documentation.  To see what version of `python-mode' you are running,
  915. enter `\\[py-version]'.
  916.  
  917. This mode knows about Python indentation, tokens, comments and
  918. continuation lines.  Paragraphs are separated by blank lines only.
  919.  
  920. COMMANDS
  921. \\{py-mode-map}
  922. VARIABLES
  923.  
  924. py-indent-offset\t\tindentation increment
  925. py-block-comment-prefix\t\tcomment string used by `comment-region'
  926. py-python-command\t\tshell command to invoke Python interpreter
  927. py-temp-directory\t\tdirectory used for temp files (if needed)
  928. py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
  929.   (interactive)
  930.   ;; set up local variables
  931.   (kill-all-local-variables)
  932.   (make-local-variable 'font-lock-defaults)
  933.   (make-local-variable 'paragraph-separate)
  934.   (make-local-variable 'paragraph-start)
  935.   (make-local-variable 'require-final-newline)
  936.   (make-local-variable 'comment-start)
  937.   (make-local-variable 'comment-end)
  938.   (make-local-variable 'comment-start-skip)
  939.   (make-local-variable 'comment-column)
  940.   (make-local-variable 'comment-indent-function)
  941.   (make-local-variable 'indent-region-function)
  942.   (make-local-variable 'indent-line-function)
  943.   (make-local-variable 'add-log-current-defun-function)
  944.   ;;
  945.   (set-syntax-table py-mode-syntax-table)
  946.   (setq major-mode              'python-mode
  947.     mode-name               "Python"
  948.     local-abbrev-table      python-mode-abbrev-table
  949.     font-lock-defaults      '(python-font-lock-keywords)
  950.     paragraph-separate      "^[ \t]*$"
  951.     paragraph-start         "^[ \t]*$"
  952.     require-final-newline   t
  953.     comment-start           "# "
  954.     comment-end             ""
  955.     comment-start-skip      "# *"
  956.     comment-column          40
  957.     comment-indent-function 'py-comment-indent-function
  958.     indent-region-function  'py-indent-region
  959.     indent-line-function    'py-indent-line
  960.     ;; tell add-log.el how to find the current function/method/variable
  961.     add-log-current-defun-function 'py-current-defun
  962.     )
  963.   (use-local-map py-mode-map)
  964.   ;; add the menu
  965.   (if py-menu
  966.       (easy-menu-add py-menu))
  967.   ;; Emacs 19 requires this
  968.   (if (boundp 'comment-multi-line)
  969.       (setq comment-multi-line nil))
  970.   ;; Install Imenu if available
  971.   (when (py-safe (require 'imenu))
  972.     (setq imenu-create-index-function #'py-imenu-create-index-function)
  973.     (setq imenu-generic-expression py-imenu-generic-expression)
  974.     (if (fboundp 'imenu-add-to-menubar)
  975.     (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
  976.     )
  977.   ;; Run the mode hook.  Note that py-mode-hook is deprecated.
  978.   (if python-mode-hook
  979.       (run-hooks 'python-mode-hook)
  980.     (run-hooks 'py-mode-hook))
  981.   ;; Now do the automagical guessing
  982.   (if py-smart-indentation
  983.     (let ((offset py-indent-offset))
  984.       ;; It's okay if this fails to guess a good value
  985.       (if (and (py-safe (py-guess-indent-offset))
  986.            (<= py-indent-offset 8)
  987.            (>= py-indent-offset 2))
  988.       (setq offset py-indent-offset))
  989.       (setq py-indent-offset offset)
  990.       ;; Only turn indent-tabs-mode off if tab-width !=
  991.       ;; py-indent-offset.  Never turn it on, because the user must
  992.       ;; have explicitly turned it off.
  993.       (if (/= tab-width py-indent-offset)
  994.       (setq indent-tabs-mode nil))
  995.       ))
  996.   ;; Set the default shell if not already set
  997.   (when (null py-which-shell)
  998.     (py-toggle-shells py-default-interpreter))
  999.   )
  1000.  
  1001.  
  1002. ;; electric characters
  1003. (defun py-outdent-p ()
  1004.   "Returns non-nil if the current line should dedent one level."
  1005.   (save-excursion
  1006.     (and (progn (back-to-indentation)
  1007.         (looking-at py-outdent-re))
  1008.      ;; short circuit infloop on illegal construct
  1009.      (not (bobp))
  1010.      (progn (forward-line -1)
  1011.         (py-goto-initial-line)
  1012.         (back-to-indentation)
  1013.         (while (or (looking-at py-blank-or-comment-re)
  1014.                (bobp))
  1015.           (backward-to-indentation 1))
  1016.         (not (looking-at py-no-outdent-re)))
  1017.      )))
  1018.       
  1019. (defun py-electric-colon (arg)
  1020.   "Insert a colon.
  1021. In certain cases the line is dedented appropriately.  If a numeric
  1022. argument ARG is provided, that many colons are inserted
  1023. non-electrically.  Electric behavior is inhibited inside a string or
  1024. comment."
  1025.   (interactive "P")
  1026.   (self-insert-command (prefix-numeric-value arg))
  1027.   ;; are we in a string or comment?
  1028.   (if (save-excursion
  1029.     (let ((pps (parse-partial-sexp (save-excursion
  1030.                      (py-beginning-of-def-or-class)
  1031.                      (point))
  1032.                        (point))))
  1033.       (not (or (nth 3 pps) (nth 4 pps)))))
  1034.       (save-excursion
  1035.     (let ((here (point))
  1036.           (outdent 0)
  1037.           (indent (py-compute-indentation t)))
  1038.       (if (and (not arg)
  1039.            (py-outdent-p)
  1040.            (= indent (save-excursion
  1041.                    (py-next-statement -1)
  1042.                    (py-compute-indentation t)))
  1043.            )
  1044.           (setq outdent py-indent-offset))
  1045.       ;; Don't indent, only dedent.  This assumes that any lines
  1046.       ;; that are already dedented relative to
  1047.       ;; py-compute-indentation were put there on purpose.  It's
  1048.       ;; highly annoying to have `:' indent for you.  Use TAB, C-c
  1049.       ;; C-l or C-c C-r to adjust.  TBD: Is there a better way to
  1050.       ;; determine this???
  1051.       (if (< (current-indentation) indent) nil
  1052.         (goto-char here)
  1053.         (beginning-of-line)
  1054.         (delete-horizontal-space)
  1055.         (indent-to (- indent outdent))
  1056.         )))))
  1057.  
  1058.  
  1059. ;; Python subprocess utilities and filters
  1060. (defun py-execute-file (proc filename)
  1061.   "Send to Python interpreter process PROC \"execfile('FILENAME')\".
  1062. Make that process's buffer visible and force display.  Also make
  1063. comint believe the user typed this string so that
  1064. `kill-output-from-shell' does The Right Thing."
  1065.   (let ((curbuf (current-buffer))
  1066.     (procbuf (process-buffer proc))
  1067. ;    (comint-scroll-to-bottom-on-output t)
  1068.     (msg (format "## working on region in file %s...\n" filename))
  1069.     (cmd (format "execfile(r'%s')\n" filename)))
  1070.     (unwind-protect
  1071.     (save-excursion
  1072.       (set-buffer procbuf)
  1073.       (goto-char (point-max))
  1074.       (move-marker (process-mark proc) (point))
  1075.       (funcall (process-filter proc) proc msg))
  1076.       (set-buffer curbuf))
  1077.     (process-send-string proc cmd)))
  1078.  
  1079. (defun py-comint-output-filter-function (string)
  1080.   "Watch output for Python prompt and exec next file waiting in queue.
  1081. This function is appropriate for `comint-output-filter-functions'."
  1082.   ;; TBD: this should probably use split-string
  1083.   (when (and (or (string-equal string ">>> ")
  1084.          (and (>= (length string) 5)
  1085.               (string-equal (substring string -5) "\n>>> ")))
  1086.          py-file-queue)
  1087.     (py-safe (delete-file (car py-file-queue)))
  1088.     (setq py-file-queue (cdr py-file-queue))
  1089.     (if py-file-queue
  1090.     (let ((pyproc (get-buffer-process (current-buffer))))
  1091.       (py-execute-file pyproc (car py-file-queue))))
  1092.     ))
  1093.  
  1094. (defun py-postprocess-output-buffer (buf)
  1095.   "Highlight exceptions found in BUF.
  1096. If an exception occurred return t, otherwise return nil.  BUF must exist."
  1097.   (let (line file bol err-p)
  1098.     (save-excursion
  1099.       (set-buffer buf)
  1100.       (beginning-of-buffer)
  1101.       (while (re-search-forward py-traceback-line-re nil t)
  1102.     (setq file (match-string 1)
  1103.           line (string-to-int (match-string 2))
  1104.           bol (py-point 'bol))
  1105.     (py-highlight-line bol (py-point 'eol) file line)))
  1106.     (when (and py-jump-on-exception line)
  1107.       (beep)
  1108.       (py-jump-to-exception file line)
  1109.       (setq err-p t))
  1110.     err-p))
  1111.  
  1112.  
  1113.  
  1114. ;;; Subprocess commands
  1115.  
  1116. ;; only used when (memq 'broken-temp-names py-emacs-features)
  1117. (defvar py-serial-number 0)
  1118. (defvar py-exception-buffer nil)
  1119. (defconst py-output-buffer "*Python Output*")
  1120. (make-variable-buffer-local 'py-output-buffer)
  1121.  
  1122. ;; for toggling between CPython and JPython
  1123. (defvar py-which-shell nil)
  1124. (defvar py-which-args  py-python-command-args)
  1125. (defvar py-which-bufname "Python")
  1126. (make-variable-buffer-local 'py-which-shell)
  1127. (make-variable-buffer-local 'py-which-args)
  1128. (make-variable-buffer-local 'py-which-bufname)
  1129.  
  1130. (defun py-toggle-shells (arg)
  1131.   "Toggles between the CPython and JPython shells.
  1132.  
  1133. With positive argument ARG (interactively \\[universal-argument]),
  1134. uses the CPython shell, with negative ARG uses the JPython shell, and
  1135. with a zero argument, toggles the shell.
  1136.  
  1137. Programmatically, ARG can also be one of the symbols `cpython' or
  1138. `jpython', equivalent to positive arg and negative arg respectively."
  1139.   (interactive "P")
  1140.   ;; default is to toggle
  1141.   (if (null arg)
  1142.       (setq arg 0))
  1143.   ;; preprocess arg
  1144.   (cond
  1145.    ((equal arg 0)
  1146.     ;; toggle
  1147.     (if (string-equal py-which-bufname "Python")
  1148.     (setq arg -1)
  1149.       (setq arg 1)))
  1150.    ((equal arg 'cpython) (setq arg 1))
  1151.    ((equal arg 'jpython) (setq arg -1)))
  1152.   (let (msg)
  1153.     (cond
  1154.      ((< 0 arg)
  1155.       ;; set to CPython
  1156.       (setq py-which-shell py-python-command
  1157.         py-which-args py-python-command-args
  1158.         py-which-bufname "Python"
  1159.         msg "CPython"
  1160.         mode-name "Python"))
  1161.      ((> 0 arg)
  1162.       (setq py-which-shell py-jpython-command
  1163.         py-which-args py-jpython-command-args
  1164.         py-which-bufname "JPython"
  1165.         msg "JPython"
  1166.         mode-name "JPython"))
  1167.      )
  1168.     (message "Using the %s shell" msg)
  1169.     (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
  1170.  
  1171. ;;;###autoload
  1172. (defun py-shell (&optional argprompt)
  1173.   "Start an interactive Python interpreter in another window.
  1174. This is like Shell mode, except that Python is running in the window
  1175. instead of a shell.  See the `Interactive Shell' and `Shell Mode'
  1176. sections of the Emacs manual for details, especially for the key
  1177. bindings active in the `*Python*' buffer.
  1178.  
  1179. With optional \\[universal-argument], the user is prompted for the
  1180. flags to pass to the Python interpreter.  This has no effect when this
  1181. command is used to switch to an existing process, only when a new
  1182. process is started.  If you use this, you will probably want to ensure
  1183. that the current arguments are retained (they will be included in the
  1184. prompt).  This argument is ignored when this function is called
  1185. programmatically, or when running in Emacs 19.34 or older.
  1186.  
  1187. Note: You can toggle between using the CPython interpreter and the
  1188. JPython interpreter by hitting \\[py-toggle-shells].  This toggles
  1189. buffer local variables which control whether all your subshell
  1190. interactions happen to the `*JPython*' or `*Python*' buffers (the
  1191. latter is the name used for the CPython buffer).
  1192.  
  1193. Warning: Don't use an interactive Python if you change sys.ps1 or
  1194. sys.ps2 from their default values, or if you're running code that
  1195. prints `>>> ' or `... ' at the start of a line.  `python-mode' can't
  1196. distinguish your output from Python's output, and assumes that `>>> '
  1197. at the start of a line is a prompt from Python.  Similarly, the Emacs
  1198. Shell mode code assumes that both `>>> ' and `... ' at the start of a
  1199. line are Python prompts.  Bad things can happen if you fool either
  1200. mode.
  1201.  
  1202. Warning:  If you do any editing *in* the process buffer *while* the
  1203. buffer is accepting output from Python, do NOT attempt to `undo' the
  1204. changes.  Some of the output (nowhere near the parts you changed!) may
  1205. be lost if you do.  This appears to be an Emacs bug, an unfortunate
  1206. interaction between undo and process filters; the same problem exists in
  1207. non-Python process buffers using the default (Emacs-supplied) process
  1208. filter."
  1209.   (interactive "P")
  1210.   ;; Set the default shell if not already set
  1211.   (when (null py-which-shell)
  1212.     (py-toggle-shells py-default-interpreter))
  1213.   (let ((args py-which-args))
  1214.     (when (and argprompt
  1215.            (interactive-p)
  1216.            (fboundp 'split-string))
  1217.       ;; TBD: Perhaps force "-i" in the final list?
  1218.       (setq args (split-string
  1219.           (read-string (concat py-which-bufname
  1220.                        " arguments: ")
  1221.                    (concat
  1222.                 (mapconcat 'identity py-which-args " ") " ")
  1223.                    ))))
  1224.     (switch-to-buffer-other-window
  1225.      (apply 'make-comint py-which-bufname py-which-shell nil args))
  1226.     (make-local-variable 'comint-prompt-regexp)
  1227.     (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
  1228.     (add-hook 'comint-output-filter-functions
  1229.           'py-comint-output-filter-function)
  1230.     (set-syntax-table py-mode-syntax-table)
  1231.     (use-local-map py-shell-map)
  1232.     ))
  1233.  
  1234. (defun py-clear-queue ()
  1235.   "Clear the queue of temporary files waiting to execute."
  1236.   (interactive)
  1237.   (let ((n (length py-file-queue)))
  1238.     (mapcar 'delete-file py-file-queue)
  1239.     (setq py-file-queue nil)
  1240.     (message "%d pending files de-queued." n)))
  1241.  
  1242.  
  1243. (defun py-execute-region (start end &optional async)
  1244.   "Execute the region in a Python interpreter.
  1245.  
  1246. The region is first copied into a temporary file (in the directory
  1247. `py-temp-directory').  If there is no Python interpreter shell
  1248. running, this file is executed synchronously using
  1249. `shell-command-on-region'.  If the program is long running, use
  1250. \\[universal-argument] to run the command asynchronously in its own
  1251. buffer.
  1252.  
  1253. When this function is used programmatically, arguments START and END
  1254. specify the region to execute, and optional third argument ASYNC, if
  1255. non-nil, specifies to run the command asynchronously in its own
  1256. buffer.
  1257.  
  1258. If the Python interpreter shell is running, the region is execfile()'d
  1259. in that shell.  If you try to execute regions too quickly,
  1260. `python-mode' will queue them up and execute them one at a time when
  1261. it sees a `>>> ' prompt from Python.  Each time this happens, the
  1262. process buffer is popped into a window (if it's not already in some
  1263. window) so you can see it, and a comment of the form
  1264.  
  1265.     \t## working on region in file <name>...
  1266.  
  1267. is inserted at the end.  See also the command `py-clear-queue'."
  1268.   (interactive "r\nP")
  1269.   (or (< start end)
  1270.       (error "Region is empty"))
  1271.   (let* ((proc (get-process py-which-bufname))
  1272.      (temp (if (memq 'broken-temp-names py-emacs-features)
  1273.            (let
  1274.                ((sn py-serial-number)
  1275.             (pid (and (fboundp 'emacs-pid) (emacs-pid))))
  1276.              (setq py-serial-number (1+ py-serial-number))
  1277.              (if pid
  1278.              (format "python-%d-%d" sn pid)
  1279.                (format "python-%d" sn)))
  1280.          (make-temp-name "python-")))
  1281.      (file (expand-file-name temp py-temp-directory))
  1282.      (cur (current-buffer))
  1283.      (buf (get-buffer-create file)))
  1284.     ;; Write the contents of the buffer, watching out for indented regions.
  1285.     (save-excursion
  1286.       (goto-char start)
  1287.       (let ((needs-if (/= (py-point 'bol) (py-point 'boi))))
  1288.     (set-buffer buf)
  1289.     (when needs-if
  1290.       (insert "if 1:\n"))
  1291.     (insert-buffer-substring cur start end)))
  1292.     (cond
  1293.      ;; always run the code in its own asynchronous subprocess
  1294.      (async
  1295.       ;; User explicitly wants this to run in its own async subprocess
  1296.       (save-excursion
  1297.     (set-buffer buf)
  1298.     (write-region (point-min) (point-max) file nil 'nomsg))
  1299.       (let* ((buf (generate-new-buffer-name py-output-buffer))
  1300.          ;; TBD: a horrible hack, but why create new Custom variables?
  1301.          (arg (if (string-equal py-which-bufname "Python")
  1302.               "-u" "")))
  1303.     (start-process py-which-bufname buf py-which-shell arg file)
  1304.     (pop-to-buffer buf)
  1305.     (py-postprocess-output-buffer buf)
  1306.     ;; TBD: clean up the temporary file!
  1307.     ))
  1308.      ;; if the Python interpreter shell is running, queue it up for
  1309.      ;; execution there.
  1310.      (proc
  1311.       ;; use the existing python shell
  1312.       (save-excursion
  1313.     (set-buffer buf)
  1314.     (write-region (point-min) (point-max) file nil 'nomsg))
  1315.       (if (not py-file-queue)
  1316.       (py-execute-file proc file)
  1317.     (message "File %s queued for execution" file))
  1318.       (setq py-file-queue (append py-file-queue (list file)))
  1319.       (setq py-exception-buffer (cons file (current-buffer))))
  1320.      (t
  1321.       ;; TBD: a horrible hack, buy why create new Custom variables?
  1322.       (let ((cmd (concat py-which-shell
  1323.              (if (string-equal py-which-bufname "JPython")
  1324.                  " -" ""))))
  1325.     ;; otherwise either run it synchronously in a subprocess
  1326.     (save-excursion
  1327.       (set-buffer buf)
  1328.       (shell-command-on-region (point-min) (point-max)
  1329.                    cmd py-output-buffer))
  1330.     ;; shell-command-on-region kills the output buffer if it never
  1331.     ;; existed and there's no output from the command
  1332.     (if (not (get-buffer py-output-buffer))
  1333.         (message "No output.")
  1334.       (setq py-exception-buffer (current-buffer))
  1335.       (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
  1336.         (pop-to-buffer py-output-buffer)
  1337.         (if err-p
  1338.         (pop-to-buffer py-exception-buffer)))
  1339.       ))
  1340.       ;; TBD: delete the buffer
  1341.       )
  1342.      )))
  1343.  
  1344.  
  1345. ;; Code execution commands
  1346. (defun py-execute-buffer (&optional async)
  1347.   "Send the contents of the buffer to a Python interpreter.
  1348. If the file local variable `py-master-file' is non-nil, execute the
  1349. named file instead of the buffer's file.
  1350.  
  1351. If there is a *Python* process buffer it is used.  If a clipping
  1352. restriction is in effect, only the accessible portion of the buffer is
  1353. sent.  A trailing newline will be supplied if needed.
  1354.  
  1355. See the `\\[py-execute-region]' docs for an account of some
  1356. subtleties, including the use of the optional ASYNC argument."
  1357.   (interactive "P")
  1358.   (if py-master-file
  1359.       (let* ((filename (expand-file-name py-master-file))
  1360.          (buffer (or (get-file-buffer filename)
  1361.              (find-file-noselect filename))))
  1362.     (set-buffer buffer)))
  1363.   (py-execute-region (point-min) (point-max) async))
  1364.  
  1365. (defun py-execute-import-or-reload (&optional async)
  1366.   "Import the current buffer's file in a Python interpreter.
  1367.  
  1368. If the file has already been imported, then do reload instead to get
  1369. the latest version.
  1370.  
  1371. If the file's name does not end in \".py\", then do execfile instead.
  1372.  
  1373. If the current buffer is not visiting a file, do `py-execute-buffer'
  1374. instead.
  1375.  
  1376. If the file local variable `py-master-file' is non-nil, import or
  1377. reload the named file instead of the buffer's file.  The file may be
  1378. saved based on the value of `py-execute-import-or-reload-save-p'.
  1379.  
  1380. See the `\\[py-execute-region]' docs for an account of some
  1381. subtleties, including the use of the optional ASYNC argument.
  1382.  
  1383. This may be preferable to `\\[py-execute-buffer]' because:
  1384.  
  1385.  - Definitions stay in their module rather than appearing at top
  1386.    level, where they would clutter the global namespace and not affect
  1387.    uses of qualified names (MODULE.NAME).
  1388.  
  1389.  - The Python debugger gets line number information about the functions."
  1390.   (interactive "P")
  1391.   ;; Check file local variable py-master-file
  1392.   (if py-master-file
  1393.       (let* ((filename (expand-file-name py-master-file))
  1394.              (buffer (or (get-file-buffer filename)
  1395.                          (find-file-noselect filename))))
  1396.         (set-buffer buffer)))
  1397.   (let ((file (buffer-file-name (current-buffer))))
  1398.     (if file
  1399.         (progn
  1400.       ;; Maybe save some buffers
  1401.       (save-some-buffers (not py-ask-about-save) nil)
  1402.           (py-execute-string
  1403.            (if (string-match "\\.py$" file)
  1404.                (let ((f (file-name-sans-extension
  1405.              (file-name-nondirectory file))))
  1406.                  (format "if globals().has_key('%s'):\n    reload(%s)\nelse:\n    import %s\n"
  1407.                          f f f))
  1408.              (format "execfile(r'%s')\n" file))
  1409.            async))
  1410.       ;; else
  1411.       (py-execute-buffer async))))
  1412.  
  1413.  
  1414. (defun py-execute-def-or-class (&optional async)
  1415.   "Send the current function or class definition to a Python interpreter.
  1416.  
  1417. If there is a *Python* process buffer it is used.
  1418.  
  1419. See the `\\[py-execute-region]' docs for an account of some
  1420. subtleties, including the use of the optional ASYNC argument."
  1421.   (interactive "P")
  1422.   (save-excursion
  1423.     (py-mark-def-or-class)
  1424.     ;; mark is before point
  1425.     (py-execute-region (mark) (point) async)))
  1426.  
  1427.  
  1428. (defun py-execute-string (string &optional async)
  1429.   "Send the argument STRING to a Python interpreter.
  1430.  
  1431. If there is a *Python* process buffer it is used.
  1432.  
  1433. See the `\\[py-execute-region]' docs for an account of some
  1434. subtleties, including the use of the optional ASYNC argument."
  1435.   (interactive "sExecute Python command: ")
  1436.   (save-excursion
  1437.     (set-buffer (get-buffer-create
  1438.                  (generate-new-buffer-name " *Python Command*")))
  1439.     (insert string)
  1440.     (py-execute-region (point-min) (point-max) async)))
  1441.  
  1442.  
  1443.  
  1444. (defun py-jump-to-exception (file line)
  1445.   "Jump to the Python code in FILE at LINE."
  1446.   (let ((buffer (cond ((string-equal file "<stdin>")
  1447.                (if (consp py-exception-buffer)
  1448.                (cdr py-exception-buffer)
  1449.              py-exception-buffer))
  1450.               ((and (consp py-exception-buffer)
  1451.                 (string-equal file (car py-exception-buffer)))
  1452.                (cdr py-exception-buffer))
  1453.               ((py-safe (find-file-noselect file)))
  1454.               ;; could not figure out what file the exception
  1455.               ;; is pointing to, so prompt for it
  1456.               (t (find-file (read-file-name "Exception file: "
  1457.                             nil
  1458.                             file t))))))
  1459.     (pop-to-buffer buffer)
  1460.     ;; Force Python mode
  1461.     (if (not (eq major-mode 'python-mode))
  1462.     (python-mode))
  1463.     (goto-line line)
  1464.     (message "Jumping to exception in file %s on line %d" file line)))
  1465.  
  1466. (defun py-mouseto-exception (event)
  1467.   "Jump to the code which caused the Python exception at EVENT.
  1468. EVENT is usually a mouse click."
  1469.   (interactive "e")
  1470.   (cond
  1471.    ((fboundp 'event-point)
  1472.     ;; XEmacs
  1473.     (let* ((point (event-point event))
  1474.        (buffer (event-buffer event))
  1475.        (e (and point buffer (extent-at point buffer 'py-exc-info)))
  1476.        (info (and e (extent-property e 'py-exc-info))))
  1477.       (message "Event point: %d, info: %s" point info)
  1478.       (and info
  1479.        (py-jump-to-exception (car info) (cdr info)))
  1480.       ))
  1481.    ;; Emacs -- Please port this!
  1482.    ))
  1483.  
  1484. (defun py-goto-exception ()
  1485.   "Go to the line indicated by the traceback."
  1486.   (interactive)
  1487.   (let (file line)
  1488.     (save-excursion
  1489.       (beginning-of-line)
  1490.       (if (looking-at py-traceback-line-re)
  1491.       (setq file (match-string 1)
  1492.         line (string-to-int (match-string 2)))))
  1493.     (if (not file)
  1494.     (error "Not on a traceback line"))
  1495.     (py-jump-to-exception file line)))
  1496.  
  1497. (defun py-find-next-exception (start buffer searchdir errwhere)
  1498.   "Find the next Python exception and jump to the code that caused it.
  1499. START is the buffer position in BUFFER from which to begin searching
  1500. for an exception.  SEARCHDIR is a function, either
  1501. `re-search-backward' or `re-search-forward' indicating the direction
  1502. to search.  ERRWHERE is used in an error message if the limit (top or
  1503. bottom) of the trackback stack is encountered."
  1504.   (let (file line)
  1505.     (save-excursion
  1506.       (set-buffer buffer)
  1507.       (goto-char (py-point start))
  1508.       (if (funcall searchdir py-traceback-line-re nil t)
  1509.       (setq file (match-string 1)
  1510.         line (string-to-int (match-string 2)))))
  1511.     (if (and file line)
  1512.     (py-jump-to-exception file line)
  1513.       (error "%s of traceback" errwhere))))
  1514.  
  1515. (defun py-down-exception (&optional bottom)
  1516.   "Go to the next line down in the traceback.
  1517. With \\[univeral-argument] (programmatically, optional argument
  1518. BOTTOM), jump to the bottom (innermost) exception in the exception
  1519. stack."
  1520.   (interactive "P")
  1521.   (let* ((proc (get-process "Python"))
  1522.      (buffer (if proc "*Python*" py-output-buffer)))
  1523.     (if bottom
  1524.     (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
  1525.       (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
  1526.  
  1527. (defun py-up-exception (&optional top)
  1528.   "Go to the previous line up in the traceback.
  1529. With \\[universal-argument] (programmatically, optional argument TOP)
  1530. jump to the top (outermost) exception in the exception stack."
  1531.   (interactive "P")
  1532.   (let* ((proc (get-process "Python"))
  1533.      (buffer (if proc "*Python*" py-output-buffer)))
  1534.     (if top
  1535.     (py-find-next-exception 'bob buffer 're-search-forward "Top")
  1536.       (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
  1537.  
  1538.  
  1539. ;; Electric deletion
  1540. (defun py-electric-backspace (arg)
  1541.   "Delete preceding character or levels of indentation.
  1542. Deletion is performed by calling the function in `py-backspace-function'
  1543. with a single argument (the number of characters to delete).
  1544.  
  1545. If point is at the leftmost column, delete the preceding newline.
  1546.  
  1547. Otherwise, if point is at the leftmost non-whitespace character of a
  1548. line that is neither a continuation line nor a non-indenting comment
  1549. line, or if point is at the end of a blank line, this command reduces
  1550. the indentation to match that of the line that opened the current
  1551. block of code.  The line that opened the block is displayed in the
  1552. echo area to help you keep track of where you are.  With
  1553. \\[universal-argument] dedents that many blocks (but not past column
  1554. zero).
  1555.  
  1556. Otherwise the preceding character is deleted, converting a tab to
  1557. spaces if needed so that only a single column position is deleted.
  1558. \\[universal-argument] specifies how many characters to delete;
  1559. default is 1.
  1560.  
  1561. When used programmatically, argument ARG specifies the number of
  1562. blocks to dedent, or the number of characters to delete, as indicated
  1563. above."
  1564.   (interactive "*p")
  1565.   (if (or (/= (current-indentation) (current-column))
  1566.       (bolp)
  1567.       (py-continuation-line-p)
  1568. ;      (not py-honor-comment-indentation)
  1569. ;      (looking-at "#[^ \t\n]")    ; non-indenting #
  1570.       )
  1571.       (funcall py-backspace-function arg)
  1572.     ;; else indent the same as the colon line that opened the block
  1573.     ;; force non-blank so py-goto-block-up doesn't ignore it
  1574.     (insert-char ?* 1)
  1575.     (backward-char)
  1576.     (let ((base-indent 0)        ; indentation of base line
  1577.       (base-text "")        ; and text of base line
  1578.       (base-found-p nil))
  1579.       (save-excursion
  1580.     (while (< 0 arg)
  1581.       (condition-case nil        ; in case no enclosing block
  1582.           (progn
  1583.         (py-goto-block-up 'no-mark)
  1584.         (setq base-indent (current-indentation)
  1585.               base-text   (py-suck-up-leading-text)
  1586.               base-found-p t))
  1587.         (error nil))
  1588.       (setq arg (1- arg))))
  1589.       (delete-char 1)            ; toss the dummy character
  1590.       (delete-horizontal-space)
  1591.       (indent-to base-indent)
  1592.       (if base-found-p
  1593.       (message "Closes block: %s" base-text)))))
  1594.  
  1595.  
  1596. (defun py-electric-delete (arg)
  1597.   "Delete preceding or following character or levels of whitespace.
  1598.  
  1599. The behavior of this function depends on the variable
  1600. `delete-key-deletes-forward'.  If this variable is nil (or does not
  1601. exist, as in older Emacsen and non-XEmacs versions), then this
  1602. function behaves identically to \\[c-electric-backspace].
  1603.  
  1604. If `delete-key-deletes-forward' is non-nil and is supported in your
  1605. Emacs, then deletion occurs in the forward direction, by calling the
  1606. function in `py-delete-function'.
  1607.  
  1608. \\[universal-argument] (programmatically, argument ARG) specifies the
  1609. number of characters to delete (default is 1)."
  1610.   (interactive "*p")
  1611.   (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
  1612.            (delete-forward-p))
  1613.       (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
  1614.            delete-key-deletes-forward))
  1615.       (funcall py-delete-function arg)
  1616.     (py-electric-backspace arg)))
  1617.  
  1618. ;; required for pending-del and delsel modes
  1619. (put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
  1620. (put 'py-electric-backspace 'pending-delete   'supersede) ;pending-del
  1621. (put 'py-electric-delete    'delete-selection 'supersede) ;delsel
  1622. (put 'py-electric-delete    'pending-delete   'supersede) ;pending-del
  1623.  
  1624.  
  1625.  
  1626. (defun py-indent-line (&optional arg)
  1627.   "Fix the indentation of the current line according to Python rules.
  1628. With \\[universal-argument] (programmatically, the optional argument
  1629. ARG non-nil), ignore dedenting rules for block closing statements
  1630. (e.g. return, raise, break, continue, pass)
  1631.  
  1632. This function is normally bound to `indent-line-function' so
  1633. \\[indent-for-tab-command] will call it."
  1634.   (interactive "P")
  1635.   (let* ((ci (current-indentation))
  1636.      (move-to-indentation-p (<= (current-column) ci))
  1637.      (need (py-compute-indentation (not arg))))
  1638.     ;; see if we need to dedent
  1639.     (if (py-outdent-p)
  1640.     (setq need (- need py-indent-offset)))
  1641.     (if (/= ci need)
  1642.     (save-excursion
  1643.       (beginning-of-line)
  1644.       (delete-horizontal-space)
  1645.       (indent-to need)))
  1646.     (if move-to-indentation-p (back-to-indentation))))
  1647.  
  1648. (defun py-newline-and-indent ()
  1649.   "Strives to act like the Emacs `newline-and-indent'.
  1650. This is just `strives to' because correct indentation can't be computed
  1651. from scratch for Python code.  In general, deletes the whitespace before
  1652. point, inserts a newline, and takes an educated guess as to how you want
  1653. the new line indented."
  1654.   (interactive)
  1655.   (let ((ci (current-indentation)))
  1656.     (if (< ci (current-column))        ; if point beyond indentation
  1657.     (newline-and-indent)
  1658.       ;; else try to act like newline-and-indent "normally" acts
  1659.       (beginning-of-line)
  1660.       (insert-char ?\n 1)
  1661.       (move-to-column ci))))
  1662.  
  1663. (defun py-compute-indentation (honor-block-close-p)
  1664.   "Compute Python indentation.
  1665. When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
  1666. `raise', `break', `continue', and `pass' force one level of
  1667. dedenting."
  1668.   (save-excursion
  1669.     (beginning-of-line)
  1670.     (let* ((bod (py-point 'bod))
  1671.        (pps (parse-partial-sexp bod (point)))
  1672.        (boipps (parse-partial-sexp bod (py-point 'boi)))
  1673.        placeholder)
  1674.       (cond
  1675.        ;; are we inside a multi-line string or comment?
  1676.        ((or (and (nth 3 pps) (nth 3 boipps))
  1677.         (and (nth 4 pps) (nth 4 boipps)))
  1678.     (save-excursion
  1679.       (if (not py-align-multiline-strings-p) 0
  1680.         ;; skip back over blank & non-indenting comment lines
  1681.         ;; note: will skip a blank or non-indenting comment line
  1682.         ;; that happens to be a continuation line too
  1683.         (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
  1684.         (back-to-indentation)
  1685.         (current-column))))
  1686.        ;; are we on a continuation line?
  1687.        ((py-continuation-line-p)
  1688.     (let ((startpos (point))
  1689.           (open-bracket-pos (py-nesting-level))
  1690.           endpos searching found state)
  1691.       (if open-bracket-pos
  1692.           (progn
  1693.         ;; align with first item in list; else a normal
  1694.         ;; indent beyond the line with the open bracket
  1695.         (goto-char (1+ open-bracket-pos)) ; just beyond bracket
  1696.         ;; is the first list item on the same line?
  1697.         (skip-chars-forward " \t")
  1698.         (if (null (memq (following-char) '(?\n ?# ?\\)))
  1699.                     ; yes, so line up with it
  1700.             (current-column)
  1701.           ;; first list item on another line, or doesn't exist yet
  1702.           (forward-line 1)
  1703.           (while (and (< (point) startpos)
  1704.                   (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
  1705.             (forward-line 1))
  1706.           (if (and (< (point) startpos)
  1707.                (/= startpos
  1708.                    (save-excursion
  1709.                  (goto-char (1+ open-bracket-pos))
  1710.                  (forward-comment (point-max))
  1711.                  (point))))
  1712.               ;; again mimic the first list item
  1713.               (current-indentation)
  1714.             ;; else they're about to enter the first item
  1715.             (goto-char open-bracket-pos)
  1716.             (setq placeholder (point))
  1717.             (py-goto-initial-line)
  1718.             (py-goto-beginning-of-tqs
  1719.              (save-excursion (nth 3 (parse-partial-sexp
  1720.                          placeholder (point)))))
  1721.             (+ (current-indentation) py-indent-offset))))
  1722.  
  1723.         ;; else on backslash continuation line
  1724.         (forward-line -1)
  1725.         (if (py-continuation-line-p) ; on at least 3rd line in block
  1726.         (current-indentation)    ; so just continue the pattern
  1727.           ;; else started on 2nd line in block, so indent more.
  1728.           ;; if base line is an assignment with a start on a RHS,
  1729.           ;; indent to 2 beyond the leftmost "="; else skip first
  1730.           ;; chunk of non-whitespace characters on base line, + 1 more
  1731.           ;; column
  1732.           (end-of-line)
  1733.           (setq endpos (point)  searching t)
  1734.           (back-to-indentation)
  1735.           (setq startpos (point))
  1736.           ;; look at all "=" from left to right, stopping at first
  1737.           ;; one not nested in a list or string
  1738.           (while searching
  1739.         (skip-chars-forward "^=" endpos)
  1740.         (if (= (point) endpos)
  1741.             (setq searching nil)
  1742.           (forward-char 1)
  1743.           (setq state (parse-partial-sexp startpos (point)))
  1744.           (if (and (zerop (car state)) ; not in a bracket
  1745.                (null (nth 3 state))) ; & not in a string
  1746.               (progn
  1747.             (setq searching nil) ; done searching in any case
  1748.             (setq found
  1749.                   (not (or
  1750.                     (eq (following-char) ?=)
  1751.                     (memq (char-after (- (point) 2))
  1752.                       '(?< ?> ?!)))))))))
  1753.           (if (or (not found)    ; not an assignment
  1754.               (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
  1755.           (progn
  1756.             (goto-char startpos)
  1757.             (skip-chars-forward "^ \t\n")))
  1758.           (1+ (current-column))))))
  1759.  
  1760.        ;; not on a continuation line
  1761.        ((bobp) (current-indentation))
  1762.  
  1763.        ;; Dfn: "Indenting comment line".  A line containing only a
  1764.        ;; comment, but which is treated like a statement for
  1765.        ;; indentation calculation purposes.  Such lines are only
  1766.        ;; treated specially by the mode; they are not treated
  1767.        ;; specially by the Python interpreter.
  1768.  
  1769.        ;; The rules for indenting comment lines are a line where:
  1770.        ;;   - the first non-whitespace character is `#', and
  1771.        ;;   - the character following the `#' is whitespace, and
  1772.        ;;   - the line is dedented with respect to (i.e. to the left
  1773.        ;;     of) the indentation of the preceding non-blank line.
  1774.  
  1775.        ;; The first non-blank line following an indenting comment
  1776.        ;; line is given the same amount of indentation as the
  1777.        ;; indenting comment line.
  1778.  
  1779.        ;; All other comment-only lines are ignored for indentation
  1780.        ;; purposes.
  1781.  
  1782.        ;; Are we looking at a comment-only line which is *not* an
  1783.        ;; indenting comment line?  If so, we assume that it's been
  1784.        ;; placed at the desired indentation, so leave it alone.
  1785.        ;; Indenting comment lines are aligned as statements down
  1786.        ;; below.
  1787.        ((and (looking-at "[ \t]*#[^ \t\n]")
  1788.          ;; NOTE: this test will not be performed in older Emacsen
  1789.          (fboundp 'forward-comment)
  1790.          (<= (current-indentation)
  1791.          (save-excursion
  1792.            (forward-comment (- (point-max)))
  1793.            (current-indentation))))
  1794.     (current-indentation))
  1795.  
  1796.        ;; else indentation based on that of the statement that
  1797.        ;; precedes us; use the first line of that statement to
  1798.        ;; establish the base, in case the user forced a non-std
  1799.        ;; indentation for the continuation lines (if any)
  1800.        (t
  1801.     ;; skip back over blank & non-indenting comment lines note:
  1802.     ;; will skip a blank or non-indenting comment line that
  1803.     ;; happens to be a continuation line too.  use fast Emacs 19
  1804.     ;; function if it's there.
  1805.     (if (and (eq py-honor-comment-indentation nil)
  1806.          (fboundp 'forward-comment))
  1807.         (forward-comment (- (point-max)))
  1808.       (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
  1809.         done)
  1810.         (while (not done)
  1811.           (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
  1812.           (setq done (or (bobp)
  1813.                  (and (eq py-honor-comment-indentation t)
  1814.                   (save-excursion
  1815.                     (back-to-indentation)
  1816.                     (not (looking-at prefix-re))
  1817.                     ))
  1818.                  (and (not (eq py-honor-comment-indentation t))
  1819.                   (save-excursion
  1820.                     (back-to-indentation)
  1821.                     (not (zerop (current-column)))))
  1822.                  ))
  1823.           )))
  1824.     ;; if we landed inside a string, go to the beginning of that
  1825.     ;; string. this handles triple quoted, multi-line spanning
  1826.     ;; strings.
  1827.     (py-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
  1828.     ;; now skip backward over continued lines
  1829.     (setq placeholder (point))
  1830.     (py-goto-initial-line)
  1831.     ;; we may *now* have landed in a TQS, so find the beginning of
  1832.     ;; this string.
  1833.     (py-goto-beginning-of-tqs
  1834.      (save-excursion (nth 3 (parse-partial-sexp
  1835.                  placeholder (point)))))
  1836.     (+ (current-indentation)
  1837.        (if (py-statement-opens-block-p)
  1838.            py-indent-offset
  1839.          (if (and honor-block-close-p (py-statement-closes-block-p))
  1840.          (- py-indent-offset)
  1841.            0)))
  1842.     )))))
  1843.  
  1844. (defun py-guess-indent-offset (&optional global)
  1845.   "Guess a good value for, and change, `py-indent-offset'.
  1846.  
  1847. By default, make a buffer-local copy of `py-indent-offset' with the
  1848. new value, so that other Python buffers are not affected.  With
  1849. \\[universal-argument] (programmatically, optional argument GLOBAL),
  1850. change the global value of `py-indent-offset'.  This affects all
  1851. Python buffers (that don't have their own buffer-local copy), both
  1852. those currently existing and those created later in the Emacs session.
  1853.  
  1854. Some people use a different value for `py-indent-offset' than you use.
  1855. There's no excuse for such foolishness, but sometimes you have to deal
  1856. with their ugly code anyway.  This function examines the file and sets
  1857. `py-indent-offset' to what it thinks it was when they created the
  1858. mess.
  1859.  
  1860. Specifically, it searches forward from the statement containing point,
  1861. looking for a line that opens a block of code.  `py-indent-offset' is
  1862. set to the difference in indentation between that line and the Python
  1863. statement following it.  If the search doesn't succeed going forward,
  1864. it's tried again going backward."
  1865.   (interactive "P")            ; raw prefix arg
  1866.   (let (new-value
  1867.     (start (point))
  1868.     (restart (point))
  1869.     (found nil)
  1870.     colon-indent)
  1871.     (py-goto-initial-line)
  1872.     (while (not (or found (eobp)))
  1873.       (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  1874.          (not (py-in-literal restart)))
  1875.     (setq restart (point))
  1876.     (py-goto-initial-line)
  1877.     (if (py-statement-opens-block-p)
  1878.         (setq found t)
  1879.       (goto-char restart))))
  1880.     (unless found
  1881.       (goto-char start)
  1882.       (py-goto-initial-line)
  1883.       (while (not (or found (bobp)))
  1884.     (setq found (and
  1885.              (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  1886.              (or (py-goto-initial-line) t) ; always true -- side effect
  1887.              (py-statement-opens-block-p)))))
  1888.     (setq colon-indent (current-indentation)
  1889.       found (and found (zerop (py-next-statement 1)))
  1890.       new-value (- (current-indentation) colon-indent))
  1891.     (goto-char start)
  1892.     (if (not found)
  1893.     (error "Sorry, couldn't guess a value for py-indent-offset")
  1894.       (funcall (if global 'kill-local-variable 'make-local-variable)
  1895.            'py-indent-offset)
  1896.       (setq py-indent-offset new-value)
  1897.       (or noninteractive
  1898.       (message "%s value of py-indent-offset set to %d"
  1899.            (if global "Global" "Local")
  1900.            py-indent-offset)))
  1901.     ))
  1902.  
  1903. (defun py-comment-indent-function ()
  1904.   "Python version of `comment-indent-function'."
  1905.   ;; This is required when filladapt is turned off.  Without it, when
  1906.   ;; filladapt is not used, comments which start in column zero
  1907.   ;; cascade one character to the right
  1908.   (save-excursion
  1909.     (beginning-of-line)
  1910.     (let ((eol (py-point 'eol)))
  1911.       (and comment-start-skip
  1912.        (re-search-forward comment-start-skip eol t)
  1913.        (setq eol (match-beginning 0)))
  1914.       (goto-char eol)
  1915.       (skip-chars-backward " \t")
  1916.       (max comment-column (+ (current-column) (if (bolp) 0 1)))
  1917.       )))
  1918.  
  1919. (defun py-narrow-to-defun (&optional class)
  1920.   "Make text outside current defun invisible.
  1921. The defun visible is the one that contains point or follows point.
  1922. Optional CLASS is passed directly to `py-beginning-of-def-or-class'."
  1923.   (interactive "P")
  1924.   (save-excursion
  1925.     (widen)
  1926.     (py-end-of-def-or-class class)
  1927.     (let ((end (point)))
  1928.       (py-beginning-of-def-or-class class)
  1929.       (narrow-to-region (point) end))))
  1930.  
  1931.  
  1932. (defun py-shift-region (start end count)
  1933.   "Indent lines from START to END by COUNT spaces."
  1934.   (save-excursion
  1935.     (goto-char end)
  1936.     (beginning-of-line)
  1937.     (setq end (point))
  1938.     (goto-char start)
  1939.     (beginning-of-line)
  1940.     (setq start (point))
  1941.     (indent-rigidly start end count)))
  1942.  
  1943. (defun py-shift-region-left (start end &optional count)
  1944.   "Shift region of Python code to the left.
  1945. The lines from the line containing the start of the current region up
  1946. to (but not including) the line containing the end of the region are
  1947. shifted to the left, by `py-indent-offset' columns.
  1948.  
  1949. If a prefix argument is given, the region is instead shifted by that
  1950. many columns.  With no active region, dedent only the current line.
  1951. You cannot dedent the region if any line is already at column zero."
  1952.   (interactive
  1953.    (let ((p (point))
  1954.      (m (mark))
  1955.      (arg current-prefix-arg))
  1956.      (if m
  1957.      (list (min p m) (max p m) arg)
  1958.        (list p (save-excursion (forward-line 1) (point)) arg))))
  1959.   ;; if any line is at column zero, don't shift the region
  1960.   (save-excursion
  1961.     (goto-char start)
  1962.     (while (< (point) end)
  1963.       (back-to-indentation)
  1964.       (if (and (zerop (current-column))
  1965.            (not (looking-at "\\s *$")))
  1966.       (error "Region is at left edge"))
  1967.       (forward-line 1)))
  1968.   (py-shift-region start end (- (prefix-numeric-value
  1969.                  (or count py-indent-offset))))
  1970.   (py-keep-region-active))
  1971.  
  1972. (defun py-shift-region-right (start end &optional count)
  1973.   "Shift region of Python code to the right.
  1974. The lines from the line containing the start of the current region up
  1975. to (but not including) the line containing the end of the region are
  1976. shifted to the right, by `py-indent-offset' columns.
  1977.  
  1978. If a prefix argument is given, the region is instead shifted by that
  1979. many columns.  With no active region, indent only the current line."
  1980.   (interactive
  1981.    (let ((p (point))
  1982.      (m (mark))
  1983.      (arg current-prefix-arg))
  1984.      (if m
  1985.      (list (min p m) (max p m) arg)
  1986.        (list p (save-excursion (forward-line 1) (point)) arg))))
  1987.   (py-shift-region start end (prefix-numeric-value
  1988.                   (or count py-indent-offset)))
  1989.   (py-keep-region-active))
  1990.  
  1991. (defun py-indent-region (start end &optional indent-offset)
  1992.   "Reindent a region of Python code.
  1993.  
  1994. The lines from the line containing the start of the current region up
  1995. to (but not including) the line containing the end of the region are
  1996. reindented.  If the first line of the region has a non-whitespace
  1997. character in the first column, the first line is left alone and the
  1998. rest of the region is reindented with respect to it.  Else the entire
  1999. region is reindented with respect to the (closest code or indenting
  2000. comment) statement immediately preceding the region.
  2001.  
  2002. This is useful when code blocks are moved or yanked, when enclosing
  2003. control structures are introduced or removed, or to reformat code
  2004. using a new value for the indentation offset.
  2005.  
  2006. If a numeric prefix argument is given, it will be used as the value of
  2007. the indentation offset.  Else the value of `py-indent-offset' will be
  2008. used.
  2009.  
  2010. Warning: The region must be consistently indented before this function
  2011. is called!  This function does not compute proper indentation from
  2012. scratch (that's impossible in Python), it merely adjusts the existing
  2013. indentation to be correct in context.
  2014.  
  2015. Warning: This function really has no idea what to do with
  2016. non-indenting comment lines, and shifts them as if they were indenting
  2017. comment lines.  Fixing this appears to require telepathy.
  2018.  
  2019. Special cases: whitespace is deleted from blank lines; continuation
  2020. lines are shifted by the same amount their initial line was shifted,
  2021. in order to preserve their relative indentation with respect to their
  2022. initial line; and comment lines beginning in column 1 are ignored."
  2023.   (interactive "*r\nP")            ; region; raw prefix arg
  2024.   (save-excursion
  2025.     (goto-char end)   (beginning-of-line) (setq end (point-marker))
  2026.     (goto-char start) (beginning-of-line)
  2027.     (let ((py-indent-offset (prefix-numeric-value
  2028.                  (or indent-offset py-indent-offset)))
  2029.       (indents '(-1))        ; stack of active indent levels
  2030.       (target-column 0)        ; column to which to indent
  2031.       (base-shifted-by 0)        ; amount last base line was shifted
  2032.       (indent-base (if (looking-at "[ \t\n]")
  2033.                (py-compute-indentation t)
  2034.              0))
  2035.       ci)
  2036.       (while (< (point) end)
  2037.     (setq ci (current-indentation))
  2038.     ;; figure out appropriate target column
  2039.     (cond
  2040.      ((or (eq (following-char) ?#)    ; comment in column 1
  2041.           (looking-at "[ \t]*$"))    ; entirely blank
  2042.       (setq target-column 0))
  2043.      ((py-continuation-line-p)    ; shift relative to base line
  2044.       (setq target-column (+ ci base-shifted-by)))
  2045.      (t                ; new base line
  2046.       (if (> ci (car indents))    ; going deeper; push it
  2047.           (setq indents (cons ci indents))
  2048.         ;; else we should have seen this indent before
  2049.         (setq indents (memq ci indents)) ; pop deeper indents
  2050.         (if (null indents)
  2051.         (error "Bad indentation in region, at line %d"
  2052.                (save-restriction
  2053.              (widen)
  2054.              (1+ (count-lines 1 (point)))))))
  2055.       (setq target-column (+ indent-base
  2056.                  (* py-indent-offset
  2057.                     (- (length indents) 2))))
  2058.       (setq base-shifted-by (- target-column ci))))
  2059.     ;; shift as needed
  2060.     (if (/= ci target-column)
  2061.         (progn
  2062.           (delete-horizontal-space)
  2063.           (indent-to target-column)))
  2064.     (forward-line 1))))
  2065.   (set-marker end nil))
  2066.  
  2067. (defun py-comment-region (beg end &optional arg)
  2068.   "Like `comment-region' but uses double hash (`#') comment starter."
  2069.   (interactive "r\nP")
  2070.   (let ((comment-start py-block-comment-prefix))
  2071.     (comment-region beg end arg)))
  2072.  
  2073.  
  2074. ;; Functions for moving point
  2075. (defun py-previous-statement (count)
  2076.   "Go to the start of the COUNTth preceding Python statement.
  2077. By default, goes to the previous statement.  If there is no such
  2078. statement, goes to the first statement.  Return count of statements
  2079. left to move.  `Statements' do not include blank, comment, or
  2080. continuation lines."
  2081.   (interactive "p")            ; numeric prefix arg
  2082.   (if (< count 0) (py-next-statement (- count))
  2083.     (py-goto-initial-line)
  2084.     (let (start)
  2085.       (while (and
  2086.           (setq start (point))    ; always true -- side effect
  2087.           (> count 0)
  2088.           (zerop (forward-line -1))
  2089.           (py-goto-statement-at-or-above))
  2090.     (setq count (1- count)))
  2091.       (if (> count 0) (goto-char start)))
  2092.     count))
  2093.  
  2094. (defun py-next-statement (count)
  2095.   "Go to the start of next Python statement.
  2096. If the statement at point is the i'th Python statement, goes to the
  2097. start of statement i+COUNT.  If there is no such statement, goes to the
  2098. last statement.  Returns count of statements left to move.  `Statements'
  2099. do not include blank, comment, or continuation lines."
  2100.   (interactive "p")            ; numeric prefix arg
  2101.   (if (< count 0) (py-previous-statement (- count))
  2102.     (beginning-of-line)
  2103.     (let (start)
  2104.       (while (and
  2105.           (setq start (point))    ; always true -- side effect
  2106.           (> count 0)
  2107.           (py-goto-statement-below))
  2108.     (setq count (1- count)))
  2109.       (if (> count 0) (goto-char start)))
  2110.     count))
  2111.  
  2112. (defun py-goto-block-up (&optional nomark)
  2113.   "Move up to start of current block.
  2114. Go to the statement that starts the smallest enclosing block; roughly
  2115. speaking, this will be the closest preceding statement that ends with a
  2116. colon and is indented less than the statement you started on.  If
  2117. successful, also sets the mark to the starting point.
  2118.  
  2119. `\\[py-mark-block]' can be used afterward to mark the whole code
  2120. block, if desired.
  2121.  
  2122. If called from a program, the mark will not be set if optional argument
  2123. NOMARK is not nil."
  2124.   (interactive)
  2125.   (let ((start (point))
  2126.     (found nil)
  2127.     initial-indent)
  2128.     (py-goto-initial-line)
  2129.     ;; if on blank or non-indenting comment line, use the preceding stmt
  2130.     (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  2131.     (progn
  2132.       (py-goto-statement-at-or-above)
  2133.       (setq found (py-statement-opens-block-p))))
  2134.     ;; search back for colon line indented less
  2135.     (setq initial-indent (current-indentation))
  2136.     (if (zerop initial-indent)
  2137.     ;; force fast exit
  2138.     (goto-char (point-min)))
  2139.     (while (not (or found (bobp)))
  2140.       (setq found
  2141.         (and
  2142.          (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  2143.          (or (py-goto-initial-line) t) ; always true -- side effect
  2144.          (< (current-indentation) initial-indent)
  2145.          (py-statement-opens-block-p))))
  2146.     (if found
  2147.     (progn
  2148.       (or nomark (push-mark start))
  2149.       (back-to-indentation))
  2150.       (goto-char start)
  2151.       (error "Enclosing block not found"))))
  2152.  
  2153. (defun py-beginning-of-def-or-class (&optional class count)
  2154.   "Move point to start of `def' or `class'.
  2155.  
  2156. Searches back for the closest preceding `def'.  If you supply a prefix
  2157. arg, looks for a `class' instead.  The docs below assume the `def'
  2158. case; just substitute `class' for `def' for the other case.
  2159. Programmatically, if CLASS is `either', then moves to either `class'
  2160. or `def'.
  2161.  
  2162. When second optional argument is given programmatically, move to the
  2163. COUNTth start of `def'.
  2164.  
  2165. If point is in a `def' statement already, and after the `d', simply
  2166. moves point to the start of the statement.
  2167.  
  2168. Otherwise (i.e. when point is not in a `def' statement, or at or
  2169. before the `d' of a `def' statement), searches for the closest
  2170. preceding `def' statement, and leaves point at its start.  If no such
  2171. statement can be found, leaves point at the start of the buffer.
  2172.  
  2173. Returns t iff a `def' statement is found by these rules.
  2174.  
  2175. Note that doing this command repeatedly will take you closer to the
  2176. start of the buffer each time.
  2177.  
  2178. To mark the current `def', see `\\[py-mark-def-or-class]'."
  2179.   (interactive "P")            ; raw prefix arg
  2180.   (setq count (or count 1))
  2181.   (let ((at-or-before-p (<= (current-column) (current-indentation)))
  2182.     (start-of-line (goto-char (py-point 'bol)))
  2183.     (start-of-stmt (goto-char (py-point 'bos)))
  2184.     (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
  2185.             (class "^[ \t]*class\\>")
  2186.             (t "^[ \t]*def\\>")))
  2187.     )
  2188.     ;; searching backward
  2189.     (if (and (< 0 count)
  2190.          (or (/= start-of-stmt start-of-line)
  2191.          (not at-or-before-p)))
  2192.     (end-of-line))
  2193.     ;; search forward
  2194.     (if (and (> 0 count)
  2195.          (zerop (current-column))
  2196.          (looking-at start-re))
  2197.     (end-of-line))
  2198.     (if (re-search-backward start-re nil 'move count)
  2199.     (goto-char (match-beginning 0)))))
  2200.  
  2201. ;; Backwards compatibility
  2202. (defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
  2203.  
  2204. (defun py-end-of-def-or-class (&optional class count)
  2205.   "Move point beyond end of `def' or `class' body.
  2206.  
  2207. By default, looks for an appropriate `def'.  If you supply a prefix
  2208. arg, looks for a `class' instead.  The docs below assume the `def'
  2209. case; just substitute `class' for `def' for the other case.
  2210. Programmatically, if CLASS is `either', then moves to either `class'
  2211. or `def'.
  2212.  
  2213. When second optional argument is given programmatically, move to the
  2214. COUNTth end of `def'.
  2215.  
  2216. If point is in a `def' statement already, this is the `def' we use.
  2217.  
  2218. Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
  2219. contains the statement you started on, that's the `def' we use.
  2220.  
  2221. Otherwise, we search forward for the closest following `def', and use that.
  2222.  
  2223. If a `def' can be found by these rules, point is moved to the start of
  2224. the line immediately following the `def' block, and the position of the
  2225. start of the `def' is returned.
  2226.  
  2227. Else point is moved to the end of the buffer, and nil is returned.
  2228.  
  2229. Note that doing this command repeatedly will take you closer to the
  2230. end of the buffer each time.
  2231.  
  2232. To mark the current `def', see `\\[py-mark-def-or-class]'."
  2233.   (interactive "P")            ; raw prefix arg
  2234.   (if (and count (/= count 1))
  2235.       (py-beginning-of-def-or-class (- 1 count)))
  2236.   (let ((start (progn (py-goto-initial-line) (point)))
  2237.     (which (cond ((eq class 'either) "\\(class\\|def\\)")
  2238.              (class "class")
  2239.              (t "def")))
  2240.     (state 'not-found))
  2241.     ;; move point to start of appropriate def/class
  2242.     (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
  2243.     (setq state 'at-beginning)
  2244.       ;; else see if py-beginning-of-def-or-class hits container
  2245.       (if (and (py-beginning-of-def-or-class class)
  2246.            (progn (py-goto-beyond-block)
  2247.               (> (point) start)))
  2248.       (setq state 'at-end)
  2249.     ;; else search forward
  2250.     (goto-char start)
  2251.     (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
  2252.         (progn (setq state 'at-beginning)
  2253.            (beginning-of-line)))))
  2254.     (cond
  2255.      ((eq state 'at-beginning) (py-goto-beyond-block) t)
  2256.      ((eq state 'at-end) t)
  2257.      ((eq state 'not-found) nil)
  2258.      (t (error "Internal error in `py-end-of-def-or-class'")))))
  2259.  
  2260. ;; Backwards compabitility
  2261. (defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
  2262.  
  2263.  
  2264. ;; Functions for marking regions
  2265. (defun py-mark-block (&optional extend just-move)
  2266.   "Mark following block of lines.  With prefix arg, mark structure.
  2267. Easier to use than explain.  It sets the region to an `interesting'
  2268. block of succeeding lines.  If point is on a blank line, it goes down to
  2269. the next non-blank line.  That will be the start of the region.  The end
  2270. of the region depends on the kind of line at the start:
  2271.  
  2272.  - If a comment, the region will include all succeeding comment lines up
  2273.    to (but not including) the next non-comment line (if any).
  2274.  
  2275.  - Else if a prefix arg is given, and the line begins one of these
  2276.    structures:
  2277.  
  2278.      if elif else try except finally for while def class
  2279.  
  2280.    the region will be set to the body of the structure, including
  2281.    following blocks that `belong' to it, but excluding trailing blank
  2282.    and comment lines.  E.g., if on a `try' statement, the `try' block
  2283.    and all (if any) of the following `except' and `finally' blocks
  2284.    that belong to the `try' structure will be in the region.  Ditto
  2285.    for if/elif/else, for/else and while/else structures, and (a bit
  2286.    degenerate, since they're always one-block structures) def and
  2287.    class blocks.
  2288.  
  2289.  - Else if no prefix argument is given, and the line begins a Python
  2290.    block (see list above), and the block is not a `one-liner' (i.e.,
  2291.    the statement ends with a colon, not with code), the region will
  2292.    include all succeeding lines up to (but not including) the next
  2293.    code statement (if any) that's indented no more than the starting
  2294.    line, except that trailing blank and comment lines are excluded.
  2295.    E.g., if the starting line begins a multi-statement `def'
  2296.    structure, the region will be set to the full function definition,
  2297.    but without any trailing `noise' lines.
  2298.  
  2299.  - Else the region will include all succeeding lines up to (but not
  2300.    including) the next blank line, or code or indenting-comment line
  2301.    indented strictly less than the starting line.  Trailing indenting
  2302.    comment lines are included in this case, but not trailing blank
  2303.    lines.
  2304.  
  2305. A msg identifying the location of the mark is displayed in the echo
  2306. area; or do `\\[exchange-point-and-mark]' to flip down to the end.
  2307.  
  2308. If called from a program, optional argument EXTEND plays the role of
  2309. the prefix arg, and if optional argument JUST-MOVE is not nil, just
  2310. moves to the end of the block (& does not set mark or display a msg)."
  2311.   (interactive "P")            ; raw prefix arg
  2312.   (py-goto-initial-line)
  2313.   ;; skip over blank lines
  2314.   (while (and
  2315.       (looking-at "[ \t]*$")    ; while blank line
  2316.       (not (eobp)))            ; & somewhere to go
  2317.     (forward-line 1))
  2318.   (if (eobp)
  2319.       (error "Hit end of buffer without finding a non-blank stmt"))
  2320.   (let ((initial-pos (point))
  2321.     (initial-indent (current-indentation))
  2322.     last-pos            ; position of last stmt in region
  2323.     (followers
  2324.      '((if elif else) (elif elif else) (else)
  2325.        (try except finally) (except except) (finally)
  2326.        (for else) (while else)
  2327.        (def) (class) ) )
  2328.     first-symbol next-symbol)
  2329.  
  2330.     (cond
  2331.      ;; if comment line, suck up the following comment lines
  2332.      ((looking-at "[ \t]*#")
  2333.       (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
  2334.       (re-search-backward "^[ \t]*#")    ; and back to last comment in block
  2335.       (setq last-pos (point)))
  2336.  
  2337.      ;; else if line is a block line and EXTEND given, suck up
  2338.      ;; the whole structure
  2339.      ((and extend
  2340.        (setq first-symbol (py-suck-up-first-keyword) )
  2341.        (assq first-symbol followers))
  2342.       (while (and
  2343.           (or (py-goto-beyond-block) t) ; side effect
  2344.           (forward-line -1)        ; side effect
  2345.           (setq last-pos (point))    ; side effect
  2346.           (py-goto-statement-below)
  2347.           (= (current-indentation) initial-indent)
  2348.           (setq next-symbol (py-suck-up-first-keyword))
  2349.           (memq next-symbol (cdr (assq first-symbol followers))))
  2350.     (setq first-symbol next-symbol)))
  2351.  
  2352.      ;; else if line *opens* a block, search for next stmt indented <=
  2353.      ((py-statement-opens-block-p)
  2354.       (while (and
  2355.           (setq last-pos (point))    ; always true -- side effect
  2356.           (py-goto-statement-below)
  2357.           (> (current-indentation) initial-indent))
  2358.     nil))
  2359.  
  2360.      ;; else plain code line; stop at next blank line, or stmt or
  2361.      ;; indenting comment line indented <
  2362.      (t
  2363.       (while (and
  2364.           (setq last-pos (point))    ; always true -- side effect
  2365.           (or (py-goto-beyond-final-line) t)
  2366.           (not (looking-at "[ \t]*$")) ; stop at blank line
  2367.           (or
  2368.            (>= (current-indentation) initial-indent)
  2369.            (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
  2370.     nil)))
  2371.  
  2372.     ;; skip to end of last stmt
  2373.     (goto-char last-pos)
  2374.     (py-goto-beyond-final-line)
  2375.  
  2376.     ;; set mark & display
  2377.     (if just-move
  2378.     ()                ; just return
  2379.       (push-mark (point) 'no-msg)
  2380.       (forward-line -1)
  2381.       (message "Mark set after: %s" (py-suck-up-leading-text))
  2382.       (goto-char initial-pos))))
  2383.  
  2384. (defun py-mark-def-or-class (&optional class)
  2385.   "Set region to body of def (or class, with prefix arg) enclosing point.
  2386. Pushes the current mark, then point, on the mark ring (all language
  2387. modes do this, but although it's handy it's never documented ...).
  2388.  
  2389. In most Emacs language modes, this function bears at least a
  2390. hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
  2391. `\\[py-beginning-of-def-or-class]'.
  2392.  
  2393. And in earlier versions of Python mode, all 3 were tightly connected.
  2394. Turned out that was more confusing than useful: the `goto start' and
  2395. `goto end' commands are usually used to search through a file, and
  2396. people expect them to act a lot like `search backward' and `search
  2397. forward' string-search commands.  But because Python `def' and `class'
  2398. can nest to arbitrary levels, finding the smallest def containing
  2399. point cannot be done via a simple backward search: the def containing
  2400. point may not be the closest preceding def, or even the closest
  2401. preceding def that's indented less.  The fancy algorithm required is
  2402. appropriate for the usual uses of this `mark' command, but not for the
  2403. `goto' variations.
  2404.  
  2405. So the def marked by this command may not be the one either of the
  2406. `goto' commands find: If point is on a blank or non-indenting comment
  2407. line, moves back to start of the closest preceding code statement or
  2408. indenting comment line.  If this is a `def' statement, that's the def
  2409. we use.  Else searches for the smallest enclosing `def' block and uses
  2410. that.  Else signals an error.
  2411.  
  2412. When an enclosing def is found: The mark is left immediately beyond
  2413. the last line of the def block.  Point is left at the start of the
  2414. def, except that: if the def is preceded by a number of comment lines
  2415. followed by (at most) one optional blank line, point is left at the
  2416. start of the comments; else if the def is preceded by a blank line,
  2417. point is left at its start.
  2418.  
  2419. The intent is to mark the containing def/class and its associated
  2420. documentation, to make moving and duplicating functions and classes
  2421. pleasant."
  2422.   (interactive "P")            ; raw prefix arg
  2423.   (let ((start (point))
  2424.     (which (cond ((eq class 'either) "\\(class\\|def\\)")
  2425.              (class "class")
  2426.              (t "def"))))
  2427.     (push-mark start)
  2428.     (if (not (py-go-up-tree-to-keyword which))
  2429.     (progn (goto-char start)
  2430.            (error "Enclosing %s not found"
  2431.               (if (eq class 'either)
  2432.               "def or class"
  2433.             which)))
  2434.       ;; else enclosing def/class found
  2435.       (setq start (point))
  2436.       (py-goto-beyond-block)
  2437.       (push-mark (point))
  2438.       (goto-char start)
  2439.       (if (zerop (forward-line -1))    ; if there is a preceding line
  2440.       (progn
  2441.         (if (looking-at "[ \t]*$")    ; it's blank
  2442.         (setq start (point))    ; so reset start point
  2443.           (goto-char start))    ; else try again
  2444.         (if (zerop (forward-line -1))
  2445.         (if (looking-at "[ \t]*#") ; a comment
  2446.             ;; look back for non-comment line
  2447.             ;; tricky: note that the regexp matches a blank
  2448.             ;; line, cuz \n is in the 2nd character class
  2449.             (and
  2450.              (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
  2451.              (forward-line 1))
  2452.           ;; no comment, so go back
  2453.           (goto-char start)))))))
  2454.   (exchange-point-and-mark)
  2455.   (py-keep-region-active))
  2456.  
  2457. ;; ripped from cc-mode
  2458. (defun py-forward-into-nomenclature (&optional arg)
  2459.   "Move forward to end of a nomenclature section or word.
  2460. With \\[universal-argument] (programmatically, optional argument ARG), 
  2461. do it that many times.
  2462.  
  2463. A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
  2464.   (interactive "p")
  2465.   (let ((case-fold-search nil))
  2466.     (if (> arg 0)
  2467.     (re-search-forward
  2468.      "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
  2469.      (point-max) t arg)
  2470.       (while (and (< arg 0)
  2471.           (re-search-backward
  2472.            "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
  2473.            (point-min) 0))
  2474.     (forward-char 1)
  2475.     (setq arg (1+ arg)))))
  2476.   (py-keep-region-active))
  2477.  
  2478. (defun py-backward-into-nomenclature (&optional arg)
  2479.   "Move backward to beginning of a nomenclature section or word.
  2480. With optional ARG, move that many times.  If ARG is negative, move
  2481. forward.
  2482.  
  2483. A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
  2484.   (interactive "p")
  2485.   (py-forward-into-nomenclature (- arg))
  2486.   (py-keep-region-active))
  2487.  
  2488.  
  2489.  
  2490. ;; Documentation functions
  2491.  
  2492. ;; dump the long form of the mode blurb; does the usual doc escapes,
  2493. ;; plus lines of the form ^[vc]:name$ to suck variable & command docs
  2494. ;; out of the right places, along with the keys they're on & current
  2495. ;; values
  2496. (defun py-dump-help-string (str)
  2497.   (with-output-to-temp-buffer "*Help*"
  2498.     (let ((locals (buffer-local-variables))
  2499.       funckind funcname func funcdoc
  2500.       (start 0) mstart end
  2501.       keys )
  2502.       (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
  2503.     (setq mstart (match-beginning 0)  end (match-end 0)
  2504.           funckind (substring str (match-beginning 1) (match-end 1))
  2505.           funcname (substring str (match-beginning 2) (match-end 2))
  2506.           func (intern funcname))
  2507.     (princ (substitute-command-keys (substring str start mstart)))
  2508.     (cond
  2509.      ((equal funckind "c")        ; command
  2510.       (setq funcdoc (documentation func)
  2511.         keys (concat
  2512.               "Key(s): "
  2513.               (mapconcat 'key-description
  2514.                  (where-is-internal func py-mode-map)
  2515.                  ", "))))
  2516.      ((equal funckind "v")        ; variable
  2517.       (setq funcdoc (documentation-property func 'variable-documentation)
  2518.         keys (if (assq func locals)
  2519.              (concat
  2520.               "Local/Global values: "
  2521.               (prin1-to-string (symbol-value func))
  2522.               " / "
  2523.               (prin1-to-string (default-value func)))
  2524.                (concat
  2525.             "Value: "
  2526.             (prin1-to-string (symbol-value func))))))
  2527.      (t                ; unexpected
  2528.       (error "Error in py-dump-help-string, tag `%s'" funckind)))
  2529.     (princ (format "\n-> %s:\t%s\t%s\n\n"
  2530.                (if (equal funckind "c") "Command" "Variable")
  2531.                funcname keys))
  2532.     (princ funcdoc)
  2533.     (terpri)
  2534.     (setq start end))
  2535.       (princ (substitute-command-keys (substring str start))))
  2536.     (print-help-return-message)))
  2537.  
  2538. (defun py-describe-mode ()
  2539.   "Dump long form of Python-mode docs."
  2540.   (interactive)
  2541.   (py-dump-help-string "Major mode for editing Python files.
  2542. Knows about Python indentation, tokens, comments and continuation lines.
  2543. Paragraphs are separated by blank lines only.
  2544.  
  2545. Major sections below begin with the string `@'; specific function and
  2546. variable docs begin with `->'.
  2547.  
  2548. @EXECUTING PYTHON CODE
  2549.  
  2550. \\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
  2551. \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
  2552. \\[py-execute-region]\tsends the current region
  2553. \\[py-execute-def-or-class]\tsends the current function or class definition
  2554. \\[py-execute-string]\tsends an arbitrary string
  2555. \\[py-shell]\tstarts a Python interpreter window; this will be used by
  2556. \tsubsequent Python execution commands
  2557. %c:py-execute-import-or-reload
  2558. %c:py-execute-buffer
  2559. %c:py-execute-region
  2560. %c:py-execute-def-or-class
  2561. %c:py-execute-string
  2562. %c:py-shell
  2563.  
  2564. @VARIABLES
  2565.  
  2566. py-indent-offset\tindentation increment
  2567. py-block-comment-prefix\tcomment string used by comment-region
  2568.  
  2569. py-python-command\tshell command to invoke Python interpreter
  2570. py-temp-directory\tdirectory used for temp files (if needed)
  2571.  
  2572. py-beep-if-tab-change\tring the bell if tab-width is changed
  2573. %v:py-indent-offset
  2574. %v:py-block-comment-prefix
  2575. %v:py-python-command
  2576. %v:py-temp-directory
  2577. %v:py-beep-if-tab-change
  2578.  
  2579. @KINDS OF LINES
  2580.  
  2581. Each physical line in the file is either a `continuation line' (the
  2582. preceding line ends with a backslash that's not part of a comment, or
  2583. the paren/bracket/brace nesting level at the start of the line is
  2584. non-zero, or both) or an `initial line' (everything else).
  2585.  
  2586. An initial line is in turn a `blank line' (contains nothing except
  2587. possibly blanks or tabs), a `comment line' (leftmost non-blank
  2588. character is `#'), or a `code line' (everything else).
  2589.  
  2590. Comment Lines
  2591.  
  2592. Although all comment lines are treated alike by Python, Python mode
  2593. recognizes two kinds that act differently with respect to indentation.
  2594.  
  2595. An `indenting comment line' is a comment line with a blank, tab or
  2596. nothing after the initial `#'.  The indentation commands (see below)
  2597. treat these exactly as if they were code lines: a line following an
  2598. indenting comment line will be indented like the comment line.  All
  2599. other comment lines (those with a non-whitespace character immediately
  2600. following the initial `#') are `non-indenting comment lines', and
  2601. their indentation is ignored by the indentation commands.
  2602.  
  2603. Indenting comment lines are by far the usual case, and should be used
  2604. whenever possible.  Non-indenting comment lines are useful in cases
  2605. like these:
  2606.  
  2607. \ta = b   # a very wordy single-line comment that ends up being
  2608. \t        #... continued onto another line
  2609.  
  2610. \tif a == b:
  2611. ##\t\tprint 'panic!' # old code we've `commented out'
  2612. \t\treturn a
  2613.  
  2614. Since the `#...' and `##' comment lines have a non-whitespace
  2615. character following the initial `#', Python mode ignores them when
  2616. computing the proper indentation for the next line.
  2617.  
  2618. Continuation Lines and Statements
  2619.  
  2620. The Python-mode commands generally work on statements instead of on
  2621. individual lines, where a `statement' is a comment or blank line, or a
  2622. code line and all of its following continuation lines (if any)
  2623. considered as a single logical unit.  The commands in this mode
  2624. generally (when it makes sense) automatically move to the start of the
  2625. statement containing point, even if point happens to be in the middle
  2626. of some continuation line.
  2627.  
  2628.  
  2629. @INDENTATION
  2630.  
  2631. Primarily for entering new code:
  2632. \t\\[indent-for-tab-command]\t indent line appropriately
  2633. \t\\[py-newline-and-indent]\t insert newline, then indent
  2634. \t\\[py-electric-backspace]\t reduce indentation, or delete single character
  2635.  
  2636. Primarily for reindenting existing code:
  2637. \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
  2638. \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
  2639.  
  2640. \t\\[py-indent-region]\t reindent region to match its context
  2641. \t\\[py-shift-region-left]\t shift region left by py-indent-offset
  2642. \t\\[py-shift-region-right]\t shift region right by py-indent-offset
  2643.  
  2644. Unlike most programming languages, Python uses indentation, and only
  2645. indentation, to specify block structure.  Hence the indentation supplied
  2646. automatically by Python-mode is just an educated guess:  only you know
  2647. the block structure you intend, so only you can supply correct
  2648. indentation.
  2649.  
  2650. The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
  2651. the indentation of preceding statements.  E.g., assuming
  2652. py-indent-offset is 4, after you enter
  2653. \tif a > 0: \\[py-newline-and-indent]
  2654. the cursor will be moved to the position of the `_' (_ is not a
  2655. character in the file, it's just used here to indicate the location of
  2656. the cursor):
  2657. \tif a > 0:
  2658. \t    _
  2659. If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
  2660. to
  2661. \tif a > 0:
  2662. \t    c = d
  2663. \t    _
  2664. Python-mode cannot know whether that's what you intended, or whether
  2665. \tif a > 0:
  2666. \t    c = d
  2667. \t_
  2668. was your intent.  In general, Python-mode either reproduces the
  2669. indentation of the (closest code or indenting-comment) preceding
  2670. statement, or adds an extra py-indent-offset blanks if the preceding
  2671. statement has `:' as its last significant (non-whitespace and non-
  2672. comment) character.  If the suggested indentation is too much, use
  2673. \\[py-electric-backspace] to reduce it.
  2674.  
  2675. Continuation lines are given extra indentation.  If you don't like the
  2676. suggested indentation, change it to something you do like, and Python-
  2677. mode will strive to indent later lines of the statement in the same way.
  2678.  
  2679. If a line is a continuation line by virtue of being in an unclosed
  2680. paren/bracket/brace structure (`list', for short), the suggested
  2681. indentation depends on whether the current line contains the first item
  2682. in the list.  If it does, it's indented py-indent-offset columns beyond
  2683. the indentation of the line containing the open bracket.  If you don't
  2684. like that, change it by hand.  The remaining items in the list will mimic
  2685. whatever indentation you give to the first item.
  2686.  
  2687. If a line is a continuation line because the line preceding it ends with
  2688. a backslash, the third and following lines of the statement inherit their
  2689. indentation from the line preceding them.  The indentation of the second
  2690. line in the statement depends on the form of the first (base) line:  if
  2691. the base line is an assignment statement with anything more interesting
  2692. than the backslash following the leftmost assigning `=', the second line
  2693. is indented two columns beyond that `='.  Else it's indented to two
  2694. columns beyond the leftmost solid chunk of non-whitespace characters on
  2695. the base line.
  2696.  
  2697. Warning:  indent-region should not normally be used!  It calls \\[indent-for-tab-command]
  2698. repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
  2699. structure you intend.
  2700. %c:indent-for-tab-command
  2701. %c:py-newline-and-indent
  2702. %c:py-electric-backspace
  2703.  
  2704.  
  2705. The next function may be handy when editing code you didn't write:
  2706. %c:py-guess-indent-offset
  2707.  
  2708.  
  2709. The remaining `indent' functions apply to a region of Python code.  They
  2710. assume the block structure (equals indentation, in Python) of the region
  2711. is correct, and alter the indentation in various ways while preserving
  2712. the block structure:
  2713. %c:py-indent-region
  2714. %c:py-shift-region-left
  2715. %c:py-shift-region-right
  2716.  
  2717. @MARKING & MANIPULATING REGIONS OF CODE
  2718.  
  2719. \\[py-mark-block]\t mark block of lines
  2720. \\[py-mark-def-or-class]\t mark smallest enclosing def
  2721. \\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
  2722. \\[comment-region]\t comment out region of code
  2723. \\[universal-argument] \\[comment-region]\t uncomment region of code
  2724. %c:py-mark-block
  2725. %c:py-mark-def-or-class
  2726. %c:comment-region
  2727.  
  2728. @MOVING POINT
  2729.  
  2730. \\[py-previous-statement]\t move to statement preceding point
  2731. \\[py-next-statement]\t move to statement following point
  2732. \\[py-goto-block-up]\t move up to start of current block
  2733. \\[py-beginning-of-def-or-class]\t move to start of def
  2734. \\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
  2735. \\[py-end-of-def-or-class]\t move to end of def
  2736. \\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
  2737.  
  2738. The first two move to one statement beyond the statement that contains
  2739. point.  A numeric prefix argument tells them to move that many
  2740. statements instead.  Blank lines, comment lines, and continuation lines
  2741. do not count as `statements' for these commands.  So, e.g., you can go
  2742. to the first code statement in a file by entering
  2743. \t\\[beginning-of-buffer]\t to move to the top of the file
  2744. \t\\[py-next-statement]\t to skip over initial comments and blank lines
  2745. Or do `\\[py-previous-statement]' with a huge prefix argument.
  2746. %c:py-previous-statement
  2747. %c:py-next-statement
  2748. %c:py-goto-block-up
  2749. %c:py-beginning-of-def-or-class
  2750. %c:py-end-of-def-or-class
  2751.  
  2752. @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
  2753.  
  2754. `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
  2755.  
  2756. `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
  2757. overall class and def structure of a module.
  2758.  
  2759. `\\[back-to-indentation]' moves point to a line's first non-blank character.
  2760.  
  2761. `\\[indent-relative]' is handy for creating odd indentation.
  2762.  
  2763. @OTHER EMACS HINTS
  2764.  
  2765. If you don't like the default value of a variable, change its value to
  2766. whatever you do like by putting a `setq' line in your .emacs file.
  2767. E.g., to set the indentation increment to 4, put this line in your
  2768. .emacs:
  2769. \t(setq  py-indent-offset  4)
  2770. To see the value of a variable, do `\\[describe-variable]' and enter the variable
  2771. name at the prompt.
  2772.  
  2773. When entering a key sequence like `C-c C-n', it is not necessary to
  2774. release the CONTROL key after doing the `C-c' part -- it suffices to
  2775. press the CONTROL key, press and release `c' (while still holding down
  2776. CONTROL), press and release `n' (while still holding down CONTROL), &
  2777. then release CONTROL.
  2778.  
  2779. Entering Python mode calls with no arguments the value of the variable
  2780. `python-mode-hook', if that value exists and is not nil; for backward
  2781. compatibility it also tries `py-mode-hook'; see the `Hooks' section of
  2782. the Elisp manual for details.
  2783.  
  2784. Obscure:  When python-mode is first loaded, it looks for all bindings
  2785. to newline-and-indent in the global keymap, and shadows them with
  2786. local bindings to py-newline-and-indent."))
  2787.  
  2788.  
  2789. ;; Helper functions
  2790. (defvar py-parse-state-re
  2791.   (concat
  2792.    "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
  2793.    "\\|"
  2794.    "^[^ #\t\n]"))
  2795.  
  2796. (defun py-parse-state ()
  2797.   "Return the parse state at point (see `parse-partial-sexp' docs)."
  2798.   (save-excursion
  2799.     (let ((here (point))
  2800.       pps done)
  2801.       (while (not done)
  2802.     ;; back up to the first preceding line (if any; else start of
  2803.     ;; buffer) that begins with a popular Python keyword, or a
  2804.     ;; non- whitespace and non-comment character.  These are good
  2805.     ;; places to start parsing to see whether where we started is
  2806.     ;; at a non-zero nesting level.  It may be slow for people who
  2807.     ;; write huge code blocks or huge lists ... tough beans.
  2808.     (re-search-backward py-parse-state-re nil 'move)
  2809.     (beginning-of-line)
  2810.     ;; In XEmacs, we have a much better way to test for whether
  2811.     ;; we're in a triple-quoted string or not.  Emacs does not
  2812.     ;; have this built-in function, which is its loss because
  2813.     ;; without scanning from the beginning of the buffer, there's
  2814.     ;; no accurate way to determine this otherwise.
  2815.     (if (not (fboundp 'buffer-syntactic-context))
  2816.         ;; Emacs
  2817.         (progn
  2818.           (save-excursion (setq pps (parse-partial-sexp (point) here)))
  2819.           ;; make sure we don't land inside a triple-quoted string
  2820.           (setq done (or (not (nth 3 pps))
  2821.                  (bobp)))
  2822.           ;; Just go ahead and short circuit the test back to the
  2823.           ;; beginning of the buffer.  This will be slow, but not
  2824.           ;; nearly as slow as looping through many
  2825.           ;; re-search-backwards.
  2826.           (if (not done)
  2827.           (goto-char (point-min))))
  2828.       ;; XEmacs
  2829.       (setq done (or (not (buffer-syntactic-context))
  2830.              (bobp)))
  2831.       (when done
  2832.         (setq pps (parse-partial-sexp (point) here)))
  2833.       ))
  2834.       pps)))
  2835.  
  2836. (defun py-nesting-level ()
  2837.   "Return the buffer position of the last unclosed enclosing list.
  2838. If nesting level is zero, return nil."
  2839.   (let ((status (py-parse-state)))
  2840.     (if (zerop (car status))
  2841.     nil                ; not in a nest
  2842.       (car (cdr status)))))        ; char# of open bracket
  2843.  
  2844. (defun py-backslash-continuation-line-p ()
  2845.   "Return t iff preceding line ends with backslash that is not in a comment."
  2846.   (save-excursion
  2847.     (beginning-of-line)
  2848.     (and
  2849.      ;; use a cheap test first to avoid the regexp if possible
  2850.      ;; use 'eq' because char-after may return nil
  2851.      (eq (char-after (- (point) 2)) ?\\ )
  2852.      ;; make sure; since eq test passed, there is a preceding line
  2853.      (forward-line -1)            ; always true -- side effect
  2854.      (looking-at py-continued-re))))
  2855.  
  2856. (defun py-continuation-line-p ()
  2857.   "Return t iff current line is a continuation line."
  2858.   (save-excursion
  2859.     (beginning-of-line)
  2860.     (or (py-backslash-continuation-line-p)
  2861.     (py-nesting-level))))
  2862.  
  2863. (defun py-goto-beginning-of-tqs (delim)
  2864.   "Go to the beginning of the triple quoted string we find ourselves in.
  2865. DELIM is the TQS string delimiter character we're searching backwards
  2866. for."
  2867.   (let ((skip (and delim (make-string 1 delim))))
  2868.     (when skip
  2869.       (save-excursion
  2870.     (py-safe (search-backward skip))
  2871.     (if (and (eq (char-before) delim)
  2872.          (eq (char-before (1- (point))) delim))
  2873.         (setq skip (make-string 3 delim))))
  2874.       ;; we're looking at a triple-quoted string
  2875.       (py-safe (search-backward skip)))))
  2876.  
  2877. (defun py-goto-initial-line ()
  2878.   "Go to the initial line of the current statement.
  2879. Usually this is the line we're on, but if we're on the 2nd or
  2880. following lines of a continuation block, we need to go up to the first
  2881. line of the block."
  2882.   ;; Tricky: We want to avoid quadratic-time behavior for long
  2883.   ;; continued blocks, whether of the backslash or open-bracket
  2884.   ;; varieties, or a mix of the two.  The following manages to do that
  2885.   ;; in the usual cases.
  2886.   ;;
  2887.   ;; Also, if we're sitting inside a triple quoted string, this will
  2888.   ;; drop us at the line that begins the string.
  2889.   (let (open-bracket-pos)
  2890.     (while (py-continuation-line-p)
  2891.       (beginning-of-line)
  2892.       (if (py-backslash-continuation-line-p)
  2893.       (while (py-backslash-continuation-line-p)
  2894.         (forward-line -1))
  2895.     ;; else zip out of nested brackets/braces/parens
  2896.     (while (setq open-bracket-pos (py-nesting-level))
  2897.       (goto-char open-bracket-pos)))))
  2898.   (beginning-of-line))
  2899.  
  2900. (defun py-goto-beyond-final-line ()
  2901.   "Go to the point just beyond the fine line of the current statement.
  2902. Usually this is the start of the next line, but if this is a
  2903. multi-line statement we need to skip over the continuation lines."
  2904.   ;; Tricky: Again we need to be clever to avoid quadratic time
  2905.   ;; behavior.
  2906.   ;;
  2907.   ;; XXX: Not quite the right solution, but deals with multi-line doc
  2908.   ;; strings
  2909.   (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
  2910.       (goto-char (match-end 0)))
  2911.   ;;
  2912.   (forward-line 1)
  2913.   (let (state)
  2914.     (while (and (py-continuation-line-p)
  2915.         (not (eobp)))
  2916.       ;; skip over the backslash flavor
  2917.       (while (and (py-backslash-continuation-line-p)
  2918.           (not (eobp)))
  2919.     (forward-line 1))
  2920.       ;; if in nest, zip to the end of the nest
  2921.       (setq state (py-parse-state))
  2922.       (if (and (not (zerop (car state)))
  2923.            (not (eobp)))
  2924.       (progn
  2925.         (parse-partial-sexp (point) (point-max) 0 nil state)
  2926.         (forward-line 1))))))
  2927.  
  2928. (defun py-statement-opens-block-p ()
  2929.   "Return t iff the current statement opens a block.
  2930. I.e., iff it ends with a colon that is not in a comment.  Point should 
  2931. be at the start of a statement."
  2932.   (save-excursion
  2933.     (let ((start (point))
  2934.       (finish (progn (py-goto-beyond-final-line) (1- (point))))
  2935.       (searching t)
  2936.       (answer nil)
  2937.       state)
  2938.       (goto-char start)
  2939.       (while searching
  2940.     ;; look for a colon with nothing after it except whitespace, and
  2941.     ;; maybe a comment
  2942.     (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
  2943.                    finish t)
  2944.         (if (eq (point) finish)    ; note: no `else' clause; just
  2945.                     ; keep searching if we're not at
  2946.                     ; the end yet
  2947.         ;; sure looks like it opens a block -- but it might
  2948.         ;; be in a comment
  2949.         (progn
  2950.           (setq searching nil)    ; search is done either way
  2951.           (setq state (parse-partial-sexp start
  2952.                           (match-beginning 0)))
  2953.           (setq answer (not (nth 4 state)))))
  2954.       ;; search failed: couldn't find another interesting colon
  2955.       (setq searching nil)))
  2956.       answer)))
  2957.  
  2958. (defun py-statement-closes-block-p ()
  2959.   "Return t iff the current statement closes a block.
  2960. I.e., if the line starts with `return', `raise', `break', `continue',
  2961. and `pass'.  This doesn't catch embedded statements."
  2962.   (let ((here (point)))
  2963.     (py-goto-initial-line)
  2964.     (back-to-indentation)
  2965.     (prog1
  2966.     (looking-at (concat py-block-closing-keywords-re "\\>"))
  2967.       (goto-char here))))
  2968.  
  2969. (defun py-goto-beyond-block ()
  2970.   "Go to point just beyond the final line of block begun by the current line.
  2971. This is the same as where `py-goto-beyond-final-line' goes unless
  2972. we're on colon line, in which case we go to the end of the block.
  2973. Assumes point is at the beginning of the line."
  2974.   (if (py-statement-opens-block-p)
  2975.       (py-mark-block nil 'just-move)
  2976.     (py-goto-beyond-final-line)))
  2977.  
  2978. (defun py-goto-statement-at-or-above ()
  2979.   "Go to the start of the first statement at or preceding point.
  2980. Return t if there is such a statement, otherwise nil.  `Statement'
  2981. does not include blank lines, comments, or continuation lines."
  2982.   (py-goto-initial-line)
  2983.   (if (looking-at py-blank-or-comment-re)
  2984.       ;; skip back over blank & comment lines
  2985.       ;; note:  will skip a blank or comment line that happens to be
  2986.       ;; a continuation line too
  2987.       (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
  2988.       (progn (py-goto-initial-line) t)
  2989.     nil)
  2990.     t))
  2991.  
  2992. (defun py-goto-statement-below ()
  2993.   "Go to start of the first statement following the statement containing point.
  2994. Return t if there is such a statement, otherwise nil.  `Statement'
  2995. does not include blank lines, comments, or continuation lines."
  2996.   (beginning-of-line)
  2997.   (let ((start (point)))
  2998.     (py-goto-beyond-final-line)
  2999.     (while (and
  3000.         (looking-at py-blank-or-comment-re)
  3001.         (not (eobp)))
  3002.       (forward-line 1))
  3003.     (if (eobp)
  3004.     (progn (goto-char start) nil)
  3005.       t)))
  3006.  
  3007. (defun py-go-up-tree-to-keyword (key)
  3008.   "Go to begining of statement starting with KEY, at or preceding point.
  3009.  
  3010. KEY is a regular expression describing a Python keyword.  Skip blank
  3011. lines and non-indenting comments.  If the statement found starts with
  3012. KEY, then stop, otherwise go back to first enclosing block starting
  3013. with KEY.  If successful, leave point at the start of the KEY line and 
  3014. return t.  Otherwise, leav point at an undefined place and return nil."
  3015.   ;; skip blanks and non-indenting #
  3016.   (py-goto-initial-line)
  3017.   (while (and
  3018.       (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  3019.       (zerop (forward-line -1)))    ; go back
  3020.     nil)
  3021.   (py-goto-initial-line)
  3022.   (let* ((re (concat "[ \t]*" key "\\b"))
  3023.      (case-fold-search nil)        ; let* so looking-at sees this
  3024.      (found (looking-at re))
  3025.      (dead nil))
  3026.     (while (not (or found dead))
  3027.       (condition-case nil        ; in case no enclosing block
  3028.       (py-goto-block-up 'no-mark)
  3029.     (error (setq dead t)))
  3030.       (or dead (setq found (looking-at re))))
  3031.     (beginning-of-line)
  3032.     found))
  3033.  
  3034. (defun py-suck-up-leading-text ()
  3035.   "Return string in buffer from start of indentation to end of line.
  3036. Prefix with \"...\" if leading whitespace was skipped."
  3037.   (save-excursion
  3038.     (back-to-indentation)
  3039.     (concat
  3040.      (if (bolp) "" "...")
  3041.      (buffer-substring (point) (progn (end-of-line) (point))))))
  3042.  
  3043. (defun py-suck-up-first-keyword ()
  3044.   "Return first keyword on the line as a Lisp symbol.
  3045. `Keyword' is defined (essentially) as the regular expression
  3046. ([a-z]+).  Returns nil if none was found."
  3047.   (let ((case-fold-search nil))
  3048.     (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
  3049.     (intern (buffer-substring (match-beginning 1) (match-end 1)))
  3050.       nil)))
  3051.  
  3052. (defun py-current-defun ()
  3053.   "Python value for `add-log-current-defun-function'.
  3054. This tells add-log.el how to find the current function/method/variable."
  3055.   (save-excursion
  3056.     (if (re-search-backward py-defun-start-re nil t)
  3057.     (or (match-string 3)
  3058.         (let ((method (match-string 2)))
  3059.           (if (and (not (zerop (length (match-string 1))))
  3060.                (re-search-backward py-class-start-re nil t))
  3061.           (concat (match-string 1) "." method)
  3062.         method)))
  3063.       nil)))
  3064.  
  3065.  
  3066. (defconst py-help-address "python-mode@python.org"
  3067.   "Address accepting submission of bug reports.")
  3068.  
  3069. (defun py-version ()
  3070.   "Echo the current version of `python-mode' in the minibuffer."
  3071.   (interactive)
  3072.   (message "Using `python-mode' version %s" py-version)
  3073.   (py-keep-region-active))
  3074.  
  3075. ;; only works under Emacs 19
  3076. ;(eval-when-compile
  3077. ;  (require 'reporter))
  3078.  
  3079. (defun py-submit-bug-report (enhancement-p)
  3080.   "Submit via mail a bug report on `python-mode'.
  3081. With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
  3082. non-nil) just submit an enhancement request."
  3083.   (interactive
  3084.    (list (not (y-or-n-p
  3085.            "Is this a bug report (hit `n' to send other comments)? "))))
  3086.   (let ((reporter-prompt-for-summary-p (if enhancement-p
  3087.                        "(Very) brief summary: "
  3088.                      t)))
  3089.     (require 'reporter)
  3090.     (reporter-submit-bug-report
  3091.      py-help-address            ;address
  3092.      (concat "python-mode " py-version)    ;pkgname
  3093.      ;; varlist
  3094.      (if enhancement-p nil
  3095.        '(py-python-command
  3096.      py-indent-offset
  3097.      py-block-comment-prefix
  3098.      py-temp-directory
  3099.      py-beep-if-tab-change))
  3100.      nil                ;pre-hooks
  3101.      nil                ;post-hooks
  3102.      "Dear Barry,")            ;salutation
  3103.     (if enhancement-p nil
  3104.       (set-mark (point))
  3105.       (insert 
  3106. "Please replace this text with a sufficiently large code sample\n\
  3107. and an exact recipe so that I can reproduce your problem.  Failure\n\
  3108. to do so may mean a greater delay in fixing your bug.\n\n")
  3109.       (exchange-point-and-mark)
  3110.       (py-keep-region-active))))
  3111.  
  3112.  
  3113. (defun py-kill-emacs-hook ()
  3114.   "Delete files in `py-file-queue'.
  3115. These are Python temporary files awaiting execution."
  3116.   (mapcar #'(lambda (filename)
  3117.           (py-safe (delete-file filename)))
  3118.       py-file-queue))
  3119.  
  3120. ;; arrange to kill temp files when Emacs exists
  3121. (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
  3122.  
  3123.  
  3124.  
  3125. (provide 'python-mode)
  3126. ;;; python-mode.el ends here
  3127.