Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 1 | ;;; Major mode for editing Python programs, version 1.08ax |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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 py-this-is-emacs-19-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 | |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 197 | (defconst py-stringlit-re |
| 198 | (concat |
| 199 | "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted |
| 200 | "\\|" ; or |
| 201 | "\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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 |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 208 | "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*" |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 209 | "\\\\$") |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 210 | "regexp matching Python lines that are continued via backslash") |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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 |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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) |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 250 | (indent-region-function . py-indent-region) |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 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) |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 512 | (let ( (open-bracket-pos (py-nesting-level)) ) |
| 513 | (if open-bracket-pos |
| 514 | ;; line up with first real character (not whitespace or |
| 515 | ;; comment hash) after open bracket; if none, to one |
| 516 | ;; column beyond the open bracket |
| 517 | (progn |
| 518 | (goto-char (1+ open-bracket-pos)) ; just beyond bracket |
| 519 | (and (looking-at "[ \t]*[^ \t\n#]") |
| 520 | (goto-char (1- (match-end 0)))) |
| 521 | (current-column)) |
| 522 | ;; else on backslash continuation line |
Guido van Rossum | d3976e2 | 1994-04-13 19:01:12 +0000 | [diff] [blame] | 523 | (forward-line -1) |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 524 | (if (py-continuation-line-p) ; on at least 3rd line in block |
| 525 | (current-indentation) ; so just continue the pattern |
| 526 | ;; else started on 2nd line in block, so indent more; |
| 527 | ;; skip first chunk of non-whitespace characters on base |
| 528 | ;; line, + 1 more column |
| 529 | (back-to-indentation) |
| 530 | (skip-chars-forward "^ \t\n") |
| 531 | (1+ (current-column)))))) |
| 532 | |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 533 | ;; not on a continuation line |
| 534 | |
| 535 | ;; if at start of restriction, or on a non-indenting comment line, |
| 536 | ;; assume they intended whatever's there |
| 537 | ( (or (bobp) (looking-at "[ \t]*#[^ \t\n]")) |
| 538 | (current-indentation) ) |
| 539 | |
| 540 | ;; else indentation based on that of the statement that precedes |
| 541 | ;; us; use the first line of that statement to establish the base, |
| 542 | ;; in case the user forced a non-std indentation for the |
| 543 | ;; continuation lines (if any) |
| 544 | ( t |
| 545 | ;; skip back over blank & non-indenting comment lines |
| 546 | ;; note: will skip a blank or non-indenting comment line that |
| 547 | ;; happens to be a continuation line too |
| 548 | (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" |
| 549 | nil 'move) |
| 550 | (py-goto-initial-line) |
| 551 | (if (py-statement-opens-block-p) |
| 552 | (+ (current-indentation) py-indent-offset) |
| 553 | (current-indentation)))))) |
| 554 | |
| 555 | (defun py-guess-indent-offset (&optional global) |
| 556 | "Guess a good value for, and change, py-indent-offset. |
| 557 | By default (without a prefix arg), makes a buffer-local copy of |
| 558 | py-indent-offset with the new value. This will not affect any other |
| 559 | Python buffers. With a prefix arg, changes the global value of |
| 560 | py-indent-offset. This affects all Python buffers (that don't have |
| 561 | their own buffer-local copy), both those currently existing and those |
| 562 | created later in the Emacs session. |
| 563 | |
| 564 | Some people use a different value for py-indent-offset than you use. |
| 565 | There's no excuse for such foolishness, but sometimes you have to deal |
| 566 | with their ugly code anyway. This function examines the file and sets |
| 567 | py-indent-offset to what it thinks it was when they created the mess. |
| 568 | |
| 569 | Specifically, it searches forward from the statement containing point, |
| 570 | looking for a line that opens a block of code. py-indent-offset is set |
| 571 | to the difference in indentation between that line and the Python |
| 572 | statement following it. If the search doesn't succeed going forward, |
| 573 | it's tried again going backward." |
| 574 | (interactive "P") ; raw prefix arg |
| 575 | (let ( new-value |
| 576 | (start (point)) |
| 577 | restart |
| 578 | (found nil) |
| 579 | colon-indent) |
| 580 | (py-goto-initial-line) |
| 581 | (while (not (or found (eobp))) |
| 582 | (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) |
| 583 | (progn |
| 584 | (setq restart (point)) |
| 585 | (py-goto-initial-line) |
| 586 | (if (py-statement-opens-block-p) |
| 587 | (setq found t) |
| 588 | (goto-char restart))))) |
| 589 | (if found |
| 590 | () |
| 591 | (goto-char start) |
| 592 | (py-goto-initial-line) |
| 593 | (while (not (or found (bobp))) |
| 594 | (setq found |
| 595 | (and |
| 596 | (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) |
| 597 | (or (py-goto-initial-line) t) ; always true -- side effect |
| 598 | (py-statement-opens-block-p))))) |
| 599 | (setq colon-indent (current-indentation) |
| 600 | found (and found (zerop (py-next-statement 1))) |
| 601 | new-value (- (current-indentation) colon-indent)) |
| 602 | (goto-char start) |
| 603 | (if found |
| 604 | (progn |
| 605 | (funcall (if global 'kill-local-variable 'make-local-variable) |
| 606 | 'py-indent-offset) |
| 607 | (setq py-indent-offset new-value) |
| 608 | (message "%s value of py-indent-offset set to %d" |
| 609 | (if global "Global" "Local") |
| 610 | py-indent-offset)) |
| 611 | (error "Sorry, couldn't guess a value for py-indent-offset")))) |
| 612 | |
| 613 | (defun py-shift-region (start end count) |
| 614 | (save-excursion |
| 615 | (goto-char end) (beginning-of-line) (setq end (point)) |
| 616 | (goto-char start) (beginning-of-line) (setq start (point)) |
| 617 | (indent-rigidly start end count))) |
| 618 | |
| 619 | (defun py-shift-region-left (start end &optional count) |
| 620 | "Shift region of Python code to the left. |
| 621 | The lines from the line containing the start of the current region up |
| 622 | to (but not including) the line containing the end of the region are |
| 623 | shifted to the left, by py-indent-offset columns. |
| 624 | |
| 625 | If a prefix argument is given, the region is instead shifted by that |
| 626 | many columns." |
| 627 | (interactive "*r\nP") ; region; raw prefix arg |
| 628 | (py-shift-region start end |
| 629 | (- (prefix-numeric-value |
| 630 | (or count py-indent-offset))))) |
| 631 | |
| 632 | (defun py-shift-region-right (start end &optional count) |
| 633 | "Shift region of Python code to the right. |
| 634 | The lines from the line containing the start of the current region up |
| 635 | to (but not including) the line containing the end of the region are |
| 636 | shifted to the right, by py-indent-offset columns. |
| 637 | |
| 638 | If a prefix argument is given, the region is instead shifted by that |
| 639 | many columns." |
| 640 | (interactive "*r\nP") ; region; raw prefix arg |
| 641 | (py-shift-region start end (prefix-numeric-value |
| 642 | (or count py-indent-offset)))) |
| 643 | |
| 644 | (defun py-indent-region (start end &optional indent-offset) |
| 645 | "Reindent a region of Python code. |
| 646 | The lines from the line containing the start of the current region up |
| 647 | to (but not including) the line containing the end of the region are |
| 648 | reindented. If the first line of the region has a non-whitespace |
| 649 | character in the first column, the first line is left alone and the rest |
| 650 | of the region is reindented with respect to it. Else the entire region |
| 651 | is reindented with respect to the (closest code or indenting-comment) |
| 652 | statement immediately preceding the region. |
| 653 | |
| 654 | This is useful when code blocks are moved or yanked, when enclosing |
| 655 | control structures are introduced or removed, or to reformat code using |
| 656 | a new value for the indentation offset. |
| 657 | |
| 658 | If a numeric prefix argument is given, it will be used as the value of |
| 659 | the indentation offset. Else the value of py-indent-offset will be |
| 660 | used. |
| 661 | |
| 662 | Warning: The region must be consistently indented before this function |
| 663 | is called! This function does not compute proper indentation from |
| 664 | scratch (that's impossible in Python), it merely adjusts the existing |
| 665 | indentation to be correct in context. |
| 666 | |
| 667 | Warning: This function really has no idea what to do with non-indenting |
| 668 | comment lines, and shifts them as if they were indenting comment lines. |
| 669 | Fixing this appears to require telepathy. |
| 670 | |
| 671 | Special cases: whitespace is deleted from blank lines; continuation |
| 672 | lines are shifted by the same amount their initial line was shifted, in |
| 673 | order to preserve their relative indentation with respect to their |
| 674 | initial line; and comment lines beginning in column 1 are ignored." |
| 675 | |
| 676 | (interactive "*r\nP") ; region; raw prefix arg |
| 677 | (save-excursion |
| 678 | (goto-char end) (beginning-of-line) (setq end (point-marker)) |
| 679 | (goto-char start) (beginning-of-line) |
| 680 | (let ( (py-indent-offset (prefix-numeric-value |
| 681 | (or indent-offset py-indent-offset))) |
| 682 | (indents '(-1)) ; stack of active indent levels |
| 683 | (target-column 0) ; column to which to indent |
| 684 | (base-shifted-by 0) ; amount last base line was shifted |
| 685 | (indent-base (if (looking-at "[ \t\n]") |
| 686 | (py-compute-indentation) |
| 687 | 0)) |
| 688 | ci) |
| 689 | (while (< (point) end) |
| 690 | (setq ci (current-indentation)) |
| 691 | ;; figure out appropriate target column |
| 692 | (cond |
| 693 | ( (or (eq (following-char) ?#) ; comment in column 1 |
| 694 | (looking-at "[ \t]*$")) ; entirely blank |
| 695 | (setq target-column 0)) |
| 696 | ( (py-continuation-line-p) ; shift relative to base line |
| 697 | (setq target-column (+ ci base-shifted-by))) |
| 698 | (t ; new base line |
| 699 | (if (> ci (car indents)) ; going deeper; push it |
| 700 | (setq indents (cons ci indents)) |
| 701 | ;; else we should have seen this indent before |
| 702 | (setq indents (memq ci indents)) ; pop deeper indents |
| 703 | (if (null indents) |
| 704 | (error "Bad indentation in region, at line %d" |
| 705 | (save-restriction |
| 706 | (widen) |
| 707 | (1+ (count-lines 1 (point))))))) |
| 708 | (setq target-column (+ indent-base |
| 709 | (* py-indent-offset |
| 710 | (- (length indents) 2)))) |
| 711 | (setq base-shifted-by (- target-column ci)))) |
| 712 | ;; shift as needed |
| 713 | (if (/= ci target-column) |
| 714 | (progn |
| 715 | (delete-horizontal-space) |
| 716 | (indent-to target-column))) |
| 717 | (forward-line 1)))) |
| 718 | (set-marker end nil)) |
| 719 | |
| 720 | ;;; Functions for moving point |
| 721 | |
| 722 | (defun py-previous-statement (count) |
| 723 | "Go to the start of previous Python statement. |
| 724 | If the statement at point is the i'th Python statement, goes to the |
| 725 | start of statement i-COUNT. If there is no such statement, goes to the |
| 726 | first statement. Returns count of statements left to move. |
| 727 | `Statements' do not include blank, comment, or continuation lines." |
| 728 | (interactive "p") ; numeric prefix arg |
| 729 | (if (< count 0) (py-next-statement (- count)) |
| 730 | (py-goto-initial-line) |
| 731 | (let ( start ) |
| 732 | (while (and |
| 733 | (setq start (point)) ; always true -- side effect |
| 734 | (> count 0) |
| 735 | (zerop (forward-line -1)) |
| 736 | (py-goto-statement-at-or-above)) |
| 737 | (setq count (1- count))) |
| 738 | (if (> count 0) (goto-char start))) |
| 739 | count)) |
| 740 | |
| 741 | (defun py-next-statement (count) |
| 742 | "Go to the start of next Python statement. |
| 743 | If the statement at point is the i'th Python statement, goes to the |
| 744 | start of statement i+COUNT. If there is no such statement, goes to the |
| 745 | last statement. Returns count of statements left to move. `Statements' |
| 746 | do not include blank, comment, or continuation lines." |
| 747 | (interactive "p") ; numeric prefix arg |
| 748 | (if (< count 0) (py-previous-statement (- count)) |
| 749 | (beginning-of-line) |
| 750 | (let ( start ) |
| 751 | (while (and |
| 752 | (setq start (point)) ; always true -- side effect |
| 753 | (> count 0) |
| 754 | (py-goto-statement-below)) |
| 755 | (setq count (1- count))) |
| 756 | (if (> count 0) (goto-char start))) |
| 757 | count)) |
| 758 | |
| 759 | (defun py-goto-block-up (&optional nomark) |
| 760 | "Move up to start of current block. |
| 761 | Go to the statement that starts the smallest enclosing block; roughly |
| 762 | speaking, this will be the closest preceding statement that ends with a |
| 763 | colon and is indented less than the statement you started on. If |
| 764 | successful, also sets the mark to the starting point. |
| 765 | |
| 766 | `\\[py-mark-block]' can be used afterward to mark the whole code block, if desired. |
| 767 | |
| 768 | If called from a program, the mark will not be set if optional argument |
| 769 | NOMARK is not nil." |
| 770 | (interactive) |
| 771 | (let ( (start (point)) |
| 772 | (found nil) |
| 773 | initial-indent) |
| 774 | (py-goto-initial-line) |
| 775 | ;; if on blank or non-indenting comment line, use the preceding stmt |
| 776 | (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") |
| 777 | (progn |
| 778 | (py-goto-statement-at-or-above) |
| 779 | (setq found (py-statement-opens-block-p)))) |
| 780 | ;; search back for colon line indented less |
| 781 | (setq initial-indent (current-indentation)) |
| 782 | (if (zerop initial-indent) |
| 783 | ;; force fast exit |
| 784 | (goto-char (point-min))) |
| 785 | (while (not (or found (bobp))) |
| 786 | (setq found |
| 787 | (and |
| 788 | (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move) |
| 789 | (or (py-goto-initial-line) t) ; always true -- side effect |
| 790 | (< (current-indentation) initial-indent) |
| 791 | (py-statement-opens-block-p)))) |
| 792 | (if found |
| 793 | (progn |
| 794 | (or nomark (push-mark start)) |
| 795 | (back-to-indentation)) |
| 796 | (goto-char start) |
| 797 | (error "Enclosing block not found")))) |
| 798 | |
| 799 | (defun beginning-of-python-def-or-class (&optional class) |
| 800 | "Move point to start of def (or class, with prefix arg). |
| 801 | |
| 802 | Searches back for the closest preceding `def'. If you supply a prefix |
| 803 | arg, looks for a `class' instead. The docs assume the `def' case; just |
| 804 | substitute `class' for `def' for the other case. |
| 805 | |
| 806 | If point is in a def statement already, and after the `d', simply moves |
| 807 | point to the start of the statement. |
| 808 | |
| 809 | Else (point is not in a def statement, or at or before the `d' of a def |
| 810 | statement), searches for the closest preceding def statement, and leaves |
| 811 | point at its start. If no such statement can be found, leaves point at |
| 812 | the start of the buffer. |
| 813 | |
| 814 | Returns t iff a def statement is found by these rules. |
| 815 | |
| 816 | Note that doing this command repeatedly will take you closer to the start |
| 817 | of the buffer each time. |
| 818 | |
| 819 | If you want to mark the current def/class, see `\\[mark-python-def-or-class]'." |
| 820 | (interactive "P") ; raw prefix arg |
| 821 | (let ( (at-or-before-p (<= (current-column) (current-indentation))) |
| 822 | (start-of-line (progn (beginning-of-line) (point))) |
| 823 | (start-of-stmt (progn (py-goto-initial-line) (point)))) |
| 824 | (if (or (/= start-of-stmt start-of-line) |
| 825 | (not at-or-before-p)) |
| 826 | (end-of-line)) ; OK to match on this line |
| 827 | (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>") |
| 828 | nil 'move))) |
| 829 | |
| 830 | (defun end-of-python-def-or-class (&optional class) |
| 831 | "Move point beyond end of def (or class, with prefix arg) body. |
| 832 | |
| 833 | By default, looks for an appropriate `def'. If you supply a prefix arg, |
| 834 | looks for a `class' instead. The docs assume the `def' case; just |
| 835 | substitute `class' for `def' for the other case. |
| 836 | |
| 837 | If point is in a def statement already, this is the def we use. |
| 838 | |
| 839 | Else if the def found by `\\[beginning-of-python-def-or-class]' contains the statement you |
| 840 | started on, that's the def we use. |
| 841 | |
| 842 | Else we search forward for the closest following def, and use that. |
| 843 | |
| 844 | If a def can be found by these rules, point is moved to the start of the |
| 845 | line immediately following the def block, and the position of the start |
| 846 | of the def is returned. |
| 847 | |
| 848 | Else point is moved to the end of the buffer, and nil is returned. |
| 849 | |
| 850 | Note that doing this command repeatedly will take you closer to the end |
| 851 | of the buffer each time. |
| 852 | |
| 853 | If you want to mark the current def/class, see `\\[mark-python-def-or-class]'." |
| 854 | (interactive "P") ; raw prefix arg |
| 855 | (let ( (start (progn (py-goto-initial-line) (point))) |
| 856 | (which (if class "class" "def")) |
| 857 | (state 'not-found)) |
| 858 | ;; move point to start of appropriate def/class |
| 859 | (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one |
| 860 | (setq state 'at-beginning) |
| 861 | ;; else see if beginning-of-python-def-or-class hits container |
| 862 | (if (and (beginning-of-python-def-or-class class) |
| 863 | (progn (py-goto-beyond-block) |
| 864 | (> (point) start))) |
| 865 | (setq state 'at-end) |
| 866 | ;; else search forward |
| 867 | (goto-char start) |
| 868 | (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move) |
| 869 | (progn (setq state 'at-beginning) |
| 870 | (beginning-of-line))))) |
| 871 | (cond |
| 872 | ((eq state 'at-beginning) (py-goto-beyond-block) t) |
| 873 | ((eq state 'at-end) t) |
| 874 | ((eq state 'not-found) nil) |
| 875 | (t (error "internal error in end-of-python-def-or-class"))))) |
| 876 | |
| 877 | ;;; Functions for marking regions |
| 878 | |
| 879 | (defun py-mark-block (&optional extend just-move) |
| 880 | "Mark following block of lines. With prefix arg, mark structure. |
| 881 | Easier to use than explain. It sets the region to an `interesting' |
| 882 | block of succeeding lines. If point is on a blank line, it goes down to |
| 883 | the next non-blank line. That will be the start of the region. The end |
| 884 | of the region depends on the kind of line at the start: |
| 885 | |
| 886 | - If a comment, the region will include all succeeding comment lines up |
| 887 | to (but not including) the next non-comment line (if any). |
| 888 | |
| 889 | - Else if a prefix arg is given, and the line begins one of these |
| 890 | structures: |
| 891 | \tif elif else try except finally for while def class |
| 892 | the region will be set to the body of the structure, including |
| 893 | following blocks that `belong' to it, but excluding trailing blank |
| 894 | and comment lines. E.g., if on a `try' statement, the `try' block |
| 895 | and all (if any) of the following `except' and `finally' blocks that |
| 896 | belong to the `try' structure will be in the region. Ditto for |
| 897 | if/elif/else, for/else and while/else structures, and (a bit |
| 898 | degenerate, since they're always one-block structures) def and class |
| 899 | blocks. |
| 900 | |
| 901 | - Else if no prefix argument is given, and the line begins a Python |
| 902 | block (see list above), and the block is not a `one-liner' (i.e., the |
| 903 | statement ends with a colon, not with code), the region will include |
| 904 | all succeeding lines up to (but not including) the next code |
| 905 | statement (if any) that's indented no more than the starting line, |
| 906 | except that trailing blank and comment lines are excluded. E.g., if |
| 907 | the starting line begins a multi-statement `def' structure, the |
| 908 | region will be set to the full function definition, but without any |
| 909 | trailing `noise' lines. |
| 910 | |
| 911 | - Else the region will include all succeeding lines up to (but not |
| 912 | including) the next blank line, or code or indenting-comment line |
| 913 | indented strictly less than the starting line. Trailing indenting |
| 914 | comment lines are included in this case, but not trailing blank |
| 915 | lines. |
| 916 | |
| 917 | A msg identifying the location of the mark is displayed in the echo |
| 918 | area; or do `\\[exchange-point-and-mark]' to flip down to the end. |
| 919 | |
| 920 | If called from a program, optional argument EXTEND plays the role of the |
| 921 | prefix arg, and if optional argument JUST-MOVE is not nil, just moves to |
| 922 | the end of the block (& does not set mark or display a msg)." |
| 923 | |
| 924 | (interactive "P") ; raw prefix arg |
| 925 | (py-goto-initial-line) |
| 926 | ;; skip over blank lines |
| 927 | (while (and |
| 928 | (looking-at "[ \t]*$") ; while blank line |
| 929 | (not (eobp))) ; & somewhere to go |
| 930 | (forward-line 1)) |
| 931 | (if (eobp) |
| 932 | (error "Hit end of buffer without finding a non-blank stmt")) |
| 933 | (let ( (initial-pos (point)) |
| 934 | (initial-indent (current-indentation)) |
| 935 | last-pos ; position of last stmt in region |
| 936 | (followers |
| 937 | '( (if elif else) (elif elif else) (else) |
| 938 | (try except finally) (except except) (finally) |
| 939 | (for else) (while else) |
| 940 | (def) (class) ) ) |
| 941 | first-symbol next-symbol) |
| 942 | |
| 943 | (cond |
| 944 | ;; if comment line, suck up the following comment lines |
| 945 | ((looking-at "[ \t]*#") |
| 946 | (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment |
| 947 | (re-search-backward "^[ \t]*#") ; and back to last comment in block |
| 948 | (setq last-pos (point))) |
| 949 | |
| 950 | ;; else if line is a block line and EXTEND given, suck up |
| 951 | ;; the whole structure |
| 952 | ((and extend |
| 953 | (setq first-symbol (py-suck-up-first-keyword) ) |
| 954 | (assq first-symbol followers)) |
| 955 | (while (and |
| 956 | (or (py-goto-beyond-block) t) ; side effect |
| 957 | (forward-line -1) ; side effect |
| 958 | (setq last-pos (point)) ; side effect |
| 959 | (py-goto-statement-below) |
| 960 | (= (current-indentation) initial-indent) |
| 961 | (setq next-symbol (py-suck-up-first-keyword)) |
| 962 | (memq next-symbol (cdr (assq first-symbol followers)))) |
| 963 | (setq first-symbol next-symbol))) |
| 964 | |
| 965 | ;; else if line *opens* a block, search for next stmt indented <= |
| 966 | ((py-statement-opens-block-p) |
| 967 | (while (and |
| 968 | (setq last-pos (point)) ; always true -- side effect |
| 969 | (py-goto-statement-below) |
| 970 | (> (current-indentation) initial-indent)) |
| 971 | nil)) |
| 972 | |
| 973 | ;; else plain code line; stop at next blank line, or stmt or |
| 974 | ;; indenting comment line indented < |
| 975 | (t |
| 976 | (while (and |
| 977 | (setq last-pos (point)) ; always true -- side effect |
| 978 | (or (py-goto-beyond-final-line) t) |
| 979 | (not (looking-at "[ \t]*$")) ; stop at blank line |
| 980 | (or |
| 981 | (>= (current-indentation) initial-indent) |
| 982 | (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting # |
| 983 | nil))) |
| 984 | |
| 985 | ;; skip to end of last stmt |
| 986 | (goto-char last-pos) |
| 987 | (py-goto-beyond-final-line) |
| 988 | |
| 989 | ;; set mark & display |
| 990 | (if just-move |
| 991 | () ; just return |
| 992 | (push-mark (point) 'no-msg) |
| 993 | (forward-line -1) |
| 994 | (message "Mark set after: %s" (py-suck-up-leading-text)) |
| 995 | (goto-char initial-pos)))) |
| 996 | |
| 997 | (defun mark-python-def-or-class (&optional class) |
| 998 | "Set region to body of def (or class, with prefix arg) enclosing point. |
| 999 | Pushes the current mark, then point, on the mark ring (all language |
| 1000 | modes do this, but although it's handy it's never documented ...). |
| 1001 | |
| 1002 | In most Emacs language modes, this function bears at least a |
| 1003 | hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and `\\[beginning-of-python-def-or-class]'. |
| 1004 | |
| 1005 | And in earlier versions of Python mode, all 3 were tightly connected. |
| 1006 | Turned out that was more confusing than useful: the `goto start' and |
| 1007 | `goto end' commands are usually used to search through a file, and people |
| 1008 | expect them to act a lot like `search backward' and `search forward' |
| 1009 | string-search commands. But because Python `def' and `class' can nest to |
| 1010 | arbitrary levels, finding the smallest def containing point cannot be |
| 1011 | done via a simple backward search: the def containing point may not be |
| 1012 | the closest preceding def, or even the closest preceding def that's |
| 1013 | indented less. The fancy algorithm required is appropriate for the usual |
| 1014 | uses of this `mark' command, but not for the `goto' variations. |
| 1015 | |
| 1016 | So the def marked by this command may not be the one either of the `goto' |
| 1017 | commands find: If point is on a blank or non-indenting comment line, |
| 1018 | moves back to start of the closest preceding code statement or indenting |
| 1019 | comment line. If this is a `def' statement, that's the def we use. Else |
| 1020 | searches for the smallest enclosing `def' block and uses that. Else |
| 1021 | signals an error. |
| 1022 | |
| 1023 | When an enclosing def is found: The mark is left immediately beyond the |
| 1024 | last line of the def block. Point is left at the start of the def, |
| 1025 | except that: if the def is preceded by a number of comment lines |
| 1026 | followed by (at most) one optional blank line, point is left at the start |
| 1027 | of the comments; else if the def is preceded by a blank line, point is |
| 1028 | left at its start. |
| 1029 | |
| 1030 | The intent is to mark the containing def/class and its associated |
| 1031 | documentation, to make moving and duplicating functions and classes |
| 1032 | pleasant." |
| 1033 | (interactive "P") ; raw prefix arg |
| 1034 | (let ( (start (point)) |
| 1035 | (which (if class "class" "def"))) |
| 1036 | (push-mark start) |
| 1037 | (if (not (py-go-up-tree-to-keyword which)) |
| 1038 | (progn (goto-char start) |
| 1039 | (error "Enclosing %s not found" which)) |
| 1040 | ;; else enclosing def/class found |
| 1041 | (setq start (point)) |
| 1042 | (py-goto-beyond-block) |
| 1043 | (push-mark (point)) |
| 1044 | (goto-char start) |
| 1045 | (if (zerop (forward-line -1)) ; if there is a preceding line |
| 1046 | (progn |
| 1047 | (if (looking-at "[ \t]*$") ; it's blank |
| 1048 | (setq start (point)) ; so reset start point |
| 1049 | (goto-char start)) ; else try again |
| 1050 | (if (zerop (forward-line -1)) |
| 1051 | (if (looking-at "[ \t]*#") ; a comment |
| 1052 | ;; look back for non-comment line |
| 1053 | ;; tricky: note that the regexp matches a blank |
| 1054 | ;; line, cuz \n is in the 2nd character class |
| 1055 | (and |
| 1056 | (re-search-backward "^[ \t]*[^ \t#]" nil 'move) |
| 1057 | (forward-line 1)) |
| 1058 | ;; no comment, so go back |
| 1059 | (goto-char start)))))))) |
| 1060 | |
| 1061 | (defun py-comment-region (start end &optional uncomment-p) |
| 1062 | "Comment out region of code; with prefix arg, uncomment region. |
| 1063 | The lines from the line containing the start of the current region up |
| 1064 | to (but not including) the line containing the end of the region are |
| 1065 | commented out, by inserting the string py-block-comment-prefix at the |
| 1066 | start of each line. With a prefix arg, removes py-block-comment-prefix |
| 1067 | from the start of each line instead." |
| 1068 | (interactive "*r\nP") ; region; raw prefix arg |
| 1069 | (goto-char end) (beginning-of-line) (setq end (point)) |
| 1070 | (goto-char start) (beginning-of-line) (setq start (point)) |
| 1071 | (let ( (prefix-len (length py-block-comment-prefix)) ) |
| 1072 | (save-excursion |
| 1073 | (save-restriction |
| 1074 | (narrow-to-region start end) |
| 1075 | (while (not (eobp)) |
| 1076 | (if uncomment-p |
| 1077 | (and (string= py-block-comment-prefix |
| 1078 | (buffer-substring |
| 1079 | (point) (+ (point) prefix-len))) |
| 1080 | (delete-char prefix-len)) |
| 1081 | (insert py-block-comment-prefix)) |
| 1082 | (forward-line 1)))))) |
| 1083 | |
| 1084 | ;;; Documentation functions |
| 1085 | |
| 1086 | ;; dump the long form of the mode blurb; does the usual doc escapes, |
| 1087 | ;; plus lines of the form ^[vc]:name$ to suck variable & command |
| 1088 | ;; docs out of the right places, along with the keys they're on & |
| 1089 | ;; current values |
| 1090 | (defun py-dump-help-string (str) |
| 1091 | (with-output-to-temp-buffer "*Help*" |
| 1092 | (let ( (locals (buffer-local-variables)) |
| 1093 | funckind funcname func funcdoc |
| 1094 | (start 0) mstart end |
| 1095 | keys ) |
| 1096 | (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start) |
| 1097 | (setq mstart (match-beginning 0) end (match-end 0) |
| 1098 | funckind (substring str (match-beginning 1) (match-end 1)) |
| 1099 | funcname (substring str (match-beginning 2) (match-end 2)) |
| 1100 | func (intern funcname)) |
| 1101 | (princ (substitute-command-keys (substring str start mstart))) |
| 1102 | (cond |
| 1103 | ( (equal funckind "c") ; command |
| 1104 | (setq funcdoc (documentation func) |
| 1105 | keys (concat |
| 1106 | "Key(s): " |
| 1107 | (mapconcat 'key-description |
| 1108 | (where-is-internal func py-mode-map) |
| 1109 | ", ")))) |
| 1110 | ( (equal funckind "v") ; variable |
| 1111 | (setq funcdoc (substitute-command-keys |
| 1112 | (get func 'variable-documentation)) |
| 1113 | keys (if (assq func locals) |
| 1114 | (concat |
| 1115 | "Local/Global values: " |
| 1116 | (prin1-to-string (symbol-value func)) |
| 1117 | " / " |
| 1118 | (prin1-to-string (default-value func))) |
| 1119 | (concat |
| 1120 | "Value: " |
| 1121 | (prin1-to-string (symbol-value func)))))) |
| 1122 | ( t ; unexpected |
| 1123 | (error "Error in py-dump-help-string, tag `%s'" funckind))) |
| 1124 | (princ (format "\n-> %s:\t%s\t%s\n\n" |
| 1125 | (if (equal funckind "c") "Command" "Variable") |
| 1126 | funcname keys)) |
| 1127 | (princ funcdoc) |
| 1128 | (terpri) |
| 1129 | (setq start end)) |
| 1130 | (princ (substitute-command-keys (substring str start)))) |
| 1131 | (print-help-return-message))) |
| 1132 | |
| 1133 | (defun py-describe-mode () |
| 1134 | "Dump long form of Python-mode docs." |
| 1135 | (interactive) |
| 1136 | (py-dump-help-string "Major mode for editing Python files. |
| 1137 | Knows about Python indentation, tokens, comments and continuation lines. |
| 1138 | Paragraphs are separated by blank lines only. |
| 1139 | |
| 1140 | Major sections below begin with the string `@'; specific function and |
| 1141 | variable docs begin with `->'. |
| 1142 | |
| 1143 | @EXECUTING PYTHON CODE |
| 1144 | |
| 1145 | \\[py-execute-buffer]\tsends the entire buffer to the Python interpreter |
| 1146 | \\[py-execute-region]\tsends the current region |
| 1147 | \\[py-shell]\tstarts a Python interpreter window; this will be used by |
| 1148 | \tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands |
| 1149 | %c:py-execute-buffer |
| 1150 | %c:py-execute-region |
| 1151 | %c:py-shell |
| 1152 | |
| 1153 | @VARIABLES |
| 1154 | |
| 1155 | py-indent-offset\tindentation increment |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 1156 | py-block-comment-prefix\tcomment string used by py-comment-region |
| 1157 | |
| 1158 | py-python-command\tshell command to invoke Python interpreter |
| 1159 | py-scroll-process-buffer\talways scroll Python process buffer |
| 1160 | py-temp-directory\tdirectory used for temp files (if needed) |
| 1161 | |
| 1162 | py-beep-if-tab-change\tring the bell if tab-width is changed |
| 1163 | %v:py-indent-offset |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 1164 | %v:py-block-comment-prefix |
| 1165 | %v:py-python-command |
| 1166 | %v:py-scroll-process-buffer |
| 1167 | %v:py-temp-directory |
| 1168 | %v:py-beep-if-tab-change |
| 1169 | |
| 1170 | @KINDS OF LINES |
| 1171 | |
| 1172 | Each physical line in the file is either a `continuation line' (the |
| 1173 | preceding line ends with a backslash that's not part of a comment, or the |
| 1174 | paren/bracket/brace nesting level at the start of the line is non-zero, |
| 1175 | or both) or an `initial line' (everything else). |
| 1176 | |
| 1177 | An initial line is in turn a `blank line' (contains nothing except |
| 1178 | possibly blanks or tabs), a `comment line' (leftmost non-blank character |
| 1179 | is `#'), or a `code line' (everything else). |
| 1180 | |
| 1181 | Comment Lines |
| 1182 | |
| 1183 | Although all comment lines are treated alike by Python, Python mode |
| 1184 | recognizes two kinds that act differently with respect to indentation. |
| 1185 | |
| 1186 | An `indenting comment line' is a comment line with a blank, tab or |
| 1187 | nothing after the initial `#'. The indentation commands (see below) |
| 1188 | treat these exactly as if they were code lines: a line following an |
| 1189 | indenting comment line will be indented like the comment line. All |
| 1190 | other comment lines (those with a non-whitespace character immediately |
| 1191 | following the initial `#') are `non-indenting comment lines', and their |
| 1192 | indentation is ignored by the indentation commands. |
| 1193 | |
| 1194 | Indenting comment lines are by far the usual case, and should be used |
| 1195 | whenever possible. Non-indenting comment lines are useful in cases like |
| 1196 | these: |
| 1197 | |
| 1198 | \ta = b # a very wordy single-line comment that ends up being |
| 1199 | \t #... continued onto another line |
| 1200 | |
| 1201 | \tif a == b: |
| 1202 | ##\t\tprint 'panic!' # old code we've `commented out' |
| 1203 | \t\treturn a |
| 1204 | |
| 1205 | Since the `#...' and `##' comment lines have a non-whitespace character |
| 1206 | following the initial `#', Python mode ignores them when computing the |
| 1207 | proper indentation for the next line. |
| 1208 | |
| 1209 | Continuation Lines and Statements |
| 1210 | |
| 1211 | The Python-mode commands generally work on statements instead of on |
| 1212 | individual lines, where a `statement' is a comment or blank line, or a |
| 1213 | code line and all of its following continuation lines (if any) |
| 1214 | considered as a single logical unit. The commands in this mode |
| 1215 | generally (when it makes sense) automatically move to the start of the |
| 1216 | statement containing point, even if point happens to be in the middle of |
| 1217 | some continuation line. |
| 1218 | |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 1219 | |
| 1220 | @INDENTATION |
| 1221 | |
| 1222 | Primarily for entering new code: |
| 1223 | \t\\[indent-for-tab-command]\t indent line appropriately |
| 1224 | \t\\[py-newline-and-indent]\t insert newline, then indent |
| 1225 | \t\\[py-delete-char]\t reduce indentation, or delete single character |
| 1226 | |
| 1227 | Primarily for reindenting existing code: |
| 1228 | \t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally |
| 1229 | \t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally |
| 1230 | |
| 1231 | \t\\[py-indent-region]\t reindent region to match its context |
| 1232 | \t\\[py-shift-region-left]\t shift region left by py-indent-offset |
| 1233 | \t\\[py-shift-region-right]\t shift region right by py-indent-offset |
| 1234 | |
| 1235 | Unlike most programming languages, Python uses indentation, and only |
| 1236 | indentation, to specify block structure. Hence the indentation supplied |
| 1237 | automatically by Python-mode is just an educated guess: only you know |
| 1238 | the block structure you intend, so only you can supply correct |
| 1239 | indentation. |
| 1240 | |
| 1241 | The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on |
| 1242 | the indentation of preceding statements. E.g., assuming |
| 1243 | py-indent-offset is 4, after you enter |
| 1244 | \tif a > 0: \\[py-newline-and-indent] |
| 1245 | the cursor will be moved to the position of the `_' (_ is not a |
| 1246 | character in the file, it's just used here to indicate the location of |
| 1247 | the cursor): |
| 1248 | \tif a > 0: |
| 1249 | \t _ |
| 1250 | If you then enter `c = d' \\[py-newline-and-indent], the cursor will move |
| 1251 | to |
| 1252 | \tif a > 0: |
| 1253 | \t c = d |
| 1254 | \t _ |
| 1255 | Python-mode cannot know whether that's what you intended, or whether |
| 1256 | \tif a > 0: |
| 1257 | \t c = d |
| 1258 | \t_ |
| 1259 | was your intent. In general, Python-mode either reproduces the |
| 1260 | indentation of the (closest code or indenting-comment) preceding |
| 1261 | statement, or adds an extra py-indent-offset blanks if the preceding |
| 1262 | statement has `:' as its last significant (non-whitespace and non- |
| 1263 | comment) character. If the suggested indentation is too much, use |
| 1264 | \\[py-delete-char] to reduce it. |
| 1265 | |
Guido van Rossum | e531e4b | 1994-04-16 08:29:27 +0000 | [diff] [blame] | 1266 | Continuation lines are given extra indentation. If a line is a |
| 1267 | continuation line by virtue of being in an unclosed paren/bracket/ |
| 1268 | brace structure, it's indented to line up with the first non-whitespace |
| 1269 | and non-comment character following the opening paren/bracket/brace |
| 1270 | of the smallest such enclosing structure. If no such character exists, |
| 1271 | it's indented to one column beyond the opening paren/bracket/brace. |
| 1272 | |
| 1273 | If a line is a continuation line because the line preceding it ends with |
| 1274 | a backslash, the third and following lines of the continuation block |
| 1275 | inherit their indentation from the line preceding them, while the second |
| 1276 | line in the block is indented to one column beyond the first chunk of |
| 1277 | non-whitespace characters in the block's initial line. |
| 1278 | |
Guido van Rossum | a7925f1 | 1994-01-26 10:20:16 +0000 | [diff] [blame] | 1279 | Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command] |
| 1280 | repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block |
| 1281 | structure you intend. |
| 1282 | %c:indent-for-tab-command |
| 1283 | %c:py-newline-and-indent |
| 1284 | %c:py-delete-char |
| 1285 | |
| 1286 | |
| 1287 | The next function may be handy when editing code you didn't write: |
| 1288 | %c:py-guess-indent-offset |
| 1289 | |
| 1290 | |
| 1291 | The remaining `indent' functions apply to a region of Python code. They |
| 1292 | assume the block structure (equals indentation, in Python) of the region |
| 1293 | is correct, and alter the indentation in various ways while preserving |
| 1294 | the block structure: |
| 1295 | %c:py-indent-region |
| 1296 | %c:py-shift-region-left |
| 1297 | %c:py-shift-region-right |
| 1298 | |
| 1299 | @MARKING & MANIPULATING REGIONS OF CODE |
| 1300 | |
| 1301 | \\[py-mark-block]\t mark block of lines |
| 1302 | \\[mark-python-def-or-class]\t mark smallest enclosing def |
| 1303 | \\[universal-argument] \\[mark-python-def-or-class]\t mark smallest enclosing class |
| 1304 | \\[py-comment-region]\t comment out region of code |
| 1305 | \\[universal-argument] \\[py-comment-region]\t uncomment region of code |
| 1306 | %c:py-mark-block |
| 1307 | %c:mark-python-def-or-class |
| 1308 | %c:py-comment-region |
| 1309 | |
| 1310 | @MOVING POINT |
| 1311 | |
| 1312 | \\[py-previous-statement]\t move to statement preceding point |
| 1313 | \\[py-next-statement]\t move to statement following point |
| 1314 | \\[py-goto-block-up]\t move up to start of current block |
| 1315 | \\[beginning-of-python-def-or-class]\t move to start of def |
| 1316 | \\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class |
| 1317 | \\[end-of-python-def-or-class]\t move to end of def |
| 1318 | \\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class |
| 1319 | |
| 1320 | The first two move to one statement beyond the statement that contains |
| 1321 | point. A numeric prefix argument tells them to move that many |
| 1322 | statements instead. Blank lines, comment lines, and continuation lines |
| 1323 | do not count as `statements' for these commands. So, e.g., you can go |
| 1324 | to the first code statement in a file by entering |
| 1325 | \t\\[beginning-of-buffer]\t to move to the top of the file |
| 1326 | \t\\[py-next-statement]\t to skip over initial comments and blank lines |
| 1327 | Or do `\\[py-previous-statement]' with a huge prefix argument. |
| 1328 | %c:py-previous-statement |
| 1329 | %c:py-next-statement |
| 1330 | %c:py-goto-block-up |
| 1331 | %c:beginning-of-python-def-or-class |
| 1332 | %c:end-of-python-def-or-class |
| 1333 | |
| 1334 | @LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE |
| 1335 | |
| 1336 | `\\[indent-new-comment-line]' is handy for entering a multi-line comment. |
| 1337 | |
| 1338 | `\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the |
| 1339 | overall class and def structure of a module. |
| 1340 | |
| 1341 | `\\[back-to-indentation]' moves point to a line's first non-blank character. |
| 1342 | |
| 1343 | `\\[indent-relative]' is handy for creating odd indentation. |
| 1344 | |
| 1345 | @OTHER EMACS HINTS |
| 1346 | |
| 1347 | If you don't like the default value of a variable, change its value to |
| 1348 | whatever you do like by putting a `setq' line in your .emacs file. |
| 1349 | E.g., to set the indentation increment to 4, put this line in your |
| 1350 | .emacs: |
| 1351 | \t(setq py-indent-offset 4) |
| 1352 | To see the value of a variable, do `\\[describe-variable]' and enter the variable |
| 1353 | name at the prompt. |
| 1354 | |
| 1355 | When entering a key sequence like `C-c C-n', it is not necessary to |
| 1356 | release the CONTROL key after doing the `C-c' part -- it suffices to |
| 1357 | press the CONTROL key, press and release `c' (while still holding down |
| 1358 | CONTROL), press and release `n' (while still holding down CONTROL), & |
| 1359 | then release CONTROL. |
| 1360 | |
| 1361 | Entering Python mode calls with no arguments the value of the variable |
| 1362 | `py-mode-hook', if that value exists and is not nil; see the `Hooks' |
| 1363 | section of the Elisp manual for details. |
| 1364 | |
| 1365 | Obscure: When python-mode is first loaded, it looks for all bindings |
| 1366 | to newline-and-indent in the global keymap, and shadows them with |
| 1367 | local bindings to py-newline-and-indent.")) |
| 1368 | |
| 1369 | ;;; Helper functions |
| 1370 | |
| 1371 | (defvar py-parse-state-re |
| 1372 | (concat |
| 1373 | "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>" |
| 1374 | "\\|" |
| 1375 | "^[^ #\t\n]")) |
| 1376 | ;; returns the parse state at point (see parse-partial-sexp docs) |
| 1377 | (defun py-parse-state () |
| 1378 | (save-excursion |
| 1379 | (let ( (here (point)) ) |
| 1380 | ;; back up to the first preceding line (if any; else start of |
| 1381 | ;; buffer) that begins with a popular Python keyword, or a non- |
| 1382 | ;; whitespace and non-comment character. These are good places to |
| 1383 | ;; start parsing to see whether where we started is at a non-zero |
| 1384 | ;; nesting level. It may be slow for people who write huge code |
| 1385 | ;; blocks or huge lists ... tough beans. |
| 1386 | (re-search-backward py-parse-state-re nil 'move) |
| 1387 | (beginning-of-line) |
| 1388 | (parse-partial-sexp (point) here)))) |
| 1389 | |
| 1390 | ;; if point is at a non-zero nesting level, returns the number of the |
| 1391 | ;; character that opens the smallest enclosing unclosed list; else |
| 1392 | ;; returns nil. |
| 1393 | (defun py-nesting-level () |
| 1394 | (let ( (status (py-parse-state)) ) |
| 1395 | (if (zerop (car status)) |
| 1396 | nil ; not in a nest |
| 1397 | (car (cdr status))))) ; char# of open bracket |
| 1398 | |
| 1399 | ;; t iff preceding line ends with backslash that's not in a comment |
| 1400 | (defun py-backslash-continuation-line-p () |
| 1401 | (save-excursion |
| 1402 | (beginning-of-line) |
| 1403 | (and |
| 1404 | ;; use a cheap test first to avoid the regexp if possible |
| 1405 | ;; use 'eq' because char-after may return nil |
| 1406 | (eq (char-after (- (point) 2)) ?\\ ) |
| 1407 | ;; make sure; since eq test passed, there is a preceding line |
| 1408 | (forward-line -1) ; always true -- side effect |
| 1409 | (looking-at py-continued-re)))) |
| 1410 | |
| 1411 | ;; t iff current line is a continuation line |
| 1412 | (defun py-continuation-line-p () |
| 1413 | (save-excursion |
| 1414 | (beginning-of-line) |
| 1415 | (or (py-backslash-continuation-line-p) |
| 1416 | (py-nesting-level)))) |
| 1417 | |
| 1418 | ;; go to initial line of current statement; usually this is the |
| 1419 | ;; line we're on, but if we're on the 2nd or following lines of a |
| 1420 | ;; continuation block, we need to go up to the first line of the block. |
| 1421 | ;; |
| 1422 | ;; Tricky: We want to avoid quadratic-time behavior for long continued |
| 1423 | ;; blocks, whether of the backslash or open-bracket varieties, or a mix |
| 1424 | ;; of the two. The following manages to do that in the usual cases. |
| 1425 | (defun py-goto-initial-line () |
| 1426 | (let ( open-bracket-pos ) |
| 1427 | (while (py-continuation-line-p) |
| 1428 | (beginning-of-line) |
| 1429 | (if (py-backslash-continuation-line-p) |
| 1430 | (while (py-backslash-continuation-line-p) |
| 1431 | (forward-line -1)) |
| 1432 | ;; else zip out of nested brackets/braces/parens |
| 1433 | (while (setq open-bracket-pos (py-nesting-level)) |
| 1434 | (goto-char open-bracket-pos))))) |
| 1435 | (beginning-of-line)) |
| 1436 | |
| 1437 | ;; go to point right beyond final line of current statement; usually |
| 1438 | ;; this is the start of the next line, but if this is a multi-line |
| 1439 | ;; statement we need to skip over the continuation lines. |
| 1440 | ;; Tricky: Again we need to be clever to avoid quadratic time behavior. |
| 1441 | (defun py-goto-beyond-final-line () |
| 1442 | (forward-line 1) |
| 1443 | (let ( state ) |
| 1444 | (while (and (py-continuation-line-p) |
| 1445 | (not (eobp))) |
| 1446 | ;; skip over the backslash flavor |
| 1447 | (while (and (py-backslash-continuation-line-p) |
| 1448 | (not (eobp))) |
| 1449 | (forward-line 1)) |
| 1450 | ;; if in nest, zip to the end of the nest |
| 1451 | (setq state (py-parse-state)) |
| 1452 | (if (and (not (zerop (car state))) |
| 1453 | (not (eobp))) |
| 1454 | (progn |
| 1455 | ;; BUG ALERT: I could swear, from reading the docs, that |
| 1456 | ;; the 3rd argument should be plain 0 |
| 1457 | (parse-partial-sexp (point) (point-max) (- 0 (car state)) |
| 1458 | nil state) |
| 1459 | (forward-line 1)))))) |
| 1460 | |
| 1461 | ;; t iff statement opens a block == iff it ends with a colon that's |
| 1462 | ;; not in a comment |
| 1463 | ;; point should be at the start of a statement |
| 1464 | (defun py-statement-opens-block-p () |
| 1465 | (save-excursion |
| 1466 | (let ( (start (point)) |
| 1467 | (finish (progn (py-goto-beyond-final-line) (1- (point)))) |
| 1468 | (searching t) |
| 1469 | (answer nil) |
| 1470 | state) |
| 1471 | (goto-char start) |
| 1472 | (while searching |
| 1473 | ;; look for a colon with nothing after it except whitespace, and |
| 1474 | ;; maybe a comment |
| 1475 | (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$" |
| 1476 | finish t) |
| 1477 | (if (eq (point) finish) ; note: no `else' clause; just |
| 1478 | ; keep searching if we're not at |
| 1479 | ; the end yet |
| 1480 | ;; sure looks like it opens a block -- but it might |
| 1481 | ;; be in a comment |
| 1482 | (progn |
| 1483 | (setq searching nil) ; search is done either way |
| 1484 | (setq state (parse-partial-sexp start |
| 1485 | (match-beginning 0))) |
| 1486 | (setq answer (not (nth 4 state))))) |
| 1487 | ;; search failed: couldn't find another interesting colon |
| 1488 | (setq searching nil))) |
| 1489 | answer))) |
| 1490 | |
| 1491 | ;; go to point right beyond final line of block begun by the current |
| 1492 | ;; line. This is the same as where py-goto-beyond-final-line goes |
| 1493 | ;; unless we're on colon line, in which case we go to the end of the |
| 1494 | ;; block. |
| 1495 | ;; assumes point is at bolp |
| 1496 | (defun py-goto-beyond-block () |
| 1497 | (if (py-statement-opens-block-p) |
| 1498 | (py-mark-block nil 'just-move) |
| 1499 | (py-goto-beyond-final-line))) |
| 1500 | |
| 1501 | ;; go to start of first statement (not blank or comment or continuation |
| 1502 | ;; line) at or preceding point |
| 1503 | ;; returns t if there is one, else nil |
| 1504 | (defun py-goto-statement-at-or-above () |
| 1505 | (py-goto-initial-line) |
| 1506 | (if (looking-at py-blank-or-comment-re) |
| 1507 | ;; skip back over blank & comment lines |
| 1508 | ;; note: will skip a blank or comment line that happens to be |
| 1509 | ;; a continuation line too |
| 1510 | (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t) |
| 1511 | (progn (py-goto-initial-line) t) |
| 1512 | nil) |
| 1513 | t)) |
| 1514 | |
| 1515 | ;; go to start of first statement (not blank or comment or continuation |
| 1516 | ;; line) following the statement containing point |
| 1517 | ;; returns t if there is one, else nil |
| 1518 | (defun py-goto-statement-below () |
| 1519 | (beginning-of-line) |
| 1520 | (let ( (start (point)) ) |
| 1521 | (py-goto-beyond-final-line) |
| 1522 | (while (and |
| 1523 | (looking-at py-blank-or-comment-re) |
| 1524 | (not (eobp))) |
| 1525 | (forward-line 1)) |
| 1526 | (if (eobp) |
| 1527 | (progn (goto-char start) nil) |
| 1528 | t))) |
| 1529 | |
| 1530 | ;; go to start of statement, at or preceding point, starting with keyword |
| 1531 | ;; KEY. Skips blank lines and non-indenting comments upward first. If |
| 1532 | ;; that statement starts with KEY, done, else go back to first enclosing |
| 1533 | ;; block starting with KEY. |
| 1534 | ;; If successful, leaves point at the start of the KEY line & returns t. |
| 1535 | ;; Else leaves point at an undefined place & returns nil. |
| 1536 | (defun py-go-up-tree-to-keyword (key) |
| 1537 | ;; skip blanks and non-indenting # |
| 1538 | (py-goto-initial-line) |
| 1539 | (while (and |
| 1540 | (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)") |
| 1541 | (zerop (forward-line -1))) ; go back |
| 1542 | nil) |
| 1543 | (py-goto-initial-line) |
| 1544 | (let* ( (re (concat "[ \t]*" key "\\b")) |
| 1545 | (case-fold-search nil) ; let* so looking-at sees this |
| 1546 | (found (looking-at re)) |
| 1547 | (dead nil)) |
| 1548 | (while (not (or found dead)) |
| 1549 | (condition-case nil ; in case no enclosing block |
| 1550 | (py-goto-block-up 'no-mark) |
| 1551 | (error (setq dead t))) |
| 1552 | (or dead (setq found (looking-at re)))) |
| 1553 | (beginning-of-line) |
| 1554 | found)) |
| 1555 | |
| 1556 | ;; return string in buffer from start of indentation to end of line; |
| 1557 | ;; prefix "..." if leading whitespace was skipped |
| 1558 | (defun py-suck-up-leading-text () |
| 1559 | (save-excursion |
| 1560 | (back-to-indentation) |
| 1561 | (concat |
| 1562 | (if (bolp) "" "...") |
| 1563 | (buffer-substring (point) (progn (end-of-line) (point)))))) |
| 1564 | |
| 1565 | ;; assuming point at bolp, return first keyword ([a-z]+) on the line, |
| 1566 | ;; as a Lisp symbol; return nil if none |
| 1567 | (defun py-suck-up-first-keyword () |
| 1568 | (let ( (case-fold-search nil) ) |
| 1569 | (if (looking-at "[ \t]*\\([a-z]+\\)\\b") |
| 1570 | (intern (buffer-substring (match-beginning 1) (match-end 1))) |
| 1571 | nil))) |
| 1572 | |
| 1573 | (defun py-make-temp-name () |
| 1574 | (make-temp-name |
| 1575 | (concat (file-name-as-directory py-temp-directory) "python"))) |
| 1576 | |
| 1577 | (defun py-delete-file-silently (fname) |
| 1578 | (condition-case nil |
| 1579 | (delete-file fname) |
| 1580 | (error nil))) |
| 1581 | |
| 1582 | (defun py-kill-emacs-hook () |
| 1583 | ;; delete our temp files |
| 1584 | (while py-file-queue |
| 1585 | (py-delete-file-silently (car py-file-queue)) |
| 1586 | (setq py-file-queue (cdr py-file-queue))) |
| 1587 | (if (not py-this-is-emacs-19-p) |
| 1588 | ;; run the hook we inherited, if any |
| 1589 | (and py-inherited-kill-emacs-hook |
| 1590 | (funcall py-inherited-kill-emacs-hook)))) |
| 1591 | |
| 1592 | ;; make PROCESS's buffer visible, append STRING to it, and force display; |
| 1593 | ;; also make shell-mode believe the user typed this string, so that |
| 1594 | ;; kill-output-from-shell and show-output-from-shell work "right" |
| 1595 | (defun py-append-to-process-buffer (process string) |
| 1596 | (let ( (cbuf (current-buffer)) |
| 1597 | (pbuf (process-buffer process)) |
| 1598 | (py-scroll-process-buffer t)) |
| 1599 | (set-buffer pbuf) |
| 1600 | (goto-char (point-max)) |
| 1601 | (move-marker (process-mark process) (point)) |
| 1602 | (if (not py-this-is-emacs-19-p) |
| 1603 | (move-marker last-input-start (point))) ; muck w/ shell-mode |
| 1604 | (funcall (process-filter process) process string) |
| 1605 | (if (not py-this-is-emacs-19-p) |
| 1606 | (move-marker last-input-end (point))) ; muck w/ shell-mode |
| 1607 | (set-buffer cbuf)) |
| 1608 | (sit-for 0)) |
| 1609 | |
| 1610 | ;; To do: |
| 1611 | ;; - support for ptags |