PageRenderTime 75ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Misc/python-mode.el

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