/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

Large files are truncated click here to view the full file

  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…