home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Misc / python-mode.el < prev    next >
Lisp/Scheme  |  1994-04-28  |  65KB  |  1,662 lines

  1. ;;; Major mode for editing Python programs, version 1.09
  2. ;; by: Tim Peters <tim@ksr.com>
  3. ;; after an original idea by: Michael A. Guravage
  4. ;;
  5. ;; Copyright (c) 1992,1993,1994  Tim Peters
  6. ;;
  7. ;; This software is provided as-is, without express or implied warranty.
  8. ;; Permission to use, copy, modify, distribute or sell this software,
  9. ;; without fee, for any purpose and by any individual or organization, is
  10. ;; hereby granted, provided that the above copyright notice and this
  11. ;; paragraph appear in all copies.
  12. ;;
  13. ;;
  14. ;; The following statements, placed in your .emacs file or site-init.el,
  15. ;; will cause this file to be autoloaded, and python-mode invoked, when
  16. ;; visiting .py files (assuming the file is in your load-path):
  17. ;;
  18. ;;    (autoload 'python-mode "python-mode" "" t)
  19. ;;    (setq auto-mode-alist
  20. ;;          (cons '("\\.py$" . python-mode) auto-mode-alist))
  21.  
  22. (provide 'python-mode)
  23.  
  24. ;;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19.
  25. ;;; This seems to be the standard way of checking this.
  26.  
  27. (setq py-this-is-lucid-emacs-p (string-match "Lucid" emacs-version))
  28. (setq py-this-is-emacs-19-p
  29.       (and
  30.        (not py-this-is-lucid-emacs-p)
  31.        (string-match "^19\\." emacs-version)))
  32.  
  33. ;;; Constants and variables
  34.  
  35. (defvar py-python-command "python"
  36.   "*Shell command used to start Python interpreter.")
  37.  
  38. (defvar py-indent-offset 8        ; argue with Guido <grin>
  39.   "*Indentation increment.
  40. Note that `\\[py-guess-indent-offset]' can usually guess a good value when you're
  41. editing someone else's Python code.")
  42.  
  43. (defvar py-block-comment-prefix "##"
  44.   "*String used by py-comment-region to comment out a block of code.
  45. This should follow the convention for non-indenting comment lines so
  46. that the indentation commands won't get confused (i.e., the string
  47. should be of the form `#x...' where `x' is not a blank or a tab, and
  48. `...' is arbitrary).")
  49.  
  50. (defvar py-scroll-process-buffer t
  51.   "*Scroll Python process buffer as output arrives.
  52. If nil, the Python process buffer acts, with respect to scrolling, like
  53. Shell-mode buffers normally act.  This is surprisingly complicated and
  54. so won't be explained here; in fact, you can't get the whole story
  55. without studying the Emacs C code.
  56.  
  57. If non-nil, the behavior is different in two respects (which are
  58. slightly inaccurate in the interest of brevity):
  59.  
  60.   - If the buffer is in a window, and you left point at its end, the
  61.     window will scroll as new output arrives, and point will move to the
  62.     buffer's end, even if the window is not the selected window (that
  63.     being the one the cursor is in).  The usual behavior for shell-mode
  64.     windows is not to scroll, and to leave point where it was, if the
  65.     buffer is in a window other than the selected window.
  66.  
  67.   - If the buffer is not visible in any window, and you left point at
  68.     its end, the buffer will be popped into a window as soon as more
  69.     output arrives.  This is handy if you have a long-running
  70.     computation and don't want to tie up screen area waiting for the
  71.     output.  The usual behavior for a shell-mode buffer is to stay
  72.     invisible until you explicitly visit it.
  73.  
  74. Note the `and if you left point at its end' clauses in both of the
  75. above:  you can `turn off' the special behaviors while output is in
  76. progress, by visiting the Python buffer and moving point to anywhere
  77. besides the end.  Then the buffer won't scroll, point will remain where
  78. you leave it, and if you hide the buffer it will stay hidden until you
  79. visit it again.  You can enable and disable the special behaviors as
  80. often as you like, while output is in progress, by (respectively) moving
  81. point to, or away from, the end of the buffer.
  82.  
  83. Warning:  If you expect a large amount of output, you'll probably be
  84. happier setting this option to nil.
  85.  
  86. Obscure:  `End of buffer' above should really say `at or beyond the
  87. process mark', but if you know what that means you didn't need to be
  88. told <grin>.")
  89.  
  90. (defvar py-temp-directory
  91.   (let ( (ok '(lambda (x)
  92.         (and x
  93.              (setq x (expand-file-name x)) ; always true
  94.              (file-directory-p x)
  95.              (file-writable-p x)
  96.              x))))
  97.     (or (funcall ok (getenv "TMPDIR"))
  98.     (funcall ok "/usr/tmp")
  99.     (funcall ok "/tmp")
  100.     (funcall ok  ".")
  101.     (error
  102.      "Couldn't find a usable temp directory -- set py-temp-directory")))
  103.   "*Directory used for temp files created by a *Python* process.
  104. By default, the first directory from this list that exists and that you
  105. can write into:  the value (if any) of the environment variable TMPDIR,
  106. /usr/tmp, /tmp, or the current directory.")
  107.  
  108. ;; have to bind py-file-queue before installing the kill-emacs hook
  109. (defvar py-file-queue nil
  110.   "Queue of Python temp files awaiting execution.
  111. Currently-active file is at the head of the list.")
  112.  
  113. ;; define a mode-specific abbrev table for those who use such things
  114. (defvar python-mode-abbrev-table nil
  115.   "Abbrev table in use in python-mode buffers.")
  116. (define-abbrev-table 'python-mode-abbrev-table nil)
  117.  
  118. ;; arrange to kill temp files no matter what
  119. (if (or py-this-is-emacs-19-p py-this-is-lucid-emacs-p)
  120.     (add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
  121.   ;; have to trust that other people are as respectful of our hook
  122.   ;; fiddling as we are of theirs
  123.   (if (boundp 'py-inherited-kill-emacs-hook)
  124.       ;; we were loaded before -- trust others not to have screwed us
  125.       ;; in the meantime (no choice, really)
  126.       nil
  127.     ;; else arrange for our hook to run theirs
  128.     (setq py-inherited-kill-emacs-hook kill-emacs-hook)
  129.     (setq kill-emacs-hook 'py-kill-emacs-hook)))
  130.  
  131. (defvar py-beep-if-tab-change t
  132.   "*Ring the bell if tab-width is changed.
  133. If a comment of the form
  134. \t# vi:set tabsize=<number>:
  135. is found before the first code line when the file is entered, and
  136. the current value of (the general Emacs variable) tab-width does not
  137. equal <number>, tab-width is set to <number>, a message saying so is
  138. displayed in the echo area, and if py-beep-if-tab-change is non-nil the
  139. Emacs bell is also rung as a warning.")
  140.  
  141. (defvar py-mode-map nil "Keymap used in Python mode buffers.")
  142. (if py-mode-map
  143.     ()
  144.   (setq py-mode-map (make-sparse-keymap))
  145.  
  146.   ;; shadow global bindings for newline-and-indent w/ the py- version
  147.   (mapcar (function (lambda (key)
  148.               (define-key
  149.             py-mode-map key 'py-newline-and-indent)))
  150.    (where-is-internal 'newline-and-indent))
  151.  
  152.   (mapcar (function
  153.        (lambda (x)
  154.          (define-key py-mode-map (car x) (cdr x))))
  155.       '( ("\C-c\C-c" . py-execute-buffer)
  156.          ("\C-c|"     . py-execute-region)
  157.          ("\C-c!"     . py-shell)
  158.          ("\177"     . py-delete-char)
  159.          ("\n"     . py-newline-and-indent)
  160.          ("\C-c:"     . py-guess-indent-offset)
  161.          ("\C-c\t"     . py-indent-region)
  162.          ("\C-c<"     . py-shift-region-left)
  163.          ("\C-c>"     . py-shift-region-right)
  164.          ("\C-c\C-n" . py-next-statement)
  165.          ("\C-c\C-p" . py-previous-statement)
  166.          ("\C-c\C-u" . py-goto-block-up)
  167.          ("\C-c\C-b" . py-mark-block)
  168.          ("\C-c#"     . py-comment-region)
  169.          ("\C-c?"     . py-describe-mode)
  170.          ("\C-c\C-hm" . py-describe-mode)
  171.          ("\e\C-a"     . beginning-of-python-def-or-class)
  172.          ("\e\C-e"     . end-of-python-def-or-class)
  173.          ( "\e\C-h"     . mark-python-def-or-class))))
  174.  
  175. (defvar py-mode-syntax-table nil "Python mode syntax table")
  176. (if py-mode-syntax-table
  177.     ()
  178.   (setq py-mode-syntax-table (make-syntax-table))
  179.   (mapcar (function
  180.        (lambda (x) (modify-syntax-entry
  181.             (car x) (cdr x) py-mode-syntax-table)))
  182.       '(( ?\( . "()" ) ( ?\) . ")(" )
  183.         ( ?\[ . "(]" ) ( ?\] . ")[" )
  184.         ( ?\{ . "(}" ) ( ?\} . "){" )
  185.         ;; fix operator symbols misassigned in the std table
  186.         ( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
  187.         ( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
  188.         ( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
  189.         ( ?\> . "." ) ( ?\| . "." )
  190.         ( ?\_ . "w" )    ; underscore is legit in names
  191.         ( ?\' . "\"")    ; single quote is string quote
  192.         ( ?\" . "\"" )    ; double quote is string quote too
  193.         ( ?\` . "$")    ; backquote is open and close paren
  194.         ( ?\# . "<")    ; hash starts comment
  195.         ( ?\n . ">"))))    ; newline ends comment
  196.  
  197. (defconst py-stringlit-re
  198.   (concat
  199.    "'\\([^'\n\\]\\|\\\\.\\)*'"        ; single-quoted
  200.    "\\|"                ; or
  201.    "\"\\([^\"\n\\]\\|\\\\.\\)*\"")    ; double-quoted
  202.   "regexp matching a Python string literal")
  203.  
  204. ;; this is tricky because a trailing backslash does not mean
  205. ;; continuation if it's in a comment
  206. (defconst py-continued-re
  207.   (concat
  208.    "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
  209.    "\\\\$")
  210.   "regexp matching Python lines that are continued via backslash")
  211.  
  212. (defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
  213.   "regexp matching blank or comment lines")
  214.  
  215. ;;; General Functions
  216.  
  217. (defun python-mode ()
  218.   "Major mode for editing Python files.
  219. Do `\\[py-describe-mode]' for detailed documentation.
  220. Knows about Python indentation, tokens, comments and continuation lines.
  221. Paragraphs are separated by blank lines only.
  222.  
  223. COMMANDS
  224. \\{py-mode-map}
  225. VARIABLES
  226.  
  227. py-indent-offset\tindentation increment
  228. py-block-comment-prefix\tcomment string used by py-comment-region
  229. py-python-command\tshell command to invoke Python interpreter
  230. py-scroll-process-buffer\talways scroll Python process buffer
  231. py-temp-directory\tdirectory used for temp files (if needed)
  232. py-beep-if-tab-change\tring the bell if tab-width is changed"
  233.   (interactive)
  234.   (kill-all-local-variables)
  235.   (setq  major-mode 'python-mode
  236.      mode-name "Python"
  237.      local-abbrev-table python-mode-abbrev-table)
  238.   (use-local-map py-mode-map)
  239.   (set-syntax-table py-mode-syntax-table)
  240.  
  241.   (mapcar (function (lambda (x)
  242.               (make-local-variable (car x))
  243.               (set (car x) (cdr x))))
  244.       '( (paragraph-separate . "^[ \t]*$")
  245.          (paragraph-start     . "^[ \t]*$")
  246.          (require-final-newline . t)
  247.          (comment-start .        "# ")
  248.          (comment-start-skip .    "# *")
  249.          (comment-column . 40)
  250.          (indent-region-function . py-indent-region)
  251.          (indent-line-function . py-indent-line)))
  252.  
  253.   ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
  254.  
  255.   ;; not sure where the magic comment has to be; to save time searching
  256.   ;; for a rarity, we give up if it's not found prior to the first
  257.   ;; executable statement
  258.   (let ( (case-fold-search nil)
  259.      (start (point))
  260.      new-tab-width)
  261.     (if (re-search-forward
  262.      "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
  263.      (prog2 (py-next-statement 1) (point) (goto-char 1))
  264.      t)
  265.     (progn
  266.       (setq new-tab-width
  267.         (string-to-int
  268.          (buffer-substring (match-beginning 1) (match-end 1))))
  269.       (if (= tab-width new-tab-width)
  270.           nil
  271.         (setq tab-width new-tab-width)
  272.         (message "Caution: tab-width changed to %d" new-tab-width)
  273.         (if py-beep-if-tab-change (beep)))))
  274.     (goto-char start))
  275.  
  276.   (run-hooks 'py-mode-hook))
  277.  
  278. ;;; Functions that execute Python commands in a subprocess
  279.  
  280. (defun py-shell ()
  281.   "Start an interactive Python interpreter in another window.
  282. This is like Shell mode, except that Python is running in the window
  283. instead of a shell.  See the `Interactive Shell' and `Shell Mode'
  284. sections of the Emacs manual for details, especially for the key
  285. bindings active in the `*Python*' buffer.
  286.  
  287. See the docs for variable py-scroll-buffer for info on scrolling
  288. behavior in the process window.
  289.  
  290. Warning:  Don't use an interactive Python if you change sys.ps1 or
  291. sys.ps2 from their default values, or if you're running code that prints
  292. `>>> ' or `... ' at the start of a line.  Python mode can't distinguish
  293. your output from Python's output, and assumes that `>>> ' at the start
  294. of a line is a prompt from Python.  Similarly, the Emacs Shell mode code
  295. assumes that both `>>> ' and `... ' at the start of a line are Python
  296. prompts.  Bad things can happen if you fool either mode.
  297.  
  298. Warning:  If you do any editing *in* the process buffer *while* the
  299. buffer is accepting output from Python, do NOT attempt to `undo' the
  300. changes.  Some of the output (nowhere near the parts you changed!) may
  301. be lost if you do.  This appears to be an Emacs bug, an unfortunate
  302. interaction between undo and process filters; the same problem exists in
  303. non-Python process buffers using the default (Emacs-supplied) process
  304. filter."
  305.   (interactive)
  306.   (if py-this-is-emacs-19-p
  307.       (progn
  308.     (require 'comint)
  309.     (switch-to-buffer-other-window
  310.      (make-comint "Python" py-python-command)))
  311.     (progn
  312.       (require 'shell)
  313.       (switch-to-buffer-other-window
  314.        (make-shell "Python" py-python-command))))
  315.   (make-local-variable 'shell-prompt-pattern)
  316.   (setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
  317.   (set-process-filter (get-buffer-process (current-buffer))
  318.               'py-process-filter)
  319.   (set-syntax-table py-mode-syntax-table))
  320.  
  321. (defun py-execute-region (start end)
  322.   "Send the region between START and END to a Python interpreter.
  323. If there is a *Python* process it is used.
  324.  
  325. Hint:  If you want to execute part of a Python file several times (e.g.,
  326. perhaps you're developing a function and want to flesh it out a bit at a
  327. time), use `\\[narrow-to-region]' to restrict the buffer to the region of interest,
  328. and send the code to a *Python* process via `\\[py-execute-buffer]' instead.
  329.  
  330. Following are subtleties to note when using a *Python* process:
  331.  
  332. If a *Python* process is used, the region is copied into a temp file (in
  333. directory py-temp-directory), and an `execfile' command is sent to
  334. Python naming that file.  If you send regions faster than Python can
  335. execute them, Python mode will save them into distinct temp files, and
  336. execute the next one in the queue the next time it sees a `>>> ' prompt
  337. from Python.  Each time this happens, the process buffer is popped into
  338. a window (if it's not already in some window) so you can see it, and a
  339. comment of the form
  340.  
  341. \t## working on region in file <name> ...
  342.  
  343. is inserted at the end.
  344.  
  345. Caution:  No more than 26 regions can be pending at any given time.  This
  346. limit is (indirectly) inherited from libc's mktemp(3).  Python mode does
  347. not try to protect you from exceeding the limit.  It's extremely
  348. unlikely that you'll get anywhere close to the limit in practice, unless
  349. you're trying to be a jerk <grin>.
  350.  
  351. See the `\\[py-shell]' docs for additional warnings."
  352.   (interactive "r")
  353.   (or (< start end) (error "Region is empty"))
  354.   (let ( (pyproc (get-process "Python"))
  355.       fname)
  356.     (if (null pyproc)
  357.     (shell-command-on-region start end py-python-command)
  358.       ;; else feed it thru a temp file
  359.       (setq fname (py-make-temp-name))
  360.       (write-region start end fname nil 'no-msg)
  361.       (setq py-file-queue (append py-file-queue (list fname)))
  362.       (if (cdr py-file-queue)
  363.       (message "File %s queued for execution" fname)
  364.     ;; else
  365.     (py-execute-file pyproc fname)))))
  366.  
  367. (defun py-execute-file (pyproc fname)
  368.   (py-append-to-process-buffer
  369.    pyproc
  370.    (format "## working on region in file %s ...\n" fname))
  371.   (process-send-string pyproc (format "execfile('%s')\n" fname)))
  372.  
  373. (defun py-process-filter (pyproc string)
  374.   (let ( (curbuf (current-buffer))
  375.      (pbuf (process-buffer pyproc))
  376.      (pmark (process-mark pyproc))
  377.      file-finished)
  378.  
  379.     ;; make sure we switch to a different buffer at least once.  if we
  380.     ;; *don't* do this, then if the process buffer is in the selected
  381.     ;; window, and point is before the end, and lots of output is coming
  382.     ;; at a fast pace, then (a) simple cursor-movement commands like
  383.     ;; C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time to have
  384.     ;; a visible effect (the window just doesn't get updated, sometimes
  385.     ;; for minutes(!)), and (b) it takes about 5x longer to get all the
  386.     ;; process output (until the next python prompt).
  387.     ;;
  388.     ;; #b makes no sense to me at all.  #a almost makes sense:  unless we
  389.     ;; actually change buffers, set_buffer_internal in buffer.c doesn't
  390.     ;; set windows_or_buffers_changed to 1, & that in turn seems to make
  391.     ;; the Emacs command loop reluctant to update the display.  Perhaps
  392.     ;; the default process filter in process.c's read_process_output has
  393.     ;; update_mode_lines++ for a similar reason?  beats me ...
  394.     (if (eq curbuf pbuf)        ; mysterious ugly hack
  395.     (set-buffer (get-buffer-create "*scratch*")))
  396.  
  397.     (set-buffer pbuf)
  398.     (let* ( (start (point))
  399.         (goback (< start pmark))
  400.         (buffer-read-only nil))
  401.       (goto-char pmark)
  402.       (insert string)
  403.       (move-marker pmark (point))
  404.       (setq file-finished
  405.         (and py-file-queue
  406.          (equal ">>> "
  407.             (buffer-substring
  408.              (prog2 (beginning-of-line) (point)
  409.                 (goto-char pmark))
  410.              (point)))))
  411.       (if goback (goto-char start)
  412.     ;; else
  413.     (if py-scroll-process-buffer
  414.         (let* ( (pop-up-windows t)
  415.             (pwin (display-buffer pbuf)))
  416.           (set-window-point pwin (point))))))
  417.     (set-buffer curbuf)
  418.     (if file-finished
  419.     (progn
  420.       (py-delete-file-silently (car py-file-queue))
  421.       (setq py-file-queue (cdr py-file-queue))
  422.       (if py-file-queue
  423.         (py-execute-file pyproc (car py-file-queue)))))))
  424.  
  425. (defun py-execute-buffer ()
  426.   "Send the contents of the buffer to a Python interpreter.
  427. If there is a *Python* process buffer it is used.  If a clipping
  428. restriction is in effect, only the accessible portion of the buffer is
  429. sent.  A trailing newline will be supplied if needed.
  430.  
  431. See the `\\[py-execute-region]' docs for an account of some subtleties."
  432.   (interactive)
  433.   (py-execute-region (point-min) (point-max)))
  434.  
  435.  
  436. ;;; Functions for Python style indentation
  437.  
  438. (defun py-delete-char ()
  439.   "Reduce indentation or delete character.
  440. If point is at the leftmost column, deletes the preceding newline.
  441.  
  442. Else if point is at the leftmost non-blank character of a line that is
  443. neither a continuation line nor a non-indenting comment line, or if
  444. point is at the end of a blank line, reduces the indentation to match
  445. that of the line that opened the current block of code.  The line that
  446. opened the block is displayed in the echo area to help you keep track of
  447. where you are.
  448.  
  449. Else the preceding character is deleted, converting a tab to spaces if
  450. needed so that only a single column position is deleted."
  451.   (interactive "*")
  452.   (if (or (/= (current-indentation) (current-column))
  453.       (bolp)
  454.       (py-continuation-line-p)
  455.       (looking-at "#[^ \t\n]"))    ; non-indenting #
  456.       (backward-delete-char-untabify 1)
  457.     ;; else indent the same as the colon line that opened the block
  458.  
  459.     ;; force non-blank so py-goto-block-up doesn't ignore it
  460.     (insert-char ?* 1)
  461.     (backward-char)
  462.     (let ( (base-indent 0)        ; indentation of base line
  463.        (base-text "")        ; and text of base line
  464.        (base-found-p nil))
  465.       (condition-case nil        ; in case no enclosing block
  466.       (save-excursion
  467.         (py-goto-block-up 'no-mark)
  468.         (setq base-indent (current-indentation)
  469.           base-text   (py-suck-up-leading-text)
  470.           base-found-p t))
  471.     (error nil))
  472.       (delete-char 1)            ; toss the dummy character
  473.       (delete-horizontal-space)
  474.       (indent-to base-indent)
  475.       (if base-found-p
  476.       (message "Closes block: %s" base-text)))))
  477.  
  478. (defun py-indent-line ()
  479.   "Fix the indentation of the current line according to Python rules."
  480.   (interactive)
  481.   (let* ( (ci (current-indentation))
  482.       (move-to-indentation-p (<= (current-column) ci))
  483.       (need (py-compute-indentation)) )
  484.     (if (/= ci need)
  485.     (save-excursion
  486.       (beginning-of-line)
  487.       (delete-horizontal-space)
  488.       (indent-to need)))
  489.     (if move-to-indentation-p (back-to-indentation))))
  490.  
  491. (defun py-newline-and-indent ()
  492.   "Strives to act like the Emacs newline-and-indent.
  493. This is just `strives to' because correct indentation can't be computed
  494. from scratch for Python code.  In general, deletes the whitespace before
  495. point, inserts a newline, and takes an educated guess as to how you want
  496. the new line indented."
  497.   (interactive)
  498.   (let ( (ci (current-indentation)) )
  499.     (if (< ci (current-column))        ; if point beyond indentation
  500.     (newline-and-indent)
  501.       ;; else try to act like newline-and-indent "normally" acts
  502.       (beginning-of-line)
  503.       (insert-char ?\n 1)
  504.       (move-to-column ci))))
  505.  
  506. (defun py-compute-indentation ()
  507.   (save-excursion
  508.     (beginning-of-line)
  509.     (cond
  510.      ;; are we on a continuation line?
  511.      ( (py-continuation-line-p)
  512.        (let ( (startpos (point))
  513.           (open-bracket-pos (py-nesting-level))
  514.           endpos searching found)
  515.      (if open-bracket-pos
  516.          (progn
  517.            ;; align with first item in list; else a normal
  518.            ;; indent beyond the line with the open bracket
  519.            (goto-char (1+ open-bracket-pos)) ; just beyond bracket
  520.            ;; is the first list item on the same line?
  521.            (skip-chars-forward " \t")
  522.            (if (null (memq (following-char) '(?\n ?# ?\\)))
  523.            ; yes, so line up with it
  524.            (current-column)
  525.          ;; first list item on another line, or doesn't exist yet
  526.          (forward-line 1)
  527.          (while (and (< (point) startpos)
  528.                  (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
  529.            (forward-line 1))
  530.          (if (< (point) startpos)
  531.              ;; again mimic the first list item
  532.              (current-indentation)
  533.            ;; else they're about to enter the first item
  534.            (goto-char open-bracket-pos)
  535.            (+ (current-indentation) py-indent-offset))))
  536.  
  537.        ;; else on backslash continuation line
  538.        (forward-line -1)
  539.        (if (py-continuation-line-p)    ; on at least 3rd line in block
  540.            (current-indentation)    ; so just continue the pattern
  541.          ;; else started on 2nd line in block, so indent more.
  542.          ;; if base line is an assignment with a start on a RHS,
  543.          ;; indent to 2 beyond the leftmost "="; else skip first
  544.          ;; chunk of non-whitespace characters on base line, + 1 more
  545.          ;; column
  546.          (end-of-line)
  547.          (setq endpos (point)  searching t)
  548.          (back-to-indentation)
  549.          (setq startpos (point))
  550.          ;; look at all "=" from left to right, stopping at first
  551.          ;; one not nested in a list or string
  552.          (while searching
  553.            (skip-chars-forward "^=" endpos)
  554.            (if (= (point) endpos)
  555.            (setq searching nil)
  556.          (forward-char 1)
  557.          (setq state (parse-partial-sexp startpos (point)))
  558.          (if (and (zerop (car state)) ; not in a bracket
  559.               (null (nth 3 state)))    ; & not in a string
  560.              (progn
  561.                (setq searching nil) ; done searching in any case
  562.                (setq found
  563.                  (not (or
  564.                    (eq (following-char) ?=)
  565.                    (memq (char-after (- (point) 2))
  566.                      '(?< ?> ?!)))))))))
  567.          (if (or (not found)    ; not an assignment
  568.              (looking-at "[ \t]*\\\\"))    ; <=><spaces><backslash>
  569.          (progn
  570.            (goto-char startpos)
  571.            (skip-chars-forward "^ \t\n")))
  572.          (1+ (current-column))))))
  573.  
  574.      ;; not on a continuation line
  575.  
  576.      ;; if at start of restriction, or on a non-indenting comment line,
  577.      ;; assume they intended whatever's there
  578.      ( (or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
  579.        (current-indentation) )
  580.  
  581.      ;; else indentation based on that of the statement that precedes
  582.      ;; us; use the first line of that statement to establish the base,
  583.      ;; in case the user forced a non-std indentation for the
  584.      ;; continuation lines (if any)
  585.      ( t
  586.        ;; skip back over blank & non-indenting comment lines
  587.        ;; note:  will skip a blank or non-indenting comment line that
  588.        ;; happens to be a continuation line too
  589.        (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
  590.                nil 'move)
  591.        (py-goto-initial-line)
  592.        (if (py-statement-opens-block-p)
  593.        (+ (current-indentation) py-indent-offset)
  594.      (current-indentation))))))
  595.  
  596. (defun py-guess-indent-offset (&optional global)
  597.   "Guess a good value for, and change, py-indent-offset.
  598. By default (without a prefix arg), makes a buffer-local copy of
  599. py-indent-offset with the new value.  This will not affect any other
  600. Python buffers.  With a prefix arg, changes the global value of
  601. py-indent-offset.  This affects all Python buffers (that don't have
  602. their own buffer-local copy), both those currently existing and those
  603. created later in the Emacs session.
  604.  
  605. Some people use a different value for py-indent-offset than you use.
  606. There's no excuse for such foolishness, but sometimes you have to deal
  607. with their ugly code anyway.  This function examines the file and sets
  608. py-indent-offset to what it thinks it was when they created the mess.
  609.  
  610. Specifically, it searches forward from the statement containing point,
  611. looking for a line that opens a block of code.  py-indent-offset is set
  612. to the difference in indentation between that line and the Python
  613. statement following it.  If the search doesn't succeed going forward,
  614. it's tried again going backward."
  615.   (interactive "P")            ; raw prefix arg
  616.   (let ( new-value
  617.      (start (point))
  618.      restart
  619.      (found nil)
  620.      colon-indent)
  621.     (py-goto-initial-line)
  622.     (while (not (or found (eobp)))
  623.       (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  624.       (progn
  625.         (setq restart (point))
  626.         (py-goto-initial-line)
  627.         (if (py-statement-opens-block-p)
  628.         (setq found t)
  629.           (goto-char restart)))))
  630.     (if found
  631.     ()
  632.       (goto-char start)
  633.       (py-goto-initial-line)
  634.       (while (not (or found (bobp)))
  635.     (setq found
  636.           (and
  637.            (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  638.            (or (py-goto-initial-line) t) ; always true -- side effect
  639.            (py-statement-opens-block-p)))))
  640.     (setq colon-indent (current-indentation)
  641.       found (and found (zerop (py-next-statement 1)))
  642.       new-value (- (current-indentation) colon-indent))
  643.     (goto-char start)
  644.     (if found
  645.     (progn
  646.       (funcall (if global 'kill-local-variable 'make-local-variable)
  647.            'py-indent-offset)
  648.       (setq py-indent-offset new-value)
  649.       (message "%s value of py-indent-offset set to %d"
  650.            (if global "Global" "Local")
  651.            py-indent-offset))
  652.       (error "Sorry, couldn't guess a value for py-indent-offset"))))
  653.  
  654. (defun py-shift-region (start end count)
  655.   (save-excursion
  656.     (goto-char end)   (beginning-of-line) (setq end (point))
  657.     (goto-char start) (beginning-of-line) (setq start (point))
  658.     (indent-rigidly start end count)))
  659.  
  660. (defun py-shift-region-left (start end &optional count)
  661.   "Shift region of Python code to the left.
  662. The lines from the line containing the start of the current region up
  663. to (but not including) the line containing the end of the region are
  664. shifted to the left, by py-indent-offset columns.
  665.  
  666. If a prefix argument is given, the region is instead shifted by that
  667. many columns."
  668.   (interactive "*r\nP")   ; region; raw prefix arg
  669.   (py-shift-region start end
  670.            (- (prefix-numeric-value
  671.                (or count py-indent-offset)))))
  672.  
  673. (defun py-shift-region-right (start end &optional count)
  674.   "Shift region of Python code to the right.
  675. The lines from the line containing the start of the current region up
  676. to (but not including) the line containing the end of the region are
  677. shifted to the right, by py-indent-offset columns.
  678.  
  679. If a prefix argument is given, the region is instead shifted by that
  680. many columns."
  681.   (interactive "*r\nP")   ; region; raw prefix arg
  682.   (py-shift-region start end (prefix-numeric-value
  683.                   (or count py-indent-offset))))
  684.  
  685. (defun py-indent-region (start end &optional indent-offset)
  686.   "Reindent a region of Python code.
  687. The lines from the line containing the start of the current region up
  688. to (but not including) the line containing the end of the region are
  689. reindented.  If the first line of the region has a non-whitespace
  690. character in the first column, the first line is left alone and the rest
  691. of the region is reindented with respect to it.  Else the entire region
  692. is reindented with respect to the (closest code or indenting-comment)
  693. statement immediately preceding the region.
  694.  
  695. This is useful when code blocks are moved or yanked, when enclosing
  696. control structures are introduced or removed, or to reformat code using
  697. a new value for the indentation offset.
  698.  
  699. If a numeric prefix argument is given, it will be used as the value of
  700. the indentation offset.  Else the value of py-indent-offset will be
  701. used.
  702.  
  703. Warning:  The region must be consistently indented before this function
  704. is called!  This function does not compute proper indentation from
  705. scratch (that's impossible in Python), it merely adjusts the existing
  706. indentation to be correct in context.
  707.  
  708. Warning:  This function really has no idea what to do with non-indenting
  709. comment lines, and shifts them as if they were indenting comment lines.
  710. Fixing this appears to require telepathy.
  711.  
  712. Special cases:  whitespace is deleted from blank lines; continuation
  713. lines are shifted by the same amount their initial line was shifted, in
  714. order to preserve their relative indentation with respect to their
  715. initial line; and comment lines beginning in column 1 are ignored."
  716.  
  717.   (interactive "*r\nP") ; region; raw prefix arg
  718.   (save-excursion
  719.     (goto-char end)   (beginning-of-line) (setq end (point-marker))
  720.     (goto-char start) (beginning-of-line)
  721.     (let ( (py-indent-offset (prefix-numeric-value
  722.                   (or indent-offset py-indent-offset)))
  723.        (indents '(-1))    ; stack of active indent levels
  724.        (target-column 0)    ; column to which to indent
  725.        (base-shifted-by 0)    ; amount last base line was shifted
  726.        (indent-base (if (looking-at "[ \t\n]")
  727.                 (py-compute-indentation)
  728.               0))
  729.        ci)
  730.       (while (< (point) end)
  731.     (setq ci (current-indentation))
  732.     ;; figure out appropriate target column
  733.     (cond
  734.      ( (or (eq (following-char) ?#)    ; comment in column 1
  735.            (looking-at "[ \t]*$"))    ; entirely blank
  736.        (setq target-column 0))
  737.      ( (py-continuation-line-p)    ; shift relative to base line
  738.        (setq target-column (+ ci base-shifted-by)))
  739.      (t                ; new base line
  740.       (if (> ci (car indents))    ; going deeper; push it
  741.           (setq indents (cons ci indents))
  742.         ;; else we should have seen this indent before
  743.         (setq indents (memq ci indents)) ; pop deeper indents
  744.         (if (null indents)
  745.         (error "Bad indentation in region, at line %d"
  746.                (save-restriction
  747.              (widen)
  748.              (1+ (count-lines 1 (point)))))))
  749.       (setq target-column (+ indent-base
  750.                  (* py-indent-offset
  751.                     (- (length indents) 2))))
  752.       (setq base-shifted-by (- target-column ci))))
  753.     ;; shift as needed
  754.     (if (/= ci target-column)
  755.         (progn
  756.           (delete-horizontal-space)
  757.           (indent-to target-column)))
  758.     (forward-line 1))))
  759.   (set-marker end nil))
  760.  
  761. ;;; Functions for moving point
  762.  
  763. (defun py-previous-statement (count)
  764.   "Go to the start of previous Python statement.
  765. If the statement at point is the i'th Python statement, goes to the
  766. start of statement i-COUNT.  If there is no such statement, goes to the
  767. first statement.  Returns count of statements left to move.
  768. `Statements' do not include blank, comment, or continuation lines."
  769.   (interactive "p") ; numeric prefix arg
  770.   (if (< count 0) (py-next-statement (- count))
  771.     (py-goto-initial-line)
  772.     (let ( start )
  773.       (while (and
  774.           (setq start (point)) ; always true -- side effect
  775.           (> count 0)
  776.           (zerop (forward-line -1))
  777.           (py-goto-statement-at-or-above))
  778.     (setq count (1- count)))
  779.       (if (> count 0) (goto-char start)))
  780.     count))
  781.  
  782. (defun py-next-statement (count)
  783.   "Go to the start of next Python statement.
  784. If the statement at point is the i'th Python statement, goes to the
  785. start of statement i+COUNT.  If there is no such statement, goes to the
  786. last statement.  Returns count of statements left to move.  `Statements'
  787. do not include blank, comment, or continuation lines."
  788.   (interactive "p") ; numeric prefix arg
  789.   (if (< count 0) (py-previous-statement (- count))
  790.     (beginning-of-line)
  791.     (let ( start )
  792.       (while (and
  793.           (setq start (point)) ; always true -- side effect
  794.           (> count 0)
  795.           (py-goto-statement-below))
  796.     (setq count (1- count)))
  797.       (if (> count 0) (goto-char start)))
  798.     count))
  799.  
  800. (defun py-goto-block-up (&optional nomark)
  801.   "Move up to start of current block.
  802. Go to the statement that starts the smallest enclosing block; roughly
  803. speaking, this will be the closest preceding statement that ends with a
  804. colon and is indented less than the statement you started on.  If
  805. successful, also sets the mark to the starting point.
  806.  
  807. `\\[py-mark-block]' can be used afterward to mark the whole code block, if desired.
  808.  
  809. If called from a program, the mark will not be set if optional argument
  810. NOMARK is not nil."
  811.   (interactive)
  812.   (let ( (start (point))
  813.      (found nil)
  814.      initial-indent)
  815.     (py-goto-initial-line)
  816.     ;; if on blank or non-indenting comment line, use the preceding stmt
  817.     (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  818.     (progn
  819.       (py-goto-statement-at-or-above)
  820.       (setq found (py-statement-opens-block-p))))
  821.     ;; search back for colon line indented less
  822.     (setq initial-indent (current-indentation))
  823.     (if (zerop initial-indent)
  824.     ;; force fast exit
  825.     (goto-char (point-min)))
  826.     (while (not (or found (bobp)))
  827.       (setq found
  828.         (and
  829.          (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
  830.          (or (py-goto-initial-line) t) ; always true -- side effect
  831.          (< (current-indentation) initial-indent)
  832.          (py-statement-opens-block-p))))
  833.     (if found
  834.     (progn
  835.       (or nomark (push-mark start))
  836.       (back-to-indentation))
  837.       (goto-char start)
  838.       (error "Enclosing block not found"))))
  839.  
  840. (defun beginning-of-python-def-or-class (&optional class)
  841.   "Move point to start of def (or class, with prefix arg).
  842.  
  843. Searches back for the closest preceding `def'.  If you supply a prefix
  844. arg, looks for a `class' instead.  The docs assume the `def' case; just
  845. substitute `class' for `def' for the other case.
  846.  
  847. If point is in a def statement already, and after the `d', simply moves
  848. point to the start of the statement.
  849.  
  850. Else (point is not in a def statement, or at or before the `d' of a def
  851. statement), searches for the closest preceding def statement, and leaves
  852. point at its start.  If no such statement can be found, leaves point at
  853. the start of the buffer.
  854.  
  855. Returns t iff a def statement is found by these rules.
  856.  
  857. Note that doing this command repeatedly will take you closer to the start
  858. of the buffer each time.
  859.  
  860. If you want to mark the current def/class, see `\\[mark-python-def-or-class]'."
  861.   (interactive "P")            ; raw prefix arg
  862.   (let ( (at-or-before-p (<= (current-column) (current-indentation)))
  863.      (start-of-line (progn (beginning-of-line) (point)))
  864.      (start-of-stmt (progn (py-goto-initial-line) (point))))
  865.     (if (or (/= start-of-stmt start-of-line)
  866.         (not at-or-before-p))
  867.     (end-of-line))            ; OK to match on this line
  868.     (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
  869.     nil 'move)))
  870.  
  871. (defun end-of-python-def-or-class (&optional class)
  872.   "Move point beyond end of def (or class, with prefix arg) body.
  873.  
  874. By default, looks for an appropriate `def'.  If you supply a prefix arg,
  875. looks for a `class' instead.  The docs assume the `def' case; just
  876. substitute `class' for `def' for the other case.
  877.  
  878. If point is in a def statement already, this is the def we use.
  879.  
  880. Else if the def found by `\\[beginning-of-python-def-or-class]' contains the statement you
  881. started on, that's the def we use.
  882.  
  883. Else we search forward for the closest following def, and use that.
  884.  
  885. If a def can be found by these rules, point is moved to the start of the
  886. line immediately following the def block, and the position of the start
  887. of the def is returned.
  888.  
  889. Else point is moved to the end of the buffer, and nil is returned.
  890.  
  891. Note that doing this command repeatedly will take you closer to the end
  892. of the buffer each time.
  893.  
  894. If you want to mark the current def/class, see `\\[mark-python-def-or-class]'."
  895.   (interactive "P")            ; raw prefix arg
  896.   (let ( (start (progn (py-goto-initial-line) (point)))
  897.      (which (if class "class" "def"))
  898.      (state 'not-found))
  899.     ;; move point to start of appropriate def/class
  900.     (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
  901.     (setq state 'at-beginning)
  902.       ;; else see if beginning-of-python-def-or-class hits container
  903.       (if (and (beginning-of-python-def-or-class class)
  904.            (progn (py-goto-beyond-block)
  905.               (> (point) start)))
  906.       (setq state 'at-end)
  907.     ;; else search forward
  908.     (goto-char start)
  909.     (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
  910.         (progn (setq state 'at-beginning)
  911.            (beginning-of-line)))))
  912.     (cond
  913.      ((eq state 'at-beginning) (py-goto-beyond-block) t)
  914.      ((eq state 'at-end) t)
  915.      ((eq state 'not-found) nil)
  916.      (t (error "internal error in end-of-python-def-or-class")))))
  917.  
  918. ;;; Functions for marking regions
  919.  
  920. (defun py-mark-block (&optional extend just-move)
  921.   "Mark following block of lines.  With prefix arg, mark structure.
  922. Easier to use than explain.  It sets the region to an `interesting'
  923. block of succeeding lines.  If point is on a blank line, it goes down to
  924. the next non-blank line.  That will be the start of the region.  The end
  925. of the region depends on the kind of line at the start:
  926.  
  927.  - If a comment, the region will include all succeeding comment lines up
  928.    to (but not including) the next non-comment line (if any).
  929.  
  930.  - Else if a prefix arg is given, and the line begins one of these
  931.    structures:
  932. \tif elif else try except finally for while def class
  933.    the region will be set to the body of the structure, including
  934.    following blocks that `belong' to it, but excluding trailing blank
  935.    and comment lines.  E.g., if on a `try' statement, the `try' block
  936.    and all (if any) of the following `except' and `finally' blocks that
  937.    belong to the `try' structure will be in the region.  Ditto for
  938.    if/elif/else, for/else and while/else structures, and (a bit
  939.    degenerate, since they're always one-block structures) def and class
  940.    blocks.
  941.  
  942.  - Else if no prefix argument is given, and the line begins a Python
  943.    block (see list above), and the block is not a `one-liner' (i.e., the
  944.    statement ends with a colon, not with code), the region will include
  945.    all succeeding lines up to (but not including) the next code
  946.    statement (if any) that's indented no more than the starting line,
  947.    except that trailing blank and comment lines are excluded.  E.g., if
  948.    the starting line begins a multi-statement `def' structure, the
  949.    region will be set to the full function definition, but without any
  950.    trailing `noise' lines.
  951.  
  952.  - Else the region will include all succeeding lines up to (but not
  953.    including) the next blank line, or code or indenting-comment line
  954.    indented strictly less than the starting line.  Trailing indenting
  955.    comment lines are included in this case, but not trailing blank
  956.    lines.
  957.  
  958. A msg identifying the location of the mark is displayed in the echo
  959. area; or do `\\[exchange-point-and-mark]' to flip down to the end.
  960.  
  961. If called from a program, optional argument EXTEND plays the role of the
  962. prefix arg, and if optional argument JUST-MOVE is not nil, just moves to
  963. the end of the block (& does not set mark or display a msg)."
  964.  
  965.   (interactive "P")            ; raw prefix arg
  966.   (py-goto-initial-line)
  967.   ;; skip over blank lines
  968.   (while (and
  969.       (looking-at "[ \t]*$")    ; while blank line
  970.       (not (eobp)))            ; & somewhere to go
  971.     (forward-line 1))
  972.   (if (eobp)
  973.       (error "Hit end of buffer without finding a non-blank stmt"))
  974.   (let ( (initial-pos (point))
  975.      (initial-indent (current-indentation))
  976.      last-pos            ; position of last stmt in region
  977.      (followers
  978.       '( (if elif else) (elif elif else) (else)
  979.          (try except finally) (except except) (finally)
  980.          (for else) (while else)
  981.          (def) (class) ) )
  982.      first-symbol next-symbol)
  983.  
  984.     (cond
  985.      ;; if comment line, suck up the following comment lines
  986.      ((looking-at "[ \t]*#")
  987.       (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
  988.       (re-search-backward "^[ \t]*#")    ; and back to last comment in block
  989.       (setq last-pos (point)))
  990.  
  991.      ;; else if line is a block line and EXTEND given, suck up
  992.      ;; the whole structure
  993.      ((and extend
  994.        (setq first-symbol (py-suck-up-first-keyword) )
  995.        (assq first-symbol followers))
  996.       (while (and
  997.           (or (py-goto-beyond-block) t) ; side effect
  998.           (forward-line -1)        ; side effect
  999.           (setq last-pos (point))    ; side effect
  1000.           (py-goto-statement-below)
  1001.           (= (current-indentation) initial-indent)
  1002.           (setq next-symbol (py-suck-up-first-keyword))
  1003.           (memq next-symbol (cdr (assq first-symbol followers))))
  1004.     (setq first-symbol next-symbol)))
  1005.  
  1006.      ;; else if line *opens* a block, search for next stmt indented <=
  1007.      ((py-statement-opens-block-p)
  1008.       (while (and
  1009.           (setq last-pos (point))    ; always true -- side effect
  1010.           (py-goto-statement-below)
  1011.           (> (current-indentation) initial-indent))
  1012.     nil))
  1013.  
  1014.      ;; else plain code line; stop at next blank line, or stmt or
  1015.      ;; indenting comment line indented <
  1016.      (t
  1017.       (while (and
  1018.           (setq last-pos (point))    ; always true -- side effect
  1019.           (or (py-goto-beyond-final-line) t)
  1020.           (not (looking-at "[ \t]*$")) ; stop at blank line
  1021.           (or
  1022.            (>= (current-indentation) initial-indent)
  1023.            (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
  1024.     nil)))
  1025.  
  1026.     ;; skip to end of last stmt
  1027.     (goto-char last-pos)
  1028.     (py-goto-beyond-final-line)
  1029.  
  1030.     ;; set mark & display
  1031.     (if just-move
  1032.     ()                ; just return
  1033.       (push-mark (point) 'no-msg)
  1034.       (forward-line -1)
  1035.       (message "Mark set after: %s" (py-suck-up-leading-text))
  1036.       (goto-char initial-pos))))
  1037.  
  1038. (defun mark-python-def-or-class (&optional class)
  1039.   "Set region to body of def (or class, with prefix arg) enclosing point.
  1040. Pushes the current mark, then point, on the mark ring (all language
  1041. modes do this, but although it's handy it's never documented ...).
  1042.  
  1043. In most Emacs language modes, this function bears at least a
  1044. hallucinogenic resemblance to  `\\[end-of-python-def-or-class]' and `\\[beginning-of-python-def-or-class]'.
  1045.  
  1046. And in earlier versions of Python mode, all 3 were tightly connected.
  1047. Turned out that was more confusing than useful:  the `goto start' and
  1048. `goto end' commands are usually used to search through a file, and people
  1049. expect them to act a lot like `search backward' and `search forward'
  1050. string-search commands.  But because Python `def' and `class' can nest to
  1051. arbitrary levels, finding the smallest def containing point cannot be
  1052. done via a simple backward search:  the def containing point may not be
  1053. the closest preceding def, or even the closest preceding def that's
  1054. indented less.  The fancy algorithm required is appropriate for the usual
  1055. uses of this `mark' command, but not for the `goto' variations.
  1056.  
  1057. So the def marked by this command may not be the one either of the `goto'
  1058. commands find:  If point is on a blank or non-indenting comment line,
  1059. moves back to start of the closest preceding code statement or indenting
  1060. comment line.  If this is a `def' statement, that's the def we use.  Else
  1061. searches for the smallest enclosing `def' block and uses that.  Else
  1062. signals an error.
  1063.  
  1064. When an enclosing def is found:  The mark is left immediately beyond the
  1065. last line of the def block.  Point is left at the start of the def,
  1066. except that:  if the def is preceded by a number of comment lines
  1067. followed by (at most) one optional blank line, point is left at the start
  1068. of the comments; else if the def is preceded by a blank line, point is
  1069. left at its start.
  1070.  
  1071. The intent is to mark the containing def/class and its associated
  1072. documentation, to make moving and duplicating functions and classes
  1073. pleasant."
  1074.   (interactive "P")            ; raw prefix arg
  1075.   (let ( (start (point))
  1076.      (which (if class "class" "def")))
  1077.     (push-mark start)
  1078.     (if (not (py-go-up-tree-to-keyword which))
  1079.     (progn (goto-char start)
  1080.            (error "Enclosing %s not found" which))
  1081.       ;; else enclosing def/class found
  1082.       (setq start (point))
  1083.       (py-goto-beyond-block)
  1084.       (push-mark (point))
  1085.       (goto-char start)
  1086.       (if (zerop (forward-line -1))    ; if there is a preceding line
  1087.       (progn
  1088.         (if (looking-at "[ \t]*$")    ; it's blank
  1089.         (setq start (point))    ; so reset start point
  1090.           (goto-char start))    ; else try again
  1091.         (if (zerop (forward-line -1))
  1092.         (if (looking-at "[ \t]*#") ; a comment
  1093.             ;; look back for non-comment line
  1094.             ;; tricky: note that the regexp matches a blank
  1095.             ;; line, cuz \n is in the 2nd character class
  1096.             (and
  1097.              (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
  1098.              (forward-line 1))
  1099.           ;; no comment, so go back
  1100.           (goto-char start))))))))
  1101.  
  1102. (defun py-comment-region (start end &optional uncomment-p)
  1103.   "Comment out region of code; with prefix arg, uncomment region.
  1104. The lines from the line containing the start of the current region up
  1105. to (but not including) the line containing the end of the region are
  1106. commented out, by inserting the string py-block-comment-prefix at the
  1107. start of each line.  With a prefix arg, removes py-block-comment-prefix
  1108. from the start of each line instead."
  1109.   (interactive "*r\nP")   ; region; raw prefix arg
  1110.   (goto-char end)   (beginning-of-line) (setq end (point))
  1111.   (goto-char start) (beginning-of-line) (setq start (point))
  1112.   (let ( (prefix-len (length py-block-comment-prefix)) )
  1113.     (save-excursion
  1114.       (save-restriction
  1115.     (narrow-to-region start end)
  1116.     (while (not (eobp))
  1117.       (if uncomment-p
  1118.           (and (string= py-block-comment-prefix
  1119.                 (buffer-substring
  1120.                  (point) (+ (point) prefix-len)))
  1121.            (delete-char prefix-len))
  1122.         (insert py-block-comment-prefix))
  1123.       (forward-line 1))))))
  1124.  
  1125. ;;; Documentation functions
  1126.  
  1127. ;; dump the long form of the mode blurb; does the usual doc escapes,
  1128. ;; plus lines of the form ^[vc]:name$ to suck variable & command
  1129. ;; docs out of the right places, along with the keys they're on &
  1130. ;; current values
  1131. (defun py-dump-help-string (str)
  1132.   (with-output-to-temp-buffer "*Help*"
  1133.     (let ( (locals (buffer-local-variables))
  1134.        funckind funcname func funcdoc
  1135.        (start 0) mstart end
  1136.        keys )
  1137.       (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
  1138.     (setq mstart (match-beginning 0)  end (match-end 0)
  1139.           funckind (substring str (match-beginning 1) (match-end 1))
  1140.           funcname (substring str (match-beginning 2) (match-end 2))
  1141.           func (intern funcname))
  1142.     (princ (substitute-command-keys (substring str start mstart)))
  1143.     (cond
  1144.      ( (equal funckind "c")        ; command
  1145.        (setq funcdoc (documentation func)
  1146.          keys (concat
  1147.                "Key(s): "
  1148.                (mapconcat 'key-description
  1149.                   (where-is-internal func py-mode-map)
  1150.                   ", "))))
  1151.      ( (equal funckind "v")        ; variable
  1152.        (setq funcdoc (substitute-command-keys
  1153.               (get func 'variable-documentation))
  1154.          keys (if (assq func locals)
  1155.               (concat
  1156.                "Local/Global values: "
  1157.                (prin1-to-string (symbol-value func))
  1158.                " / "
  1159.                (prin1-to-string (default-value func)))
  1160.             (concat
  1161.              "Value: "
  1162.              (prin1-to-string (symbol-value func))))))
  1163.      ( t                ; unexpected
  1164.        (error "Error in py-dump-help-string, tag `%s'" funckind)))
  1165.     (princ (format "\n-> %s:\t%s\t%s\n\n"
  1166.                (if (equal funckind "c") "Command" "Variable")
  1167.                funcname keys))
  1168.     (princ funcdoc)
  1169.     (terpri)
  1170.     (setq start end))
  1171.       (princ (substitute-command-keys (substring str start))))
  1172.     (print-help-return-message)))
  1173.  
  1174. (defun py-describe-mode ()
  1175.   "Dump long form of Python-mode docs."
  1176.   (interactive)
  1177.   (py-dump-help-string "Major mode for editing Python files.
  1178. Knows about Python indentation, tokens, comments and continuation lines.
  1179. Paragraphs are separated by blank lines only.
  1180.  
  1181. Major sections below begin with the string `@'; specific function and
  1182. variable docs begin with `->'.
  1183.  
  1184. @EXECUTING PYTHON CODE
  1185.  
  1186. \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
  1187. \\[py-execute-region]\tsends the current region
  1188. \\[py-shell]\tstarts a Python interpreter window; this will be used by
  1189. \tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
  1190. %c:py-execute-buffer
  1191. %c:py-execute-region
  1192. %c:py-shell
  1193.  
  1194. @VARIABLES
  1195.  
  1196. py-indent-offset\tindentation increment
  1197. py-block-comment-prefix\tcomment string used by py-comment-region
  1198.  
  1199. py-python-command\tshell command to invoke Python interpreter
  1200. py-scroll-process-buffer\talways scroll Python process buffer
  1201. py-temp-directory\tdirectory used for temp files (if needed)
  1202.  
  1203. py-beep-if-tab-change\tring the bell if tab-width is changed
  1204. %v:py-indent-offset
  1205. %v:py-block-comment-prefix
  1206. %v:py-python-command
  1207. %v:py-scroll-process-buffer
  1208. %v:py-temp-directory
  1209. %v:py-beep-if-tab-change
  1210.  
  1211. @KINDS OF LINES
  1212.  
  1213. Each physical line in the file is either a `continuation line' (the
  1214. preceding line ends with a backslash that's not part of a comment, or the
  1215. paren/bracket/brace nesting level at the start of the line is non-zero,
  1216. or both) or an `initial line' (everything else).
  1217.  
  1218. An initial line is in turn a `blank line' (contains nothing except
  1219. possibly blanks or tabs), a `comment line' (leftmost non-blank character
  1220. is `#'), or a `code line' (everything else).
  1221.  
  1222. Comment Lines
  1223.  
  1224. Although all comment lines are treated alike by Python, Python mode
  1225. recognizes two kinds that act differently with respect to indentation.
  1226.  
  1227. An `indenting comment line' is a comment line with a blank, tab or
  1228. nothing after the initial `#'.  The indentation commands (see below)
  1229. treat these exactly as if they were code lines:  a line following an
  1230. indenting comment line will be indented like the comment line.  All
  1231. other comment lines (those with a non-whitespace character immediately
  1232. following the initial `#') are `non-indenting comment lines', and their
  1233. indentation is ignored by the indentation commands.
  1234.  
  1235. Indenting comment lines are by far the usual case, and should be used
  1236. whenever possible.  Non-indenting comment lines are useful in cases like
  1237. these:
  1238.  
  1239. \ta = b   # a very wordy single-line comment that ends up being
  1240. \t        #... continued onto another line
  1241.  
  1242. \tif a == b:
  1243. ##\t\tprint 'panic!' # old code we've `commented out'
  1244. \t\treturn a
  1245.  
  1246. Since the `#...' and `##' comment lines have a non-whitespace character
  1247. following the initial `#', Python mode ignores them when computing the
  1248. proper indentation for the next line.
  1249.  
  1250. Continuation Lines and Statements
  1251.  
  1252. The Python-mode commands generally work on statements instead of on
  1253. individual lines, where a `statement' is a comment or blank line, or a
  1254. code line and all of its following continuation lines (if any)
  1255. considered as a single logical unit.  The commands in this mode
  1256. generally (when it makes sense) automatically move to the start of the
  1257. statement containing point, even if point happens to be in the middle of
  1258. some continuation line.
  1259.  
  1260.  
  1261. @INDENTATION
  1262.  
  1263. Primarily for entering new code:
  1264. \t\\[indent-for-tab-command]\t indent line appropriately
  1265. \t\\[py-newline-and-indent]\t insert newline, then indent
  1266. \t\\[py-delete-char]\t reduce indentation, or delete single character
  1267.  
  1268. Primarily for reindenting existing code:
  1269. \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
  1270. \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
  1271.  
  1272. \t\\[py-indent-region]\t reindent region to match its context
  1273. \t\\[py-shift-region-left]\t shift region left by py-indent-offset
  1274. \t\\[py-shift-region-right]\t shift region right by py-indent-offset
  1275.  
  1276. Unlike most programming languages, Python uses indentation, and only
  1277. indentation, to specify block structure.  Hence the indentation supplied
  1278. automatically by Python-mode is just an educated guess:  only you know
  1279. the block structure you intend, so only you can supply correct
  1280. indentation.
  1281.  
  1282. The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
  1283. the indentation of preceding statements.  E.g., assuming
  1284. py-indent-offset is 4, after you enter
  1285. \tif a > 0: \\[py-newline-and-indent]
  1286. the cursor will be moved to the position of the `_' (_ is not a
  1287. character in the file, it's just used here to indicate the location of
  1288. the cursor):
  1289. \tif a > 0:
  1290. \t    _
  1291. If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
  1292. to
  1293. \tif a > 0:
  1294. \t    c = d
  1295. \t    _
  1296. Python-mode cannot know whether that's what you intended, or whether
  1297. \tif a > 0:
  1298. \t    c = d
  1299. \t_
  1300. was your intent.  In general, Python-mode either reproduces the
  1301. indentation of the (closest code or indenting-comment) preceding
  1302. statement, or adds an extra py-indent-offset blanks if the preceding
  1303. statement has `:' as its last significant (non-whitespace and non-
  1304. comment) character.  If the suggested indentation is too much, use
  1305. \\[py-delete-char] to reduce it.
  1306.  
  1307. Continuation lines are given extra indentation.  If you don't like the
  1308. suggested indentation, change it to something you do like, and Python-
  1309. mode will strive to indent later lines of the statement in the same way.
  1310.  
  1311. If a line is a continuation line by virtue of being in an unclosed
  1312. paren/bracket/brace structure (`list', for short), the suggested
  1313. indentation depends on whether the current line contains the first item
  1314. in the list.  If it does, it's indented py-indent-offset columns beyond
  1315. the indentation of the line containing the open bracket.  If you don't
  1316. like that, change it by hand.  The remaining items in the list will mimic
  1317. whatever indentation you give to the first item.
  1318.  
  1319. If a line is a continuation line because the line preceding it ends with
  1320. a backslash, the third and following lines of the statement inherit their
  1321. indentation from the line preceding them.  The indentation of the second
  1322. line in the statement depends on the form of the first (base) line:  if
  1323. the base line is an assignment statement with anything more interesting
  1324. than the backslash following the leftmost assigning `=', the second line
  1325. is indented two columns beyond that `='.  Else it's indented to two
  1326. columns beyond the leftmost solid chunk of non-whitespace characters on
  1327. the base line.
  1328.  
  1329. Warning:  indent-region should not normally be used!  It calls \\[indent-for-tab-command]
  1330. repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
  1331. structure you intend.
  1332. %c:indent-for-tab-command
  1333. %c:py-newline-and-indent
  1334. %c:py-delete-char
  1335.  
  1336.  
  1337. The next function may be handy when editing code you didn't write:
  1338. %c:py-guess-indent-offset
  1339.  
  1340.  
  1341. The remaining `indent' functions apply to a region of Python code.  They
  1342. assume the block structure (equals indentation, in Python) of the region
  1343. is correct, and alter the indentation in various ways while preserving
  1344. the block structure:
  1345. %c:py-indent-region
  1346. %c:py-shift-region-left
  1347. %c:py-shift-region-right
  1348.  
  1349. @MARKING & MANIPULATING REGIONS OF CODE
  1350.  
  1351. \\[py-mark-block]\t mark block of lines
  1352. \\[mark-python-def-or-class]\t mark smallest enclosing def
  1353. \\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class
  1354. \\[py-comment-region]\t comment out region of code
  1355. \\[universal-argument] \\[py-comment-region]\t uncomment region of code
  1356. %c:py-mark-block
  1357. %c:mark-python-def-or-class
  1358. %c:py-comment-region
  1359.  
  1360. @MOVING POINT
  1361.  
  1362. \\[py-previous-statement]\t move to statement preceding point
  1363. \\[py-next-statement]\t move to statement following point
  1364. \\[py-goto-block-up]\t move up to start of current block
  1365. \\[beginning-of-python-def-or-class]\t move to start of def
  1366. \\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
  1367. \\[end-of-python-def-or-class]\t move to end of def
  1368. \\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
  1369.  
  1370. The first two move to one statement beyond the statement that contains
  1371. point.  A numeric prefix argument tells them to move that many
  1372. statements instead.  Blank lines, comment lines, and continuation lines
  1373. do not count as `statements' for these commands.  So, e.g., you can go
  1374. to the first code statement in a file by entering
  1375. \t\\[beginning-of-buffer]\t to move to the top of the file
  1376. \t\\[py-next-statement]\t to skip over initial comments and blank lines
  1377. Or do `\\[py-previous-statement]' with a huge prefix argument.
  1378. %c:py-previous-statement
  1379. %c:py-next-statement
  1380. %c:py-goto-block-up
  1381. %c:beginning-of-python-def-or-class
  1382. %c:end-of-python-def-or-class
  1383.  
  1384. @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
  1385.  
  1386. `\\[indent-new-comment-line]' is handy for entering a multi-line comment.
  1387.  
  1388. `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
  1389. overall class and def structure of a module.
  1390.  
  1391. `\\[back-to-indentation]' moves point to a line's first non-blank character.
  1392.  
  1393. `\\[indent-relative]' is handy for creating odd indentation.
  1394.  
  1395. @OTHER EMACS HINTS
  1396.  
  1397. If you don't like the default value of a variable, change its value to
  1398. whatever you do like by putting a `setq' line in your .emacs file.
  1399. E.g., to set the indentation increment to 4, put this line in your
  1400. .emacs:
  1401. \t(setq  py-indent-offset  4)
  1402. To see the value of a variable, do `\\[describe-variable]' and enter the variable
  1403. name at the prompt.
  1404.  
  1405. When entering a key sequence like `C-c C-n', it is not necessary to
  1406. release the CONTROL key after doing the `C-c' part -- it suffices to
  1407. press the CONTROL key, press and release `c' (while still holding down
  1408. CONTROL), press and release `n' (while still holding down CONTROL), &
  1409. then release CONTROL.
  1410.  
  1411. Entering Python mode calls with no arguments the value of the variable
  1412. `py-mode-hook', if that value exists and is not nil; see the `Hooks'
  1413. section of the Elisp manual for details.
  1414.  
  1415. Obscure:  When python-mode is first loaded, it looks for all bindings
  1416. to newline-and-indent in the global keymap, and shadows them with
  1417. local bindings to py-newline-and-indent."))
  1418.  
  1419. ;;; Helper functions
  1420.  
  1421. (defvar py-parse-state-re
  1422.   (concat
  1423.    "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
  1424.    "\\|"
  1425.    "^[^ #\t\n]"))
  1426. ;; returns the parse state at point (see parse-partial-sexp docs)
  1427. (defun py-parse-state ()
  1428.   (save-excursion
  1429.     (let ( (here (point)) )
  1430.       ;; back up to the first preceding line (if any; else start of
  1431.       ;; buffer) that begins with a popular Python keyword, or a non-
  1432.       ;; whitespace and non-comment character.  These are good places to
  1433.       ;; start parsing to see whether where we started is at a non-zero
  1434.       ;; nesting level.  It may be slow for people who write huge code
  1435.       ;; blocks or huge lists ... tough beans.
  1436.       (re-search-backward py-parse-state-re nil 'move)
  1437.       (beginning-of-line)
  1438.       (parse-partial-sexp (point) here))))
  1439.  
  1440. ;; if point is at a non-zero nesting level, returns the number of the
  1441. ;; character that opens the smallest enclosing unclosed list; else
  1442. ;; returns nil.
  1443. (defun py-nesting-level ()
  1444.   (let ( (status (py-parse-state)) )
  1445.     (if (zerop (car status))
  1446.     nil                ; not in a nest
  1447.       (car (cdr status)))))        ; char# of open bracket
  1448.  
  1449. ;; t iff preceding line ends with backslash that's not in a comment
  1450. (defun py-backslash-continuation-line-p ()
  1451.   (save-excursion
  1452.     (beginning-of-line)
  1453.     (and
  1454.      ;; use a cheap test first to avoid the regexp if possible
  1455.      ;; use 'eq' because char-after may return nil
  1456.      (eq (char-after (- (point) 2)) ?\\ )
  1457.      ;; make sure; since eq test passed, there is a preceding line
  1458.      (forward-line -1) ; always true -- side effect
  1459.      (looking-at py-continued-re))))
  1460.  
  1461. ;; t iff current line is a continuation line
  1462. (defun py-continuation-line-p ()
  1463.   (save-excursion
  1464.    (beginning-of-line)
  1465.     (or (py-backslash-continuation-line-p)
  1466.     (py-nesting-level))))
  1467.  
  1468. ;; go to initial line of current statement; usually this is the
  1469. ;; line we're on, but if we're on the 2nd or following lines of a
  1470. ;; continuation block, we need to go up to the first line of the block.
  1471. ;;
  1472. ;; Tricky:  We want to avoid quadratic-time behavior for long continued
  1473. ;; blocks, whether of the backslash or open-bracket varieties, or a mix
  1474. ;; of the two.  The following manages to do that in the usual cases.
  1475. (defun py-goto-initial-line ()
  1476.   (let ( open-bracket-pos )
  1477.     (while (py-continuation-line-p)
  1478.       (beginning-of-line)
  1479.       (if (py-backslash-continuation-line-p)
  1480.       (while (py-backslash-continuation-line-p)
  1481.         (forward-line -1))
  1482.     ;; else zip out of nested brackets/braces/parens
  1483.     (while (setq open-bracket-pos (py-nesting-level))
  1484.       (goto-char open-bracket-pos)))))
  1485.   (beginning-of-line))
  1486.  
  1487. ;; go to point right beyond final line of current statement; usually
  1488. ;; this is the start of the next line, but if this is a multi-line
  1489. ;; statement we need to skip over the continuation lines.
  1490. ;; Tricky:  Again we need to be clever to avoid quadratic time behavior.
  1491. (defun py-goto-beyond-final-line ()
  1492.   (forward-line 1)
  1493.   (let ( state )
  1494.     (while (and (py-continuation-line-p)
  1495.         (not (eobp)))
  1496.       ;; skip over the backslash flavor
  1497.       (while (and (py-backslash-continuation-line-p)
  1498.           (not (eobp)))
  1499.     (forward-line 1))
  1500.       ;; if in nest, zip to the end of the nest
  1501.       (setq state (py-parse-state))
  1502.       (if (and (not (zerop (car state)))
  1503.            (not (eobp)))
  1504.       (progn
  1505.         ;; BUG ALERT:  I could swear, from reading the docs, that
  1506.         ;; the 3rd argument should be plain 0
  1507.         (parse-partial-sexp (point) (point-max) (- 0 (car state))
  1508.                 nil state)
  1509.         (forward-line 1))))))
  1510.  
  1511. ;; t iff statement opens a block == iff it ends with a colon that's
  1512. ;; not in a comment
  1513. ;; point should be at the start of a statement
  1514. (defun py-statement-opens-block-p ()
  1515.   (save-excursion
  1516.     (let ( (start (point))
  1517.        (finish (progn (py-goto-beyond-final-line) (1- (point))))
  1518.        (searching t)
  1519.        (answer nil)
  1520.        state)
  1521.       (goto-char start)
  1522.       (while searching
  1523.     ;; look for a colon with nothing after it except whitespace, and
  1524.     ;; maybe a comment
  1525.     (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
  1526.                    finish t)
  1527.         (if (eq (point) finish)    ; note: no `else' clause; just
  1528.                     ; keep searching if we're not at
  1529.                     ; the end yet
  1530.         ;; sure looks like it opens a block -- but it might
  1531.         ;; be in a comment
  1532.         (progn
  1533.           (setq searching nil)    ; search is done either way
  1534.           (setq state (parse-partial-sexp start
  1535.                           (match-beginning 0)))
  1536.           (setq answer (not (nth 4 state)))))
  1537.       ;; search failed: couldn't find another interesting colon
  1538.       (setq searching nil)))
  1539.       answer)))
  1540.  
  1541. ;; go to point right beyond final line of block begun by the current
  1542. ;; line.  This is the same as where py-goto-beyond-final-line goes
  1543. ;; unless we're on colon line, in which case we go to the end of the
  1544. ;; block.
  1545. ;; assumes point is at bolp
  1546. (defun py-goto-beyond-block ()
  1547.   (if (py-statement-opens-block-p)
  1548.       (py-mark-block nil 'just-move)
  1549.     (py-goto-beyond-final-line)))
  1550.  
  1551. ;; go to start of first statement (not blank or comment or continuation
  1552. ;; line) at or preceding point
  1553. ;; returns t if there is one, else nil
  1554. (defun py-goto-statement-at-or-above ()
  1555.   (py-goto-initial-line)
  1556.   (if (looking-at py-blank-or-comment-re)
  1557.     ;; skip back over blank & comment lines
  1558.     ;; note:  will skip a blank or comment line that happens to be
  1559.     ;; a continuation line too
  1560.     (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
  1561.         (progn (py-goto-initial-line) t)
  1562.       nil)
  1563.     t))
  1564.  
  1565. ;; go to start of first statement (not blank or comment or continuation
  1566. ;; line) following the statement containing point
  1567. ;; returns t if there is one, else nil
  1568. (defun py-goto-statement-below ()
  1569.   (beginning-of-line)
  1570.   (let ( (start (point)) )
  1571.     (py-goto-beyond-final-line)
  1572.     (while (and
  1573.         (looking-at py-blank-or-comment-re)
  1574.         (not (eobp)))
  1575.       (forward-line 1))
  1576.     (if (eobp)
  1577.     (progn (goto-char start) nil)
  1578.       t)))
  1579.  
  1580. ;; go to start of statement, at or preceding point, starting with keyword
  1581. ;; KEY.  Skips blank lines and non-indenting comments upward first.  If
  1582. ;; that statement starts with KEY, done, else go back to first enclosing
  1583. ;; block starting with KEY.
  1584. ;; If successful, leaves point at the start of the KEY line & returns t.
  1585. ;; Else leaves point at an undefined place & returns nil.
  1586. (defun py-go-up-tree-to-keyword (key)
  1587.   ;; skip blanks and non-indenting #
  1588.   (py-goto-initial-line)
  1589.   (while (and
  1590.       (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
  1591.       (zerop (forward-line -1)))    ; go back
  1592.     nil)
  1593.   (py-goto-initial-line)
  1594.   (let* ( (re (concat "[ \t]*" key "\\b"))
  1595.       (case-fold-search nil)    ; let* so looking-at sees this
  1596.       (found (looking-at re))
  1597.       (dead nil))
  1598.     (while (not (or found dead))
  1599.       (condition-case nil        ; in case no enclosing block
  1600.       (py-goto-block-up 'no-mark)
  1601.     (error (setq dead t)))
  1602.       (or dead (setq found (looking-at re))))
  1603.     (beginning-of-line)
  1604.     found))
  1605.  
  1606. ;; return string in buffer from start of indentation to end of line;
  1607. ;; prefix "..." if leading whitespace was skipped
  1608. (defun py-suck-up-leading-text ()
  1609.   (save-excursion
  1610.     (back-to-indentation)
  1611.     (concat
  1612.      (if (bolp) "" "...")
  1613.      (buffer-substring (point) (progn (end-of-line) (point))))))
  1614.  
  1615. ;; assuming point at bolp, return first keyword ([a-z]+) on the line,
  1616. ;; as a Lisp symbol; return nil if none
  1617. (defun py-suck-up-first-keyword ()
  1618.   (let ( (case-fold-search nil) )
  1619.     (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
  1620.     (intern (buffer-substring (match-beginning 1) (match-end 1)))
  1621.       nil)))
  1622.  
  1623. (defun py-make-temp-name ()
  1624.   (make-temp-name
  1625.    (concat (file-name-as-directory py-temp-directory) "python")))
  1626.  
  1627. (defun py-delete-file-silently (fname)
  1628.   (condition-case nil
  1629.       (delete-file fname)
  1630.     (error nil)))
  1631.  
  1632. (defun py-kill-emacs-hook ()
  1633.   ;; delete our temp files
  1634.   (while py-file-queue
  1635.     (py-delete-file-silently (car py-file-queue))
  1636.     (setq py-file-queue (cdr py-file-queue)))
  1637.   (if (not (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p))
  1638.       ;; run the hook we inherited, if any
  1639.       (and py-inherited-kill-emacs-hook
  1640.        (funcall py-inherited-kill-emacs-hook))))
  1641.  
  1642. ;; make PROCESS's buffer visible, append STRING to it, and force display;
  1643. ;; also make shell-mode believe the user typed this string, so that
  1644. ;; kill-output-from-shell and show-output-from-shell work "right"
  1645. (defun py-append-to-process-buffer (process string)
  1646.   (let ( (cbuf (current-buffer))
  1647.      (pbuf (process-buffer process))
  1648.      (py-scroll-process-buffer t))
  1649.     (set-buffer pbuf)
  1650.     (goto-char (point-max))
  1651.     (move-marker (process-mark process) (point))
  1652.     (if (not py-this-is-emacs-19-p)
  1653.     (move-marker last-input-start (point))) ; muck w/ shell-mode
  1654.     (funcall (process-filter process) process string)
  1655.     (if (not py-this-is-emacs-19-p)
  1656.     (move-marker last-input-end (point))) ; muck w/ shell-mode
  1657.     (set-buffer cbuf))
  1658.   (sit-for 0))
  1659.  
  1660. ;; To do:
  1661. ;; - support for ptags
  1662.