home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / modes / python-mode.el.z / python-mode.el
Encoding:
Text File  |  1998-05-21  |  101.2 KB  |  2,731 lines

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