python.el 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732
  1. ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
  2. ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
  3. ;; Author: Dave Love <fx@gnu.org>
  4. ;; Maintainer: FSF
  5. ;; Created: Nov 2003
  6. ;; Keywords: languages
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Major mode for editing Python, with support for inferior processes.
  20. ;; There is another Python mode, python-mode.el:
  21. ;; http://launchpad.net/python-mode
  22. ;; used by XEmacs, and originally maintained with Python.
  23. ;; That isn't covered by an FSF copyright assignment (?), unlike this
  24. ;; code, and seems not to be well-maintained for Emacs (though I've
  25. ;; submitted fixes). This mode is rather simpler and is better in
  26. ;; other ways. In particular, using the syntax functions with text
  27. ;; properties maintained by font-lock makes it more correct with
  28. ;; arbitrary string and comment contents.
  29. ;; This doesn't implement all the facilities of python-mode.el. Some
  30. ;; just need doing, e.g. catching exceptions in the inferior Python
  31. ;; buffer (but see M-x pdb for debugging). [Actually, the use of
  32. ;; `compilation-shell-minor-mode' now is probably enough for that.]
  33. ;; Others don't seem appropriate. For instance,
  34. ;; `forward-into-nomenclature' should be done separately, since it's
  35. ;; not specific to Python, and I've installed a minor mode to do the
  36. ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
  37. ;; feature, `subword-mode' which is intended to have a similar
  38. ;; effect, but actually only affects word-oriented keybindings.]
  39. ;; Other things seem more natural or canonical here, e.g. the
  40. ;; {beginning,end}-of-defun implementation dealing with nested
  41. ;; definitions, and the inferior mode following `cmuscheme'. (The
  42. ;; inferior mode can find the source of errors from
  43. ;; `python-send-region' & al via `compilation-shell-minor-mode'.)
  44. ;; There is (limited) symbol completion using lookup in Python and
  45. ;; Eldoc support also using the inferior process. Successive TABs
  46. ;; cycle between possible indentations for the line.
  47. ;; Even where it has similar facilities, this mode is incompatible
  48. ;; with python-mode.el in some respects. For instance, various key
  49. ;; bindings are changed to obey Emacs conventions.
  50. ;; TODO: See various Fixmes below.
  51. ;; Fixme: This doesn't support (the nascent) Python 3 .
  52. ;;; Code:
  53. (require 'comint)
  54. (require 'ansi-color)
  55. (eval-when-compile
  56. (require 'compile)
  57. (require 'hippie-exp))
  58. (autoload 'comint-mode "comint")
  59. (defgroup python nil
  60. "Silly walks in the Python language."
  61. :group 'languages
  62. :version "22.1"
  63. :link '(emacs-commentary-link "python"))
  64. ;;;###autoload
  65. (add-to-list 'interpreter-mode-alist (cons (purecopy "jython") 'jython-mode))
  66. ;;;###autoload
  67. (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
  68. ;;;###autoload
  69. (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
  70. ;;;; Font lock
  71. (defvar python-font-lock-keywords
  72. `(,(rx symbol-start
  73. ;; From v 2.7 reference, § keywords.
  74. ;; def and class dealt with separately below
  75. (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
  76. "except" "exec" "finally" "for" "from" "global" "if"
  77. "import" "in" "is" "lambda" "not" "or" "pass" "print"
  78. "raise" "return" "try" "while" "with" "yield"
  79. ;; Not real keywords, but close enough to be fontified as such
  80. "self" "True" "False"
  81. ;; Python 3
  82. "nonlocal")
  83. symbol-end)
  84. (,(rx symbol-start "None" symbol-end) ; see § Keywords in 2.7 manual
  85. . font-lock-constant-face)
  86. ;; Definitions
  87. (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
  88. (1 font-lock-keyword-face) (2 font-lock-type-face))
  89. (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
  90. (1 font-lock-keyword-face) (2 font-lock-function-name-face))
  91. ;; Top-level assignments are worth highlighting.
  92. (,(rx line-start (group (1+ (or word ?_))) (0+ space)
  93. (opt (or "+" "-" "*" "**" "/" "//" "&" "%" "|" "^" "<<" ">>")) "=")
  94. (1 font-lock-variable-name-face))
  95. ;; Decorators.
  96. (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
  97. (0+ "." (1+ (or word ?_)))))
  98. (1 font-lock-type-face))
  99. ;; Built-ins. (The next three blocks are from
  100. ;; `__builtin__.__dict__.keys()' in Python 2.7) These patterns
  101. ;; are debatable, but they at least help to spot possible
  102. ;; shadowing of builtins.
  103. (,(rx symbol-start (or
  104. ;; exceptions
  105. "ArithmeticError" "AssertionError" "AttributeError"
  106. "BaseException" "DeprecationWarning" "EOFError"
  107. "EnvironmentError" "Exception" "FloatingPointError"
  108. "FutureWarning" "GeneratorExit" "IOError" "ImportError"
  109. "ImportWarning" "IndentationError" "IndexError" "KeyError"
  110. "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
  111. "NotImplemented" "NotImplementedError" "OSError"
  112. "OverflowError" "PendingDeprecationWarning" "ReferenceError"
  113. "RuntimeError" "RuntimeWarning" "StandardError"
  114. "StopIteration" "SyntaxError" "SyntaxWarning" "SystemError"
  115. "SystemExit" "TabError" "TypeError" "UnboundLocalError"
  116. "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
  117. "UnicodeTranslateError" "UnicodeWarning" "UserWarning"
  118. "ValueError" "Warning" "ZeroDivisionError"
  119. ;; Python 2.7
  120. "BufferError" "BytesWarning" "WindowsError") symbol-end)
  121. . font-lock-type-face)
  122. (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
  123. (group (or
  124. ;; callable built-ins, fontified when not appearing as
  125. ;; object attributes
  126. "abs" "all" "any" "apply" "basestring" "bool" "buffer" "callable"
  127. "chr" "classmethod" "cmp" "coerce" "compile" "complex"
  128. "copyright" "credits" "delattr" "dict" "dir" "divmod"
  129. "enumerate" "eval" "execfile" "exit" "file" "filter" "float"
  130. "frozenset" "getattr" "globals" "hasattr" "hash" "help"
  131. "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
  132. "iter" "len" "license" "list" "locals" "long" "map" "max"
  133. "min" "object" "oct" "open" "ord" "pow" "property" "quit"
  134. "range" "raw_input" "reduce" "reload" "repr" "reversed"
  135. "round" "set" "setattr" "slice" "sorted" "staticmethod"
  136. "str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars"
  137. "xrange" "zip"
  138. ;; Python 2.7.
  139. "bin" "bytearray" "bytes" "format" "memoryview" "next" "print"
  140. )) symbol-end)
  141. (1 font-lock-builtin-face))
  142. (,(rx symbol-start (or
  143. ;; other built-ins
  144. "True" "False" "None" "Ellipsis"
  145. "_" "__debug__" "__doc__" "__import__" "__name__" "__package__")
  146. symbol-end)
  147. . font-lock-builtin-face)))
  148. (defconst python-syntax-propertize-function
  149. ;; Make outer chars of matching triple-quote sequences into generic
  150. ;; string delimiters. Fixme: Is there a better way?
  151. ;; First avoid a sequence preceded by an odd number of backslashes.
  152. (syntax-propertize-rules
  153. (;; ¡Backrefs don't work in syntax-propertize-rules!
  154. (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
  155. "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
  156. (3 (ignore (python-quote-syntax))))
  157. ;; This doesn't really help.
  158. ;;((rx (and ?\\ (group ?\n))) (1 " "))
  159. ))
  160. (defun python-quote-syntax ()
  161. "Put `syntax-table' property correctly on triple quote.
  162. Used for syntactic keywords. N is the match number (1, 2 or 3)."
  163. ;; Given a triple quote, we have to check the context to know
  164. ;; whether this is an opening or closing triple or whether it's
  165. ;; quoted anyhow, and should be ignored. (For that we need to do
  166. ;; the same job as `syntax-ppss' to be correct and it seems to be OK
  167. ;; to use it here despite initial worries.) We also have to sort
  168. ;; out a possible prefix -- well, we don't _have_ to, but I think it
  169. ;; should be treated as part of the string.
  170. ;; Test cases:
  171. ;; ur"""ar""" x='"' # """
  172. ;; x = ''' """ ' a
  173. ;; '''
  174. ;; x '"""' x """ \"""" x
  175. (save-excursion
  176. (goto-char (match-beginning 0))
  177. (let ((syntax (save-match-data (syntax-ppss))))
  178. (cond
  179. ((eq t (nth 3 syntax)) ; after unclosed fence
  180. ;; Consider property for the last char if in a fenced string.
  181. (goto-char (nth 8 syntax)) ; fence position
  182. (skip-chars-forward "uUrR") ; skip any prefix
  183. ;; Is it a matching sequence?
  184. (if (eq (char-after) (char-after (match-beginning 2)))
  185. (put-text-property (match-beginning 3) (match-end 3)
  186. 'syntax-table (string-to-syntax "|"))))
  187. ((match-end 1)
  188. ;; Consider property for initial char, accounting for prefixes.
  189. (put-text-property (match-beginning 1) (match-end 1)
  190. 'syntax-table (string-to-syntax "|")))
  191. (t
  192. ;; Consider property for initial char, accounting for prefixes.
  193. (put-text-property (match-beginning 2) (match-end 2)
  194. 'syntax-table (string-to-syntax "|"))))
  195. )))
  196. ;; This isn't currently in `font-lock-defaults' as probably not worth
  197. ;; it -- we basically only mess with a few normally-symbol characters.
  198. ;; (defun python-font-lock-syntactic-face-function (state)
  199. ;; "`font-lock-syntactic-face-function' for Python mode.
  200. ;; Returns the string or comment face as usual, with side effect of putting
  201. ;; a `syntax-table' property on the inside of the string or comment which is
  202. ;; the standard syntax table."
  203. ;; (if (nth 3 state)
  204. ;; (save-excursion
  205. ;; (goto-char (nth 8 state))
  206. ;; (condition-case nil
  207. ;; (forward-sexp)
  208. ;; (error nil))
  209. ;; (put-text-property (1+ (nth 8 state)) (1- (point))
  210. ;; 'syntax-table (standard-syntax-table))
  211. ;; 'font-lock-string-face)
  212. ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
  213. ;; 'syntax-table (standard-syntax-table))
  214. ;; 'font-lock-comment-face))
  215. ;;;; Keymap and syntax
  216. (defvar python-mode-map
  217. (let ((map (make-sparse-keymap)))
  218. ;; Mostly taken from python-mode.el.
  219. (define-key map ":" 'python-electric-colon)
  220. (define-key map "\177" 'python-backspace)
  221. (define-key map "\C-c<" 'python-shift-left)
  222. (define-key map "\C-c>" 'python-shift-right)
  223. (define-key map "\C-c\C-k" 'python-mark-block)
  224. (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking)
  225. (define-key map "\C-c\C-n" 'python-next-statement)
  226. (define-key map "\C-c\C-p" 'python-previous-statement)
  227. (define-key map "\C-c\C-u" 'python-beginning-of-block)
  228. (define-key map "\C-c\C-f" 'python-describe-symbol)
  229. (define-key map "\C-c\C-w" 'python-check)
  230. (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
  231. (define-key map "\C-c\C-s" 'python-send-string)
  232. (define-key map [?\C-\M-x] 'python-send-defun)
  233. (define-key map "\C-c\C-r" 'python-send-region)
  234. (define-key map "\C-c\M-r" 'python-send-region-and-go)
  235. (define-key map "\C-c\C-c" 'python-send-buffer)
  236. (define-key map "\C-c\C-z" 'python-switch-to-python)
  237. (define-key map "\C-c\C-m" 'python-load-file)
  238. (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
  239. (substitute-key-definition 'complete-symbol 'completion-at-point
  240. map global-map)
  241. (define-key map "\C-c\C-i" 'python-find-imports)
  242. (define-key map "\C-c\C-t" 'python-expand-template)
  243. (easy-menu-define python-menu map "Python Mode menu"
  244. `("Python"
  245. :help "Python-specific Features"
  246. ["Shift region left" python-shift-left :active mark-active
  247. :help "Shift by a single indentation step"]
  248. ["Shift region right" python-shift-right :active mark-active
  249. :help "Shift by a single indentation step"]
  250. "-"
  251. ["Mark block" python-mark-block
  252. :help "Mark innermost block around point"]
  253. ["Mark def/class" mark-defun
  254. :help "Mark innermost definition around point"]
  255. "-"
  256. ["Start of block" python-beginning-of-block
  257. :help "Go to start of innermost definition around point"]
  258. ["End of block" python-end-of-block
  259. :help "Go to end of innermost definition around point"]
  260. ["Start of def/class" beginning-of-defun
  261. :help "Go to start of innermost definition around point"]
  262. ["End of def/class" end-of-defun
  263. :help "Go to end of innermost definition around point"]
  264. "-"
  265. ("Templates..."
  266. :help "Expand templates for compound statements"
  267. :filter (lambda (&rest junk)
  268. (abbrev-table-menu python-mode-abbrev-table)))
  269. "-"
  270. ["Start interpreter" run-python
  271. :help "Run `inferior' Python in separate buffer"]
  272. ["Import/reload file" python-load-file
  273. :help "Load into inferior Python session"]
  274. ["Eval buffer" python-send-buffer
  275. :help "Evaluate buffer en bloc in inferior Python session"]
  276. ["Eval region" python-send-region :active mark-active
  277. :help "Evaluate region en bloc in inferior Python session"]
  278. ["Eval def/class" python-send-defun
  279. :help "Evaluate current definition in inferior Python session"]
  280. ["Switch to interpreter" python-switch-to-python
  281. :help "Switch to inferior Python buffer"]
  282. ["Set default process" python-set-proc
  283. :help "Make buffer's inferior process the default"
  284. :active (buffer-live-p python-buffer)]
  285. ["Check file" python-check :help "Run pychecker"]
  286. ["Debugger" pdb :help "Run pdb under GUD"]
  287. "-"
  288. ["Help on symbol" python-describe-symbol
  289. :help "Use pydoc on symbol at point"]
  290. ["Complete symbol" completion-at-point
  291. :help "Complete (qualified) symbol before point"]
  292. ["Find function" python-find-function
  293. :help "Try to find source definition of function at point"]
  294. ["Update imports" python-find-imports
  295. :help "Update list of top-level imports for completion"]))
  296. map))
  297. ;; Fixme: add toolbar stuff for useful things like symbol help, send
  298. ;; region, at least. (Shouldn't be specific to Python, obviously.)
  299. ;; eric has items including: (un)indent, (un)comment, restart script,
  300. ;; run script, debug script; also things for profiling, unit testing.
  301. (defvar python-mode-syntax-table
  302. (let ((table (make-syntax-table)))
  303. ;; Give punctuation syntax to ASCII that normally has symbol
  304. ;; syntax or has word syntax and isn't a letter.
  305. (let ((symbol (string-to-syntax "_"))
  306. (sst (standard-syntax-table)))
  307. (dotimes (i 128)
  308. (unless (= i ?_)
  309. (if (equal symbol (aref sst i))
  310. (modify-syntax-entry i "." table)))))
  311. (modify-syntax-entry ?$ "." table)
  312. (modify-syntax-entry ?% "." table)
  313. ;; exceptions
  314. (modify-syntax-entry ?# "<" table)
  315. (modify-syntax-entry ?\n ">" table)
  316. (modify-syntax-entry ?' "\"" table)
  317. (modify-syntax-entry ?` "$" table)
  318. table))
  319. ;;;; Utility stuff
  320. (defsubst python-in-string/comment ()
  321. "Return non-nil if point is in a Python literal (a comment or string)."
  322. ;; We don't need to save the match data.
  323. (nth 8 (syntax-ppss)))
  324. (defconst python-space-backslash-table
  325. (let ((table (copy-syntax-table python-mode-syntax-table)))
  326. (modify-syntax-entry ?\\ " " table)
  327. table)
  328. "`python-mode-syntax-table' with backslash given whitespace syntax.")
  329. (defun python-skip-comments/blanks (&optional backward)
  330. "Skip comments and blank lines.
  331. BACKWARD non-nil means go backwards, otherwise go forwards.
  332. Backslash is treated as whitespace so that continued blank lines
  333. are skipped. Doesn't move out of comments -- should be outside
  334. or at end of line."
  335. (let ((arg (if backward
  336. ;; If we're in a comment (including on the trailing
  337. ;; newline), forward-comment doesn't move backwards out
  338. ;; of it. Don't set the syntax table round this bit!
  339. (let ((syntax (syntax-ppss)))
  340. (if (nth 4 syntax)
  341. (goto-char (nth 8 syntax)))
  342. (- (point-max)))
  343. (point-max))))
  344. (with-syntax-table python-space-backslash-table
  345. (forward-comment arg))))
  346. (defun python-backslash-continuation-line-p ()
  347. "Non-nil if preceding line ends with backslash that is not in a comment."
  348. (and (eq ?\\ (char-before (line-end-position 0)))
  349. (not (syntax-ppss-context (syntax-ppss)))))
  350. (defun python-continuation-line-p ()
  351. "Return non-nil if current line continues a previous one.
  352. The criteria are that the previous line ends in a backslash outside
  353. comments and strings, or that point is within brackets/parens."
  354. (or (python-backslash-continuation-line-p)
  355. (let ((depth (syntax-ppss-depth
  356. (save-excursion ; syntax-ppss with arg changes point
  357. (syntax-ppss (line-beginning-position))))))
  358. (or (> depth 0)
  359. (if (< depth 0) ; Unbalanced brackets -- act locally
  360. (save-excursion
  361. (condition-case ()
  362. (progn (backward-up-list) t) ; actually within brackets
  363. (error nil))))))))
  364. (defun python-comment-line-p ()
  365. "Return non-nil if and only if current line has only a comment."
  366. (save-excursion
  367. (end-of-line)
  368. (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
  369. (back-to-indentation)
  370. (looking-at (rx (or (syntax comment-start) line-end))))))
  371. (defun python-blank-line-p ()
  372. "Return non-nil if and only if current line is blank."
  373. (save-excursion
  374. (beginning-of-line)
  375. (looking-at "\\s-*$")))
  376. (defun python-beginning-of-string ()
  377. "Go to beginning of string around point.
  378. Do nothing if not in string."
  379. (let ((state (syntax-ppss)))
  380. (when (eq 'string (syntax-ppss-context state))
  381. (goto-char (nth 8 state)))))
  382. (defun python-open-block-statement-p (&optional bos)
  383. "Return non-nil if statement at point opens a block.
  384. BOS non-nil means point is known to be at beginning of statement."
  385. (save-excursion
  386. (unless bos (python-beginning-of-statement))
  387. (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
  388. "class" "try" "except" "finally" "with")
  389. symbol-end)))))
  390. (defun python-close-block-statement-p (&optional bos)
  391. "Return non-nil if current line is a statement closing a block.
  392. BOS non-nil means point is at beginning of statement.
  393. The criteria are that the line isn't a comment or in string and
  394. starts with keyword `raise', `break', `continue' or `pass'."
  395. (save-excursion
  396. (unless bos (python-beginning-of-statement))
  397. (back-to-indentation)
  398. (looking-at (rx (or "return" "raise" "break" "continue" "pass")
  399. symbol-end))))
  400. (defun python-outdent-p ()
  401. "Return non-nil if current line should outdent a level."
  402. (save-excursion
  403. (back-to-indentation)
  404. (and (looking-at (rx (and (or "else" "finally" "except" "elif")
  405. symbol-end)))
  406. (not (python-in-string/comment))
  407. ;; Ensure there's a previous statement and move to it.
  408. (zerop (python-previous-statement))
  409. (not (python-close-block-statement-p t))
  410. ;; Fixme: check this
  411. (not (python-open-block-statement-p)))))
  412. ;;;; Indentation.
  413. (defcustom python-indent 4
  414. "Number of columns for a unit of indentation in Python mode.
  415. See also `\\[python-guess-indent]'"
  416. :group 'python
  417. :type 'integer)
  418. (put 'python-indent 'safe-local-variable 'integerp)
  419. (defcustom python-guess-indent t
  420. "Non-nil means Python mode guesses `python-indent' for the buffer."
  421. :type 'boolean
  422. :group 'python)
  423. (defcustom python-indent-string-contents t
  424. "Non-nil means indent contents of multi-line strings together.
  425. This means indent them the same as the preceding non-blank line.
  426. Otherwise preserve their indentation.
  427. This only applies to `doc' strings, i.e. those that form statements;
  428. the indentation is preserved in others."
  429. :type '(choice (const :tag "Align with preceding" t)
  430. (const :tag "Preserve indentation" nil))
  431. :group 'python)
  432. (defcustom python-honour-comment-indentation nil
  433. "Non-nil means indent relative to preceding comment line.
  434. Only do this for comments where the leading comment character is
  435. followed by space. This doesn't apply to comment lines, which
  436. are always indented in lines with preceding comments."
  437. :type 'boolean
  438. :group 'python)
  439. (defcustom python-continuation-offset 4
  440. "Number of columns of additional indentation for continuation lines.
  441. Continuation lines follow a backslash-terminated line starting a
  442. statement."
  443. :group 'python
  444. :type 'integer)
  445. (defcustom python-pdbtrack-do-tracking-p t
  446. "*Controls whether the pdbtrack feature is enabled or not.
  447. When non-nil, pdbtrack is enabled in all comint-based buffers,
  448. e.g. shell interaction buffers and the *Python* buffer.
  449. When using pdb to debug a Python program, pdbtrack notices the
  450. pdb prompt and presents the line in the source file where the
  451. program is stopped in a pop-up buffer. It's similar to what
  452. gud-mode does for debugging C programs with gdb, but without
  453. having to restart the program."
  454. :type 'boolean
  455. :group 'python)
  456. (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
  457. (defcustom python-pdbtrack-minor-mode-string " PDB"
  458. "*Minor-mode sign to be displayed when pdbtrack is active."
  459. :type 'string
  460. :group 'python)
  461. ;; Add a designator to the minor mode strings
  462. (or (assq 'python-pdbtrack-is-tracking-p minor-mode-alist)
  463. (push '(python-pdbtrack-is-tracking-p python-pdbtrack-minor-mode-string)
  464. minor-mode-alist))
  465. (defcustom python-shell-prompt-alist
  466. '(("ipython" . "^In \\[[0-9]+\\]: *")
  467. (t . "^>>> "))
  468. "Alist of Python input prompts.
  469. Each element has the form (PROGRAM . REGEXP), where PROGRAM is
  470. the value of `python-python-command' for the python process and
  471. REGEXP is a regular expression matching the Python prompt.
  472. PROGRAM can also be t, which specifies the default when no other
  473. element matches `python-python-command'."
  474. :type 'string
  475. :group 'python
  476. :version "24.1")
  477. (defcustom python-shell-continuation-prompt-alist
  478. '(("ipython" . "^ [.][.][.]+: *")
  479. (t . "^[.][.][.] "))
  480. "Alist of Python continued-line prompts.
  481. Each element has the form (PROGRAM . REGEXP), where PROGRAM is
  482. the value of `python-python-command' for the python process and
  483. REGEXP is a regular expression matching the Python prompt for
  484. continued lines.
  485. PROGRAM can also be t, which specifies the default when no other
  486. element matches `python-python-command'."
  487. :type 'string
  488. :group 'python
  489. :version "24.1")
  490. (defvar python-pdbtrack-is-tracking-p nil)
  491. (defconst python-pdbtrack-stack-entry-regexp
  492. "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
  493. "Regular expression pdbtrack uses to find a stack trace entry.")
  494. (defconst python-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]db[>)]+ "
  495. "Regular expression pdbtrack uses to recognize a pdb prompt.")
  496. (defconst python-pdbtrack-track-range 10000
  497. "Max number of characters from end of buffer to search for stack entry.")
  498. (defun python-guess-indent ()
  499. "Guess step for indentation of current buffer.
  500. Set `python-indent' locally to the value guessed."
  501. (interactive)
  502. (save-excursion
  503. (save-restriction
  504. (widen)
  505. (goto-char (point-min))
  506. (let (done indent)
  507. (while (and (not done) (not (eobp)))
  508. (when (and (re-search-forward (rx ?: (0+ space)
  509. (or (syntax comment-start)
  510. line-end))
  511. nil 'move)
  512. (python-open-block-statement-p))
  513. (save-excursion
  514. (python-beginning-of-statement)
  515. (let ((initial (current-indentation)))
  516. (if (zerop (python-next-statement))
  517. (setq indent (- (current-indentation) initial)))
  518. (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
  519. (setq done t))))))
  520. (when done
  521. (when (/= indent (default-value 'python-indent))
  522. (set (make-local-variable 'python-indent) indent)
  523. (unless (= tab-width python-indent)
  524. (setq indent-tabs-mode nil)))
  525. indent)))))
  526. ;; Alist of possible indentations and start of statement they would
  527. ;; close. Used in indentation cycling (below).
  528. (defvar python-indent-list nil
  529. "Internal use.")
  530. ;; Length of the above
  531. (defvar python-indent-list-length nil
  532. "Internal use.")
  533. ;; Current index into the alist.
  534. (defvar python-indent-index nil
  535. "Internal use.")
  536. (defun python-calculate-indentation ()
  537. "Calculate Python indentation for line at point."
  538. (setq python-indent-list nil
  539. python-indent-list-length 1)
  540. (save-excursion
  541. (beginning-of-line)
  542. (let ((syntax (syntax-ppss))
  543. start)
  544. (cond
  545. ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
  546. (if (not python-indent-string-contents)
  547. (current-indentation)
  548. ;; Only respect `python-indent-string-contents' in doc
  549. ;; strings (defined as those which form statements).
  550. (if (not (save-excursion
  551. (python-beginning-of-statement)
  552. (looking-at (rx (or (syntax string-delimiter)
  553. (syntax string-quote))))))
  554. (current-indentation)
  555. ;; Find indentation of preceding non-blank line within string.
  556. (setq start (nth 8 syntax))
  557. (forward-line -1)
  558. (while (and (< start (point)) (looking-at "\\s-*$"))
  559. (forward-line -1))
  560. (current-indentation))))
  561. ((python-continuation-line-p) ; after backslash, or bracketed
  562. (let ((point (point))
  563. (open-start (cadr syntax))
  564. (backslash (python-backslash-continuation-line-p))
  565. (colon (eq ?: (char-before (1- (line-beginning-position))))))
  566. (if open-start
  567. ;; Inside bracketed expression.
  568. (progn
  569. (goto-char (1+ open-start))
  570. ;; Look for first item in list (preceding point) and
  571. ;; align with it, if found.
  572. (if (with-syntax-table python-space-backslash-table
  573. (let ((parse-sexp-ignore-comments t))
  574. (condition-case ()
  575. (progn (forward-sexp)
  576. (backward-sexp)
  577. (< (point) point))
  578. (error nil))))
  579. ;; Extra level if we're backslash-continued or
  580. ;; following a key.
  581. (if (or backslash colon)
  582. (+ python-indent (current-column))
  583. (current-column))
  584. ;; Otherwise indent relative to statement start, one
  585. ;; level per bracketing level.
  586. (goto-char (1+ open-start))
  587. (python-beginning-of-statement)
  588. (+ (current-indentation) (* (car syntax) python-indent))))
  589. ;; Otherwise backslash-continued.
  590. (forward-line -1)
  591. (if (python-continuation-line-p)
  592. ;; We're past first continuation line. Align with
  593. ;; previous line.
  594. (current-indentation)
  595. ;; First continuation line. Indent one step, with an
  596. ;; extra one if statement opens a block.
  597. (python-beginning-of-statement)
  598. (+ (current-indentation) python-continuation-offset
  599. (if (python-open-block-statement-p t)
  600. python-indent
  601. 0))))))
  602. ((bobp) 0)
  603. ;; Fixme: Like python-mode.el; not convinced by this.
  604. ((looking-at (rx (0+ space) (syntax comment-start)
  605. (not (any " \t\n")))) ; non-indentable comment
  606. (current-indentation))
  607. ((and python-honour-comment-indentation
  608. ;; Back over whitespace, newlines, non-indentable comments.
  609. (catch 'done
  610. (while (cond ((bobp) nil)
  611. ((not (forward-comment -1))
  612. nil) ; not at comment start
  613. ;; Now at start of comment -- trailing one?
  614. ((/= (current-column) (current-indentation))
  615. nil)
  616. ;; Indentable comment, like python-mode.el?
  617. ((and (looking-at (rx (syntax comment-start)
  618. (or space line-end)))
  619. (/= 0 (current-column)))
  620. (throw 'done (current-column)))
  621. ;; Else skip it (loop).
  622. (t))))))
  623. (t
  624. (python-indentation-levels)
  625. ;; Prefer to indent comments with an immediately-following
  626. ;; statement, e.g.
  627. ;; ...
  628. ;; # ...
  629. ;; def ...
  630. (when (and (> python-indent-list-length 1)
  631. (python-comment-line-p))
  632. (forward-line)
  633. (unless (python-comment-line-p)
  634. (let ((elt (assq (current-indentation) python-indent-list)))
  635. (setq python-indent-list
  636. (nconc (delete elt python-indent-list)
  637. (list elt))))))
  638. (caar (last python-indent-list)))))))
  639. ;;;; Cycling through the possible indentations with successive TABs.
  640. ;; These don't need to be buffer-local since they're only relevant
  641. ;; during a cycle.
  642. (defun python-initial-text ()
  643. "Text of line following indentation and ignoring any trailing comment."
  644. (save-excursion
  645. (buffer-substring (progn
  646. (back-to-indentation)
  647. (point))
  648. (progn
  649. (end-of-line)
  650. (forward-comment -1)
  651. (point)))))
  652. (defconst python-block-pairs
  653. '(("else" "if" "elif" "while" "for" "try" "except")
  654. ("elif" "if" "elif")
  655. ("except" "try" "except")
  656. ("finally" "else" "try" "except"))
  657. "Alist of keyword matches.
  658. The car of an element is a keyword introducing a statement which
  659. can close a block opened by a keyword in the cdr.")
  660. (defun python-first-word ()
  661. "Return first word (actually symbol) on the line."
  662. (save-excursion
  663. (back-to-indentation)
  664. (current-word t)))
  665. (defun python-indentation-levels ()
  666. "Return a list of possible indentations for this line.
  667. It is assumed not to be a continuation line or in a multi-line string.
  668. Includes the default indentation and those which would close all
  669. enclosing blocks. Elements of the list are actually pairs:
  670. \(INDENTATION . TEXT), where TEXT is the initial text of the
  671. corresponding block opening (or nil)."
  672. (save-excursion
  673. (let ((initial "")
  674. levels indent)
  675. ;; Only one possibility immediately following a block open
  676. ;; statement, assuming it doesn't have a `suite' on the same line.
  677. (cond
  678. ((save-excursion (and (python-previous-statement)
  679. (python-open-block-statement-p t)
  680. (setq indent (current-indentation))
  681. ;; Check we don't have something like:
  682. ;; if ...: ...
  683. (if (progn (python-end-of-statement)
  684. (python-skip-comments/blanks t)
  685. (eq ?: (char-before)))
  686. (setq indent (+ python-indent indent)))))
  687. (push (cons indent initial) levels))
  688. ;; Only one possibility for comment line immediately following
  689. ;; another.
  690. ((save-excursion
  691. (when (python-comment-line-p)
  692. (forward-line -1)
  693. (if (python-comment-line-p)
  694. (push (cons (current-indentation) initial) levels)))))
  695. ;; Fixme: Maybe have a case here which indents (only) first
  696. ;; line after a lambda.
  697. (t
  698. (let ((start (car (assoc (python-first-word) python-block-pairs))))
  699. (python-previous-statement)
  700. ;; Is this a valid indentation for the line of interest?
  701. (unless (or (if start ; potentially only outdentable
  702. ;; Check for things like:
  703. ;; if ...: ...
  704. ;; else ...:
  705. ;; where the second line need not be outdented.
  706. (not (member (python-first-word)
  707. (cdr (assoc start
  708. python-block-pairs)))))
  709. ;; Not sensible to indent to the same level as
  710. ;; previous `return' &c.
  711. (python-close-block-statement-p))
  712. (push (cons (current-indentation) (python-initial-text))
  713. levels))
  714. (while (python-beginning-of-block)
  715. (when (or (not start)
  716. (member (python-first-word)
  717. (cdr (assoc start python-block-pairs))))
  718. (push (cons (current-indentation) (python-initial-text))
  719. levels))))))
  720. (prog1 (or levels (setq levels '((0 . ""))))
  721. (setq python-indent-list levels
  722. python-indent-list-length (length python-indent-list))))))
  723. ;; This is basically what `python-indent-line' would be if we didn't
  724. ;; do the cycling.
  725. (defun python-indent-line-1 (&optional leave)
  726. "Subroutine of `python-indent-line'.
  727. Does non-repeated indentation. LEAVE non-nil means leave
  728. indentation if it is valid, i.e. one of the positions returned by
  729. `python-calculate-indentation'."
  730. (let ((target (python-calculate-indentation))
  731. (pos (- (point-max) (point))))
  732. (if (or (= target (current-indentation))
  733. ;; Maybe keep a valid indentation.
  734. (and leave python-indent-list
  735. (assq (current-indentation) python-indent-list)))
  736. (if (< (current-column) (current-indentation))
  737. (back-to-indentation))
  738. (beginning-of-line)
  739. (delete-horizontal-space)
  740. (indent-to target)
  741. (if (> (- (point-max) pos) (point))
  742. (goto-char (- (point-max) pos))))))
  743. (defun python-indent-line ()
  744. "Indent current line as Python code.
  745. When invoked via `indent-for-tab-command', cycle through possible
  746. indentations for current line. The cycle is broken by a command
  747. different from `indent-for-tab-command', i.e. successive TABs do
  748. the cycling."
  749. (interactive)
  750. (if (and (eq this-command 'indent-for-tab-command)
  751. (eq last-command this-command))
  752. (if (= 1 python-indent-list-length)
  753. (message "Sole indentation")
  754. (progn (setq python-indent-index
  755. (% (1+ python-indent-index) python-indent-list-length))
  756. (beginning-of-line)
  757. (delete-horizontal-space)
  758. (indent-to (car (nth python-indent-index python-indent-list)))
  759. (if (python-block-end-p)
  760. (let ((text (cdr (nth python-indent-index
  761. python-indent-list))))
  762. (if text
  763. (message "Closes: %s" text))))))
  764. (python-indent-line-1)
  765. (setq python-indent-index (1- python-indent-list-length))))
  766. (defun python-indent-region (start end)
  767. "`indent-region-function' for Python.
  768. Leaves validly-indented lines alone, i.e. doesn't indent to
  769. another valid position."
  770. (save-excursion
  771. (goto-char end)
  772. (setq end (point-marker))
  773. (goto-char start)
  774. (or (bolp) (forward-line 1))
  775. (while (< (point) end)
  776. (or (and (bolp) (eolp))
  777. (python-indent-line-1 t))
  778. (forward-line 1))
  779. (move-marker end nil)))
  780. (defun python-block-end-p ()
  781. "Non-nil if this is a line in a statement closing a block,
  782. or a blank line indented to where it would close a block."
  783. (and (not (python-comment-line-p))
  784. (or (python-close-block-statement-p t)
  785. (< (current-indentation)
  786. (save-excursion
  787. (python-previous-statement)
  788. (current-indentation))))))
  789. ;;;; Movement.
  790. ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
  791. ;; block, statement, depending on context.
  792. (defun python-beginning-of-defun ()
  793. "`beginning-of-defun-function' for Python.
  794. Finds beginning of innermost nested class or method definition.
  795. Returns the name of the definition found at the end, or nil if
  796. reached start of buffer."
  797. (let ((ci (current-indentation))
  798. (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
  799. (group (1+ (or word (syntax symbol))))))
  800. found lep) ;; def-line
  801. (if (python-comment-line-p)
  802. (setq ci most-positive-fixnum))
  803. (while (and (not (bobp)) (not found))
  804. ;; Treat bol at beginning of function as outside function so
  805. ;; that successive C-M-a makes progress backwards.
  806. ;;(setq def-line (looking-at def-re))
  807. (unless (bolp) (end-of-line))
  808. (setq lep (line-end-position))
  809. (if (and (re-search-backward def-re nil 'move)
  810. ;; Must be less indented or matching top level, or
  811. ;; equally indented if we started on a definition line.
  812. (let ((in (current-indentation)))
  813. (or (and (zerop ci) (zerop in))
  814. (= lep (line-end-position)) ; on initial line
  815. ;; Not sure why it was like this -- fails in case of
  816. ;; last internal function followed by first
  817. ;; non-def statement of the main body.
  818. ;; (and def-line (= in ci))
  819. (= in ci)
  820. (< in ci)))
  821. (not (python-in-string/comment)))
  822. (setq found t)))
  823. found))
  824. (defun python-end-of-defun ()
  825. "`end-of-defun-function' for Python.
  826. Finds end of innermost nested class or method definition."
  827. (let ((orig (point))
  828. (pattern (rx line-start (0+ space) (or "def" "class") space)))
  829. ;; Go to start of current block and check whether it's at top
  830. ;; level. If it is, and not a block start, look forward for
  831. ;; definition statement.
  832. (when (python-comment-line-p)
  833. (end-of-line)
  834. (forward-comment most-positive-fixnum))
  835. (if (not (python-open-block-statement-p))
  836. (python-beginning-of-block))
  837. (if (zerop (current-indentation))
  838. (unless (python-open-block-statement-p)
  839. (while (and (re-search-forward pattern nil 'move)
  840. (python-in-string/comment))) ; just loop
  841. (unless (eobp)
  842. (beginning-of-line)))
  843. ;; Don't move before top-level statement that would end defun.
  844. (end-of-line)
  845. (python-beginning-of-defun))
  846. ;; If we got to the start of buffer, look forward for
  847. ;; definition statement.
  848. (if (and (bobp) (not (looking-at "def\\|class")))
  849. (while (and (not (eobp))
  850. (re-search-forward pattern nil 'move)
  851. (python-in-string/comment)))) ; just loop
  852. ;; We're at a definition statement (or end-of-buffer).
  853. (unless (eobp)
  854. (python-end-of-block)
  855. ;; Count trailing space in defun (but not trailing comments).
  856. (skip-syntax-forward " >")
  857. (unless (eobp) ; e.g. missing final newline
  858. (beginning-of-line)))
  859. ;; Catch pathological cases like this, where the beginning-of-defun
  860. ;; skips to a definition we're not in:
  861. ;; if ...:
  862. ;; ...
  863. ;; else:
  864. ;; ... # point here
  865. ;; ...
  866. ;; def ...
  867. (if (< (point) orig)
  868. (goto-char (point-max)))))
  869. (defun python-beginning-of-statement ()
  870. "Go to start of current statement.
  871. Accounts for continuation lines, multi-line strings, and
  872. multi-line bracketed expressions."
  873. (while
  874. (if (python-backslash-continuation-line-p)
  875. (progn (forward-line -1) t)
  876. (beginning-of-line)
  877. (or (python-beginning-of-string)
  878. (python-skip-out))))
  879. (back-to-indentation))
  880. (defun python-skip-out (&optional forward syntax)
  881. "Skip out of any nested brackets.
  882. Skip forward if FORWARD is non-nil, else backward.
  883. If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
  884. Return non-nil if and only if skipping was done."
  885. ;; FIXME: Use syntax-ppss-toplevel-pos.
  886. (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
  887. (forward (if forward -1 1)))
  888. (unless (zerop depth)
  889. (if (> depth 0)
  890. ;; Skip forward out of nested brackets.
  891. (condition-case () ; beware invalid syntax
  892. (progn (backward-up-list (* forward depth)) t)
  893. (error nil))
  894. ;; Invalid syntax (too many closed brackets).
  895. ;; Skip out of as many as possible.
  896. (let (done)
  897. (while (condition-case ()
  898. (progn (backward-up-list forward)
  899. (setq done t))
  900. (error nil)))
  901. done)))))
  902. (defun python-end-of-statement ()
  903. "Go to the end of the current statement and return point.
  904. Usually this is the start of the next line, but if this is a
  905. multi-line statement we need to skip over the continuation lines.
  906. On a comment line, go to end of line."
  907. (end-of-line)
  908. (while (let (comment)
  909. ;; Move past any enclosing strings and sexps, or stop if
  910. ;; we're in a comment.
  911. (while (let ((s (syntax-ppss)))
  912. (cond ((eq 'comment (syntax-ppss-context s))
  913. (setq comment t)
  914. nil)
  915. ((eq 'string (syntax-ppss-context s))
  916. ;; Go to start of string and skip it.
  917. (let ((pos (point)))
  918. (goto-char (nth 8 s))
  919. (condition-case () ; beware invalid syntax
  920. (progn (forward-sexp) t)
  921. ;; If there's a mismatched string, make sure
  922. ;; we still overall move *forward*.
  923. (error (goto-char pos) (end-of-line)))))
  924. ((python-skip-out t s))))
  925. (end-of-line))
  926. (and (not comment)
  927. (not (eobp))
  928. (eq ?\\ (char-before)))) ; Line continued?
  929. (end-of-line 2)) ; Try next line.
  930. (point))
  931. (defun python-previous-statement (&optional count)
  932. "Go to start of previous statement.
  933. With argument COUNT, do it COUNT times. Stop at beginning of buffer.
  934. Return count of statements left to move."
  935. (interactive "p")
  936. (unless count (setq count 1))
  937. (if (< count 0)
  938. (python-next-statement (- count))
  939. (python-beginning-of-statement)
  940. (while (and (> count 0) (not (bobp)))
  941. (python-skip-comments/blanks t)
  942. (python-beginning-of-statement)
  943. (unless (bobp) (setq count (1- count))))
  944. count))
  945. (defun python-next-statement (&optional count)
  946. "Go to start of next statement.
  947. With argument COUNT, do it COUNT times. Stop at end of buffer.
  948. Return count of statements left to move."
  949. (interactive "p")
  950. (unless count (setq count 1))
  951. (if (< count 0)
  952. (python-previous-statement (- count))
  953. (beginning-of-line)
  954. (let (bogus)
  955. (while (and (> count 0) (not (eobp)) (not bogus))
  956. (python-end-of-statement)
  957. (python-skip-comments/blanks)
  958. (if (eq 'string (syntax-ppss-context (syntax-ppss)))
  959. (setq bogus t)
  960. (unless (eobp)
  961. (setq count (1- count))))))
  962. count))
  963. (defun python-beginning-of-block (&optional arg)
  964. "Go to start of current block.
  965. With numeric arg, do it that many times. If ARG is negative, call
  966. `python-end-of-block' instead.
  967. If point is on the first line of a block, use its outer block.
  968. If current statement is in column zero, don't move and return nil.
  969. Otherwise return non-nil."
  970. (interactive "p")
  971. (unless arg (setq arg 1))
  972. (cond
  973. ((zerop arg))
  974. ((< arg 0) (python-end-of-block (- arg)))
  975. (t
  976. (let ((point (point)))
  977. (if (or (python-comment-line-p)
  978. (python-blank-line-p))
  979. (python-skip-comments/blanks t))
  980. (python-beginning-of-statement)
  981. (let ((ci (current-indentation)))
  982. (if (zerop ci)
  983. (not (goto-char point)) ; return nil
  984. ;; Look upwards for less indented statement.
  985. (if (catch 'done
  986. ;;; This is slower than the below.
  987. ;;; (while (zerop (python-previous-statement))
  988. ;;; (when (and (< (current-indentation) ci)
  989. ;;; (python-open-block-statement-p t))
  990. ;;; (beginning-of-line)
  991. ;;; (throw 'done t)))
  992. (while (and (zerop (forward-line -1)))
  993. (when (and (< (current-indentation) ci)
  994. (not (python-comment-line-p))
  995. ;; Move to beginning to save effort in case
  996. ;; this is in string.
  997. (progn (python-beginning-of-statement) t)
  998. (python-open-block-statement-p t))
  999. (beginning-of-line)
  1000. (throw 'done t)))
  1001. (not (goto-char point))) ; Failed -- return nil
  1002. (python-beginning-of-block (1- arg)))))))))
  1003. (defun python-end-of-block (&optional arg)
  1004. "Go to end of current block.
  1005. With numeric arg, do it that many times. If ARG is negative,
  1006. call `python-beginning-of-block' instead.
  1007. If current statement is in column zero and doesn't open a block,
  1008. don't move and return nil. Otherwise return t."
  1009. (interactive "p")
  1010. (unless arg (setq arg 1))
  1011. (if (< arg 0)
  1012. (python-beginning-of-block (- arg))
  1013. (while (and (> arg 0)
  1014. (let* ((point (point))
  1015. (_ (if (python-comment-line-p)
  1016. (python-skip-comments/blanks t)))
  1017. (ci (current-indentation))
  1018. (open (python-open-block-statement-p)))
  1019. (if (and (zerop ci) (not open))
  1020. (not (goto-char point))
  1021. (catch 'done
  1022. (while (zerop (python-next-statement))
  1023. (when (or (and open (<= (current-indentation) ci))
  1024. (< (current-indentation) ci))
  1025. (python-skip-comments/blanks t)
  1026. (beginning-of-line 2)
  1027. (throw 'done t)))))))
  1028. (setq arg (1- arg)))
  1029. (zerop arg)))
  1030. (defvar python-which-func-length-limit 40
  1031. "Non-strict length limit for `python-which-func' output.")
  1032. (defun python-which-func ()
  1033. (let ((function-name (python-current-defun python-which-func-length-limit)))
  1034. (set-text-properties 0 (length function-name) nil function-name)
  1035. function-name))
  1036. ;;;; Imenu.
  1037. ;; For possibly speeding this up, here's the top of the ELP profile
  1038. ;; for rescanning pydoc.py (2.2k lines, 90kb):
  1039. ;; Function Name Call Count Elapsed Time Average Time
  1040. ;; ==================================== ========== ============= ============
  1041. ;; python-imenu-create-index 156 2.430906 0.0155827307
  1042. ;; python-end-of-defun 155 1.2718260000 0.0082053290
  1043. ;; python-end-of-block 155 1.1898689999 0.0076765741
  1044. ;; python-next-statement 2970 1.024717 0.0003450225
  1045. ;; python-end-of-statement 2970 0.4332190000 0.0001458649
  1046. ;; python-beginning-of-defun 265 0.0918479999 0.0003465962
  1047. ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05
  1048. (defvar python-recursing)
  1049. (defun python-imenu-create-index ()
  1050. "`imenu-create-index-function' for Python.
  1051. Makes nested Imenu menus from nested `class' and `def' statements.
  1052. The nested menus are headed by an item referencing the outer
  1053. definition; it has a space prepended to the name so that it sorts
  1054. first with `imenu--sort-by-name' (though, unfortunately, sub-menus
  1055. precede it)."
  1056. (unless (boundp 'python-recursing) ; dynamically bound below
  1057. ;; Normal call from Imenu.
  1058. (goto-char (point-min))
  1059. ;; Without this, we can get an infloop if the buffer isn't all
  1060. ;; fontified. I guess this is really a bug in syntax.el. OTOH,
  1061. ;; _with_ this, imenu doesn't immediately work; I can't figure out
  1062. ;; what's going on, but it must be something to do with timers in
  1063. ;; font-lock.
  1064. ;; This can't be right, especially not when jit-lock is not used. --Stef
  1065. ;; (unless (get-text-property (1- (point-max)) 'fontified)
  1066. ;; (font-lock-fontify-region (point-min) (point-max)))
  1067. )
  1068. (let (index-alist) ; accumulated value to return
  1069. (while (re-search-forward
  1070. (rx line-start (0+ space) ; leading space
  1071. (or (group "def") (group "class")) ; type
  1072. (1+ space) (group (1+ (or word ?_)))) ; name
  1073. nil t)
  1074. (unless (python-in-string/comment)
  1075. (let ((pos (match-beginning 0))
  1076. (name (match-string-no-properties 3)))
  1077. (if (match-beginning 2) ; def or class?
  1078. (setq name (concat "class " name)))
  1079. (save-restriction
  1080. (narrow-to-defun)
  1081. (let* ((python-recursing t)
  1082. (sublist (python-imenu-create-index)))
  1083. (if sublist
  1084. (progn (push (cons (concat " " name) pos) sublist)
  1085. (push (cons name sublist) index-alist))
  1086. (push (cons name pos) index-alist)))))))
  1087. (unless (boundp 'python-recursing)
  1088. ;; Look for module variables.
  1089. (let (vars)
  1090. (goto-char (point-min))
  1091. (while (re-search-forward
  1092. (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
  1093. nil t)
  1094. (unless (python-in-string/comment)
  1095. (push (cons (match-string 1) (match-beginning 1))
  1096. vars)))
  1097. (setq index-alist (nreverse index-alist))
  1098. (if vars
  1099. (push (cons "Module variables"
  1100. (nreverse vars))
  1101. index-alist))))
  1102. index-alist))
  1103. ;;;; `Electric' commands.
  1104. (defun python-electric-colon (arg)
  1105. "Insert a colon and maybe outdent the line if it is a statement like `else'.
  1106. With numeric ARG, just insert that many colons. With \\[universal-argument],
  1107. just insert a single colon."
  1108. (interactive "*P")
  1109. (self-insert-command (if (not (integerp arg)) 1 arg))
  1110. (and (not arg)
  1111. (eolp)
  1112. (python-outdent-p)
  1113. (not (python-in-string/comment))
  1114. (> (current-indentation) (python-calculate-indentation))
  1115. (python-indent-line))) ; OK, do it
  1116. (put 'python-electric-colon 'delete-selection t)
  1117. (defun python-backspace (arg)
  1118. "Maybe delete a level of indentation on the current line.
  1119. Do so if point is at the end of the line's indentation outside
  1120. strings and comments.
  1121. Otherwise just call `backward-delete-char-untabify'.
  1122. Repeat ARG times."
  1123. (interactive "*p")
  1124. (if (or (/= (current-indentation) (current-column))
  1125. (bolp)
  1126. (python-continuation-line-p)
  1127. (python-in-string/comment))
  1128. (backward-delete-char-untabify arg)
  1129. ;; Look for the largest valid indentation which is smaller than
  1130. ;; the current indentation.
  1131. (let ((indent 0)
  1132. (ci (current-indentation))
  1133. (indents (python-indentation-levels))
  1134. initial)
  1135. (dolist (x indents)
  1136. (if (< (car x) ci)
  1137. (setq indent (max indent (car x)))))
  1138. (setq initial (cdr (assq indent indents)))
  1139. (if (> (length initial) 0)
  1140. (message "Closes %s" initial))
  1141. (delete-horizontal-space)
  1142. (indent-to indent))))
  1143. (put 'python-backspace 'delete-selection 'supersede)
  1144. ;;;; pychecker
  1145. (defcustom python-check-command "pychecker --stdlib"
  1146. "Command used to check a Python file."
  1147. :type 'string
  1148. :group 'python)
  1149. (defvar python-saved-check-command nil
  1150. "Internal use.")
  1151. ;; After `sgml-validate-command'.
  1152. (defun python-check (command)
  1153. "Check a Python file (default current buffer's file).
  1154. Runs COMMAND, a shell command, as if by `compile'.
  1155. See `python-check-command' for the default."
  1156. (interactive
  1157. (list (read-string "Checker command: "
  1158. (or python-saved-check-command
  1159. (concat python-check-command " "
  1160. (let ((name (buffer-file-name)))
  1161. (if name
  1162. (file-name-nondirectory name))))))))
  1163. (set (make-local-variable 'python-saved-check-command) command)
  1164. (require 'compile) ;To define compilation-* variables.
  1165. (save-some-buffers (not compilation-ask-about-save) nil)
  1166. (let ((compilation-error-regexp-alist
  1167. (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
  1168. compilation-error-regexp-alist)))
  1169. (compilation-start command)))
  1170. ;;;; Inferior mode stuff (following cmuscheme).
  1171. (defcustom python-python-command "python"
  1172. "Shell command to run Python interpreter.
  1173. Any arguments can't contain whitespace."
  1174. :group 'python
  1175. :type 'string)
  1176. (defcustom python-jython-command "jython"
  1177. "Shell command to run Jython interpreter.
  1178. Any arguments can't contain whitespace."
  1179. :group 'python
  1180. :type 'string)
  1181. (defvar python-command python-python-command
  1182. "Actual command used to run Python.
  1183. May be `python-python-command' or `python-jython-command', possibly
  1184. modified by the user. Additional arguments are added when the command
  1185. is used by `run-python' et al.")
  1186. (defvar python-buffer nil
  1187. "*The current Python process buffer.
  1188. Commands that send text from source buffers to Python processes have
  1189. to choose a process to send to. This is determined by buffer-local
  1190. value of `python-buffer'. If its value in the current buffer,
  1191. i.e. both any local value and the default one, is nil, `run-python'
  1192. and commands that send to the Python process will start a new process.
  1193. Whenever \\[run-python] starts a new process, it resets the default
  1194. value of `python-buffer' to be the new process's buffer and sets the
  1195. buffer-local value similarly if the current buffer is in Python mode
  1196. or Inferior Python mode, so that source buffer stays associated with a
  1197. specific sub-process.
  1198. Use \\[python-set-proc] to set the default value from a buffer with a
  1199. local value.")
  1200. (make-variable-buffer-local 'python-buffer)
  1201. (defconst python-compilation-regexp-alist
  1202. ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
  1203. ;; The first already is (for CAML), but the second isn't. Anyhow,
  1204. ;; these are specific to the inferior buffer. -- fx
  1205. `((,(rx line-start (1+ (any " \t")) "File \""
  1206. (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
  1207. "\", line " (group (1+ digit)))
  1208. 1 2)
  1209. (,(rx " in file " (group (1+ not-newline)) " on line "
  1210. (group (1+ digit)))
  1211. 1 2)
  1212. ;; pdb stack trace
  1213. (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
  1214. "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
  1215. 1 2))
  1216. "`compilation-error-regexp-alist' for inferior Python.")
  1217. (defvar inferior-python-mode-map
  1218. (let ((map (make-sparse-keymap)))
  1219. ;; This will inherit from comint-mode-map.
  1220. (define-key map "\C-c\C-l" 'python-load-file)
  1221. (define-key map "\C-c\C-v" 'python-check)
  1222. ;; Note that we _can_ still use these commands which send to the
  1223. ;; Python process even at the prompt if we have a normal prompt,
  1224. ;; i.e. '>>> ' and not '... '. See the comment before
  1225. ;; python-send-region. Fixme: uncomment these if we address that.
  1226. ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
  1227. ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
  1228. map))
  1229. (defvar inferior-python-mode-syntax-table
  1230. (let ((st (make-syntax-table python-mode-syntax-table)))
  1231. ;; Don't get confused by apostrophes in the process's output (e.g. if
  1232. ;; you execute "help(os)").
  1233. (modify-syntax-entry ?\' "." st)
  1234. ;; Maybe we should do the same for double quotes?
  1235. ;; (modify-syntax-entry ?\" "." st)
  1236. st))
  1237. ;; Autoloaded.
  1238. (declare-function compilation-shell-minor-mode "compile" (&optional arg))
  1239. (defvar python--prompt-regexp nil)
  1240. (defun python--set-prompt-regexp ()
  1241. (let ((prompt (cdr-safe (or (assoc python-python-command
  1242. python-shell-prompt-alist)
  1243. (assq t python-shell-prompt-alist))))
  1244. (cprompt (cdr-safe (or (assoc python-python-command
  1245. python-shell-continuation-prompt-alist)
  1246. (assq t python-shell-continuation-prompt-alist)))))
  1247. (set (make-local-variable 'comint-prompt-regexp)
  1248. (concat "\\("
  1249. (mapconcat 'identity
  1250. (delq nil (list prompt cprompt "^([Pp]db) "))
  1251. "\\|")
  1252. "\\)"))
  1253. (set (make-local-variable 'python--prompt-regexp) prompt)))
  1254. ;; Fixme: This should inherit some stuff from `python-mode', but I'm
  1255. ;; not sure how much: at least some keybindings, like C-c C-f;
  1256. ;; syntax?; font-locking, e.g. for triple-quoted strings?
  1257. (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
  1258. "Major mode for interacting with an inferior Python process.
  1259. A Python process can be started with \\[run-python].
  1260. Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
  1261. that order.
  1262. You can send text to the inferior Python process from other buffers
  1263. containing Python source.
  1264. * \\[python-switch-to-python] switches the current buffer to the Python
  1265. process buffer.
  1266. * \\[python-send-region] sends the current region to the Python process.
  1267. * \\[python-send-region-and-go] switches to the Python process buffer
  1268. after sending the text.
  1269. For running multiple processes in multiple buffers, see `run-python' and
  1270. `python-buffer'.
  1271. \\{inferior-python-mode-map}"
  1272. :group 'python
  1273. (setq mode-line-process '(":%s"))
  1274. (set (make-local-variable 'comint-input-filter) 'python-input-filter)
  1275. (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
  1276. nil t)
  1277. (python--set-prompt-regexp)
  1278. (set (make-local-variable 'compilation-error-regexp-alist)
  1279. python-compilation-regexp-alist)
  1280. (compilation-shell-minor-mode 1))
  1281. (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
  1282. "Input matching this regexp is not saved on the history list.
  1283. Default ignores all inputs of 0, 1, or 2 non-blank characters."
  1284. :type 'regexp
  1285. :group 'python)
  1286. (defcustom python-remove-cwd-from-path t
  1287. "Whether to allow loading of Python modules from the current directory.
  1288. If this is non-nil, Emacs removes '' from sys.path when starting
  1289. an inferior Python process. This is the default, for security
  1290. reasons, as it is easy for the Python process to be started
  1291. without the user's realization (e.g. to perform completion)."
  1292. :type 'boolean
  1293. :group 'python
  1294. :version "23.3")
  1295. (defun python-input-filter (str)
  1296. "`comint-input-filter' function for inferior Python.
  1297. Don't save anything for STR matching `inferior-python-filter-regexp'."
  1298. (not (string-match inferior-python-filter-regexp str)))
  1299. ;; Fixme: Loses with quoted whitespace.
  1300. (defun python-args-to-list (string)
  1301. (let ((where (string-match "[ \t]" string)))
  1302. (cond ((null where) (list string))
  1303. ((not (= where 0))
  1304. (cons (substring string 0 where)
  1305. (python-args-to-list (substring string (+ 1 where)))))
  1306. (t (let ((pos (string-match "[^ \t]" string)))
  1307. (if pos (python-args-to-list (substring string pos))))))))
  1308. (defvar python-preoutput-result nil
  1309. "Data from last `_emacs_out' line seen by the preoutput filter.")
  1310. (defvar python-preoutput-continuation nil
  1311. "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
  1312. (defvar python-preoutput-leftover nil)
  1313. (defvar python-preoutput-skip-next-prompt nil)
  1314. ;; Using this stops us getting lines in the buffer like
  1315. ;; >>> ... ... >>>
  1316. ;; Also look for (and delete) an `_emacs_ok' string and call
  1317. ;; `python-preoutput-continuation' if we get it.
  1318. (defun python-preoutput-filter (s)
  1319. "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
  1320. (when python-preoutput-leftover
  1321. (setq s (concat python-preoutput-leftover s))
  1322. (setq python-preoutput-leftover nil))
  1323. (let ((start 0)
  1324. (res ""))
  1325. ;; First process whole lines.
  1326. (while (string-match "\n" s start)
  1327. (let ((line (substring s start (setq start (match-end 0)))))
  1328. ;; Skip prompt if needed.
  1329. (when (and python-preoutput-skip-next-prompt
  1330. (string-match comint-prompt-regexp line))
  1331. (setq python-preoutput-skip-next-prompt nil)
  1332. (setq line (substring line (match-end 0))))
  1333. ;; Recognize special _emacs_out lines.
  1334. (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
  1335. (local-variable-p 'python-preoutput-result))
  1336. (progn
  1337. (setq python-preoutput-result (match-string 1 line))
  1338. (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
  1339. (setq res (concat res line)))))
  1340. ;; Then process the remaining partial line.
  1341. (unless (zerop start) (setq s (substring s start)))
  1342. (cond ((and (string-match comint-prompt-regexp s)
  1343. ;; Drop this prompt if it follows an _emacs_out...
  1344. (or python-preoutput-skip-next-prompt
  1345. ;; ... or if it's not gonna be inserted at BOL.
  1346. ;; Maybe we could be more selective here.
  1347. (if (zerop (length res))
  1348. (not (bolp))
  1349. (string-match ".\\'" res))))
  1350. ;; The need for this seems to be system-dependent:
  1351. ;; What is this all about, exactly? --Stef
  1352. ;; (if (and (eq ?. (aref s 0)))
  1353. ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
  1354. (setq python-preoutput-skip-next-prompt nil)
  1355. res)
  1356. ((let ((end (min (length "_emacs_out ") (length s))))
  1357. (eq t (compare-strings s nil end "_emacs_out " nil end)))
  1358. ;; The leftover string is a prefix of _emacs_out so we don't know
  1359. ;; yet whether it's an _emacs_out or something else: wait until we
  1360. ;; get more output so we can resolve this ambiguity.
  1361. (set (make-local-variable 'python-preoutput-leftover) s)
  1362. res)
  1363. (t (concat res s)))))
  1364. (autoload 'comint-check-proc "comint")
  1365. (defvar python-version-checked nil)
  1366. (defun python-check-version (cmd)
  1367. "Check that CMD runs a suitable version of Python."
  1368. ;; Fixme: Check on Jython.
  1369. (unless (or python-version-checked
  1370. (equal 0 (string-match (regexp-quote python-python-command)
  1371. cmd)))
  1372. (unless (shell-command-to-string cmd)
  1373. (error "Can't run Python command `%s'" cmd))
  1374. (let* ((res (shell-command-to-string
  1375. (concat cmd
  1376. " -c \"from sys import version_info;\
  1377. print version_info >= (2, 2) and version_info < (3, 0)\""))))
  1378. (unless (string-match "True" res)
  1379. (error "Only Python versions >= 2.2 and < 3.0 are supported")))
  1380. (setq python-version-checked t)))
  1381. ;;;###autoload
  1382. (defun run-python (&optional cmd noshow new)
  1383. "Run an inferior Python process, input and output via buffer *Python*.
  1384. CMD is the Python command to run. NOSHOW non-nil means don't
  1385. show the buffer automatically.
  1386. Interactively, a prefix arg means to prompt for the initial
  1387. Python command line (default is `python-command').
  1388. A new process is started if one isn't running attached to
  1389. `python-buffer', or if called from Lisp with non-nil arg NEW.
  1390. Otherwise, if a process is already running in `python-buffer',
  1391. switch to that buffer.
  1392. This command runs the hook `inferior-python-mode-hook' after
  1393. running `comint-mode-hook'. Type \\[describe-mode] in the
  1394. process buffer for a list of commands.
  1395. By default, Emacs inhibits the loading of Python modules from the
  1396. current working directory, for security reasons. To disable this
  1397. behavior, change `python-remove-cwd-from-path' to nil."
  1398. (interactive (if current-prefix-arg
  1399. (list (read-string "Run Python: " python-command) nil t)
  1400. (list python-command)))
  1401. (unless cmd (setq cmd python-command))
  1402. (python-check-version cmd)
  1403. (setq python-command cmd)
  1404. ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
  1405. ;; (not a name) in Python buffers from which `run-python' &c is
  1406. ;; invoked. Would support multiple processes better.
  1407. (when (or new (not (comint-check-proc python-buffer)))
  1408. (with-current-buffer
  1409. (let* ((cmdlist
  1410. (append (python-args-to-list cmd) '("-i")
  1411. (if python-remove-cwd-from-path
  1412. '("-c" "import sys; sys.path.remove('')"))))
  1413. (path (getenv "PYTHONPATH"))
  1414. (process-environment ; to import emacs.py
  1415. (cons (concat "PYTHONPATH="
  1416. (if path (concat path path-separator))
  1417. data-directory)
  1418. process-environment))
  1419. ;; If we use a pipe, Unicode characters are not printed
  1420. ;; correctly (Bug#5794) and IPython does not work at
  1421. ;; all (Bug#5390).
  1422. (process-connection-type t))
  1423. (apply 'make-comint-in-buffer "Python"
  1424. (generate-new-buffer "*Python*")
  1425. (car cmdlist) nil (cdr cmdlist)))
  1426. (setq-default python-buffer (current-buffer))
  1427. (setq python-buffer (current-buffer))
  1428. (accept-process-output (get-buffer-process python-buffer) 5)
  1429. (inferior-python-mode)
  1430. ;; Load function definitions we need.
  1431. ;; Before the preoutput function was used, this was done via -c in
  1432. ;; cmdlist, but that loses the banner and doesn't run the startup
  1433. ;; file. The code might be inline here, but there's enough that it
  1434. ;; seems worth putting in a separate file, and it's probably cleaner
  1435. ;; to put it in a module.
  1436. ;; Ensure we're at a prompt before doing anything else.
  1437. (python-send-string "import emacs")
  1438. ;; The following line was meant to ensure that we're at a prompt
  1439. ;; before doing anything else. However, this can cause Emacs to
  1440. ;; hang waiting for a response, if that Python function fails
  1441. ;; (i.e. raises an exception).
  1442. ;; (python-send-receive "print '_emacs_out ()'")
  1443. ))
  1444. (if (derived-mode-p 'python-mode)
  1445. (setq python-buffer (default-value 'python-buffer))) ; buffer-local
  1446. ;; Without this, help output goes into the inferior python buffer if
  1447. ;; the process isn't already running.
  1448. (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
  1449. (unless noshow (pop-to-buffer python-buffer t)))
  1450. (defun python-send-command (command)
  1451. "Like `python-send-string' but resets `compilation-shell-minor-mode'."
  1452. (when (python-check-comint-prompt)
  1453. (with-current-buffer (process-buffer (python-proc))
  1454. (goto-char (point-max))
  1455. (compilation-forget-errors)
  1456. (python-send-string command)
  1457. (setq compilation-last-buffer (current-buffer)))))
  1458. (defun python-send-region (start end)
  1459. "Send the region to the inferior Python process."
  1460. ;; The region is evaluated from a temporary file. This avoids
  1461. ;; problems with blank lines, which have different semantics
  1462. ;; interactively and in files. It also saves the inferior process
  1463. ;; buffer filling up with interpreter prompts. We need a Python
  1464. ;; function to remove the temporary file when it has been evaluated
  1465. ;; (though we could probably do it in Lisp with a Comint output
  1466. ;; filter). This function also catches exceptions and truncates
  1467. ;; tracebacks not to mention the frame of the function itself.
  1468. ;;
  1469. ;; The `compilation-shell-minor-mode' parsing takes care of relating
  1470. ;; the reference to the temporary file to the source.
  1471. ;;
  1472. ;; Fixme: Write a `coding' header to the temp file if the region is
  1473. ;; non-ASCII.
  1474. (interactive "r")
  1475. (let* ((f (make-temp-file "py"))
  1476. (command
  1477. ;; IPython puts the FakeModule module into __main__ so
  1478. ;; emacs.eexecfile becomes useless.
  1479. (if (string-match "^ipython" python-command)
  1480. (format "execfile %S" f)
  1481. (format "emacs.eexecfile(%S)" f)))
  1482. (orig-start (copy-marker start)))
  1483. (when (save-excursion
  1484. (goto-char start)
  1485. (/= 0 (current-indentation))) ; need dummy block
  1486. (save-excursion
  1487. (goto-char orig-start)
  1488. ;; Wrong if we had indented code at buffer start.
  1489. (set-marker orig-start (line-beginning-position 0)))
  1490. (write-region "if True:\n" nil f nil 'nomsg))
  1491. (write-region start end f t 'nomsg)
  1492. (python-send-command command)
  1493. (with-current-buffer (process-buffer (python-proc))
  1494. ;; Tell compile.el to redirect error locations in file `f' to
  1495. ;; positions past marker `orig-start'. It has to be done *after*
  1496. ;; `python-send-command''s call to `compilation-forget-errors'.
  1497. (compilation-fake-loc orig-start f))))
  1498. (defun python-send-string (string)
  1499. "Evaluate STRING in inferior Python process."
  1500. (interactive "sPython command: ")
  1501. (comint-send-string (python-proc) string)
  1502. (unless (string-match "\n\\'" string)
  1503. ;; Make sure the text is properly LF-terminated.
  1504. (comint-send-string (python-proc) "\n"))
  1505. (when (string-match "\n[ \t].*\n?\\'" string)
  1506. ;; If the string contains a final indented line, add a second newline so
  1507. ;; as to make sure we terminate the multiline instruction.
  1508. (comint-send-string (python-proc) "\n")))
  1509. (defun python-send-buffer ()
  1510. "Send the current buffer to the inferior Python process."
  1511. (interactive)
  1512. (python-send-region (point-min) (point-max)))
  1513. ;; Fixme: Try to define the function or class within the relevant
  1514. ;; module, not just at top level.
  1515. (defun python-send-defun ()
  1516. "Send the current defun (class or method) to the inferior Python process."
  1517. (interactive)
  1518. (save-excursion (python-send-region (progn (beginning-of-defun) (point))
  1519. (progn (end-of-defun) (point)))))
  1520. (defun python-switch-to-python (eob-p)
  1521. "Switch to the Python process buffer, maybe starting new process.
  1522. With prefix arg, position cursor at end of buffer."
  1523. (interactive "P")
  1524. (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
  1525. (when eob-p
  1526. (push-mark)
  1527. (goto-char (point-max))))
  1528. (defun python-send-region-and-go (start end)
  1529. "Send the region to the inferior Python process.
  1530. Then switch to the process buffer."
  1531. (interactive "r")
  1532. (python-send-region start end)
  1533. (python-switch-to-python t))
  1534. (defcustom python-source-modes '(python-mode jython-mode)
  1535. "Used to determine if a buffer contains Python source code.
  1536. If a file is loaded into a buffer that is in one of these major modes,
  1537. it is considered Python source by `python-load-file', which uses the
  1538. value to determine defaults."
  1539. :type '(repeat function)
  1540. :group 'python)
  1541. (defvar python-prev-dir/file nil
  1542. "Caches (directory . file) pair used in the last `python-load-file' command.
  1543. Used for determining the default in the next one.")
  1544. (autoload 'comint-get-source "comint")
  1545. (defun python-load-file (file-name)
  1546. "Load a Python file FILE-NAME into the inferior Python process.
  1547. If the file has extension `.py' import or reload it as a module.
  1548. Treating it as a module keeps the global namespace clean, provides
  1549. function location information for debugging, and supports users of
  1550. module-qualified names."
  1551. (interactive (comint-get-source "Load Python file: " python-prev-dir/file
  1552. python-source-modes
  1553. t)) ; because execfile needs exact name
  1554. (comint-check-source file-name) ; Check to see if buffer needs saving.
  1555. (setq python-prev-dir/file (cons (file-name-directory file-name)
  1556. (file-name-nondirectory file-name)))
  1557. (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
  1558. ;; Fixme: I'm not convinced by this logic from python-mode.el.
  1559. (python-send-command
  1560. (if (string-match "\\.py\\'" file-name)
  1561. (let ((module (file-name-sans-extension
  1562. (file-name-nondirectory file-name))))
  1563. (format "emacs.eimport(%S,%S)"
  1564. module (file-name-directory file-name)))
  1565. (format "execfile(%S)" file-name)))
  1566. (message "%s loaded" file-name)))
  1567. (defun python-proc ()
  1568. "Return the current Python process.
  1569. See variable `python-buffer'. Starts a new process if necessary."
  1570. ;; Fixme: Maybe should look for another active process if there
  1571. ;; isn't one for `python-buffer'.
  1572. (unless (comint-check-proc python-buffer)
  1573. (run-python nil t))
  1574. (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
  1575. (current-buffer)
  1576. python-buffer)))
  1577. (defun python-set-proc ()
  1578. "Set the default value of `python-buffer' to correspond to this buffer.
  1579. If the current buffer has a local value of `python-buffer', set the
  1580. default (global) value to that. The associated Python process is
  1581. the one that gets input from \\[python-send-region] et al when used
  1582. in a buffer that doesn't have a local value of `python-buffer'."
  1583. (interactive)
  1584. (if (local-variable-p 'python-buffer)
  1585. (setq-default python-buffer python-buffer)
  1586. (error "No local value of `python-buffer'")))
  1587. ;;;; Context-sensitive help.
  1588. (defconst python-dotty-syntax-table
  1589. (let ((table (make-syntax-table)))
  1590. (set-char-table-parent table python-mode-syntax-table)
  1591. (modify-syntax-entry ?. "_" table)
  1592. table)
  1593. "Syntax table giving `.' symbol syntax.
  1594. Otherwise inherits from `python-mode-syntax-table'.")
  1595. (defvar view-return-to-alist)
  1596. (eval-when-compile (autoload 'help-buffer "help-fns"))
  1597. (defvar python-imports) ; forward declaration
  1598. ;; Fixme: Should this actually be used instead of info-look, i.e. be
  1599. ;; bound to C-h S? [Probably not, since info-look may work in cases
  1600. ;; where this doesn't.]
  1601. (defun python-describe-symbol (symbol)
  1602. "Get help on SYMBOL using `help'.
  1603. Interactively, prompt for symbol.
  1604. Symbol may be anything recognized by the interpreter's `help'
  1605. command -- e.g. `CALLS' -- not just variables in scope in the
  1606. interpreter. This only works for Python version 2.2 or newer
  1607. since earlier interpreters don't support `help'.
  1608. In some cases where this doesn't find documentation, \\[info-lookup-symbol]
  1609. will."
  1610. ;; Note that we do this in the inferior process, not a separate one, to
  1611. ;; ensure the environment is appropriate.
  1612. (interactive
  1613. (let ((symbol (with-syntax-table python-dotty-syntax-table
  1614. (current-word)))
  1615. (enable-recursive-minibuffers t))
  1616. (list (read-string (if symbol
  1617. (format "Describe symbol (default %s): " symbol)
  1618. "Describe symbol: ")
  1619. nil nil symbol))))
  1620. (if (equal symbol "") (error "No symbol"))
  1621. ;; Ensure we have a suitable help buffer.
  1622. ;; Fixme: Maybe process `Related help topics' a la help xrefs and
  1623. ;; allow C-c C-f in help buffer.
  1624. (let ((temp-buffer-show-hook ; avoid xref stuff
  1625. (lambda ()
  1626. (toggle-read-only 1)
  1627. (setq view-return-to-alist
  1628. (list (cons (selected-window) help-return-method))))))
  1629. (with-output-to-temp-buffer (help-buffer)
  1630. (with-current-buffer standard-output
  1631. ;; Fixme: Is this actually useful?
  1632. (help-setup-xref (list 'python-describe-symbol symbol)
  1633. (called-interactively-p 'interactive))
  1634. (set (make-local-variable 'comint-redirect-subvert-readonly) t)
  1635. (help-print-return-message))))
  1636. (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
  1637. symbol python-imports)
  1638. "*Help*" (python-proc) nil nil))
  1639. (add-to-list 'debug-ignored-errors "^No symbol")
  1640. (defun python-send-receive (string)
  1641. "Send STRING to inferior Python (if any) and return result.
  1642. The result is what follows `_emacs_out' in the output.
  1643. This is a no-op if `python-check-comint-prompt' returns nil."
  1644. (python-send-string string)
  1645. (let ((proc (python-proc)))
  1646. (with-current-buffer (process-buffer proc)
  1647. (when (python-check-comint-prompt proc)
  1648. (set (make-local-variable 'python-preoutput-result) nil)
  1649. (while (progn
  1650. (accept-process-output proc 5)
  1651. (null python-preoutput-result)))
  1652. (prog1 python-preoutput-result
  1653. (kill-local-variable 'python-preoutput-result))))))
  1654. (defun python-check-comint-prompt (&optional proc)
  1655. "Return non-nil if and only if there's a normal prompt in the inferior buffer.
  1656. If there isn't, it's probably not appropriate to send input to return Eldoc
  1657. information etc. If PROC is non-nil, check the buffer for that process."
  1658. (with-current-buffer (process-buffer (or proc (python-proc)))
  1659. (save-excursion
  1660. (save-match-data
  1661. (re-search-backward (concat python--prompt-regexp " *\\=")
  1662. nil t)))))
  1663. ;; Fixme: Is there anything reasonable we can do with random methods?
  1664. ;; (Currently only works with functions.)
  1665. (defun python-eldoc-function ()
  1666. "`eldoc-documentation-function' for Python.
  1667. Only works when point is in a function name, not its arg list, for
  1668. instance. Assumes an inferior Python is running."
  1669. (let ((symbol (with-syntax-table python-dotty-syntax-table
  1670. (current-word))))
  1671. ;; This is run from timers, so inhibit-quit tends to be set.
  1672. (with-local-quit
  1673. ;; First try the symbol we're on.
  1674. (or (and symbol
  1675. (python-send-receive (format "emacs.eargs(%S, %s)"
  1676. symbol python-imports)))
  1677. ;; Try moving to symbol before enclosing parens.
  1678. (let ((s (syntax-ppss)))
  1679. (unless (zerop (car s))
  1680. (when (eq ?\( (char-after (nth 1 s)))
  1681. (save-excursion
  1682. (goto-char (nth 1 s))
  1683. (skip-syntax-backward "-")
  1684. (let ((point (point)))
  1685. (skip-chars-backward "a-zA-Z._")
  1686. (if (< (point) point)
  1687. (python-send-receive
  1688. (format "emacs.eargs(%S, %s)"
  1689. (buffer-substring-no-properties (point) point)
  1690. python-imports))))))))))))
  1691. ;;;; Info-look functionality.
  1692. (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
  1693. ;;;###autoload
  1694. (defun python-after-info-look ()
  1695. "Set up info-look for Python.
  1696. Used with `eval-after-load'."
  1697. (let* ((version (let ((s (shell-command-to-string (concat python-command
  1698. " -V"))))
  1699. (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
  1700. (match-string 1 s)))
  1701. ;; Whether info files have a Python version suffix, e.g. in Debian.
  1702. (versioned
  1703. (with-temp-buffer
  1704. (with-no-warnings (Info-mode))
  1705. (condition-case ()
  1706. ;; Don't use `info' because it would pop-up a *info* buffer.
  1707. (with-no-warnings
  1708. (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
  1709. version))
  1710. t)
  1711. (error nil)))))
  1712. (info-lookup-maybe-add-help
  1713. :mode 'python-mode
  1714. :regexp "[[:alnum:]_]+"
  1715. :doc-spec
  1716. ;; Fixme: Can this reasonably be made specific to indices with
  1717. ;; different rules? Is the order of indices optimal?
  1718. ;; (Miscellaneous in -ref first prefers lookup of keywords, for
  1719. ;; instance.)
  1720. (if versioned
  1721. ;; The empty prefix just gets us highlighted terms.
  1722. `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
  1723. (,(concat "(python" version "-ref)Module Index" nil ""))
  1724. (,(concat "(python" version "-ref)Function-Method-Variable Index"
  1725. nil ""))
  1726. (,(concat "(python" version "-ref)Class-Exception-Object Index"
  1727. nil ""))
  1728. (,(concat "(python" version "-lib)Module Index" nil ""))
  1729. (,(concat "(python" version "-lib)Class-Exception-Object Index"
  1730. nil ""))
  1731. (,(concat "(python" version "-lib)Function-Method-Variable Index"
  1732. nil ""))
  1733. (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
  1734. '(("(python-ref)Miscellaneous Index" nil "")
  1735. ("(python-ref)Module Index" nil "")
  1736. ("(python-ref)Function-Method-Variable Index" nil "")
  1737. ("(python-ref)Class-Exception-Object Index" nil "")
  1738. ("(python-lib)Module Index" nil "")
  1739. ("(python-lib)Class-Exception-Object Index" nil "")
  1740. ("(python-lib)Function-Method-Variable Index" nil "")
  1741. ("(python-lib)Miscellaneous Index" nil ""))))))
  1742. (eval-after-load "info-look" '(python-after-info-look))
  1743. ;;;; Miscellany.
  1744. (defcustom python-jython-packages '("java" "javax" "org" "com")
  1745. "Packages implying `jython-mode'.
  1746. If these are imported near the beginning of the buffer, `python-mode'
  1747. actually punts to `jython-mode'."
  1748. :type '(repeat string)
  1749. :group 'python)
  1750. ;; Called from `python-mode', this causes a recursive call of the
  1751. ;; mode. See logic there to break out of the recursion.
  1752. (defun python-maybe-jython ()
  1753. "Invoke `jython-mode' if the buffer appears to contain Jython code.
  1754. The criterion is either a match for `jython-mode' via
  1755. `interpreter-mode-alist' or an import of a module from the list
  1756. `python-jython-packages'."
  1757. ;; The logic is taken from python-mode.el.
  1758. (save-excursion
  1759. (save-restriction
  1760. (widen)
  1761. (goto-char (point-min))
  1762. (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
  1763. (match-string 2))))
  1764. (if (and interpreter (eq 'jython-mode
  1765. (cdr (assoc (file-name-nondirectory
  1766. interpreter)
  1767. interpreter-mode-alist))))
  1768. (jython-mode)
  1769. (if (catch 'done
  1770. (while (re-search-forward
  1771. (rx line-start (or "import" "from") (1+ space)
  1772. (group (1+ (not (any " \t\n.")))))
  1773. (+ (point-min) 10000) ; Probably not worth customizing.
  1774. t)
  1775. (if (member (match-string 1) python-jython-packages)
  1776. (throw 'done t))))
  1777. (jython-mode)))))))
  1778. (defun python-fill-paragraph (&optional justify)
  1779. "`fill-paragraph-function' handling multi-line strings and possibly comments.
  1780. If any of the current line is in or at the end of a multi-line string,
  1781. fill the string or the paragraph of it that point is in, preserving
  1782. the string's indentation."
  1783. (interactive "P")
  1784. (or (fill-comment-paragraph justify)
  1785. (save-excursion
  1786. (end-of-line)
  1787. (let* ((syntax (syntax-ppss))
  1788. (orig (point))
  1789. start end)
  1790. (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
  1791. (let (fill-paragraph-function)
  1792. (fill-paragraph justify)))
  1793. ;; The `paragraph-start' and `paragraph-separate'
  1794. ;; variables don't allow us to delimit the last
  1795. ;; paragraph in a multi-line string properly, so narrow
  1796. ;; to the string and then fill around (the end of) the
  1797. ;; current line.
  1798. ((eq t (nth 3 syntax)) ; in fenced string
  1799. (goto-char (nth 8 syntax)) ; string start
  1800. (setq start (line-beginning-position))
  1801. (setq end (condition-case () ; for unbalanced quotes
  1802. (progn (forward-sexp)
  1803. (- (point) 3))
  1804. (error (point-max)))))
  1805. ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
  1806. (forward-char)
  1807. (setq end (point))
  1808. (condition-case ()
  1809. (progn (backward-sexp)
  1810. (setq start (line-beginning-position)))
  1811. (error nil))))
  1812. (when end
  1813. (save-restriction
  1814. (narrow-to-region start end)
  1815. (goto-char orig)
  1816. ;; Avoid losing leading and trailing newlines in doc
  1817. ;; strings written like:
  1818. ;; """
  1819. ;; ...
  1820. ;; """
  1821. (let ((paragraph-separate
  1822. ;; Note that the string could be part of an
  1823. ;; expression, so it can have preceding and
  1824. ;; trailing non-whitespace.
  1825. (concat
  1826. (rx (or
  1827. ;; Opening triple quote without following text.
  1828. (and (* nonl)
  1829. (group (syntax string-delimiter))
  1830. (repeat 2 (backref 1))
  1831. ;; Fixme: Not sure about including
  1832. ;; trailing whitespace.
  1833. (* (any " \t"))
  1834. eol)
  1835. ;; Closing trailing quote without preceding text.
  1836. (and (group (any ?\" ?')) (backref 2)
  1837. (syntax string-delimiter))))
  1838. "\\(?:" paragraph-separate "\\)"))
  1839. fill-paragraph-function)
  1840. (fill-paragraph justify))))))) t)
  1841. (defun python-shift-left (start end &optional count)
  1842. "Shift lines in region COUNT (the prefix arg) columns to the left.
  1843. COUNT defaults to `python-indent'. If region isn't active, just shift
  1844. current line. The region shifted includes the lines in which START and
  1845. END lie. It is an error if any lines in the region are indented less than
  1846. COUNT columns."
  1847. (interactive
  1848. (if mark-active
  1849. (list (region-beginning) (region-end) current-prefix-arg)
  1850. (list (line-beginning-position) (line-end-position) current-prefix-arg)))
  1851. (if count
  1852. (setq count (prefix-numeric-value count))
  1853. (setq count python-indent))
  1854. (when (> count 0)
  1855. (save-excursion
  1856. (goto-char start)
  1857. (while (< (point) end)
  1858. (if (and (< (current-indentation) count)
  1859. (not (looking-at "[ \t]*$")))
  1860. (error "Can't shift all lines enough"))
  1861. (forward-line))
  1862. (indent-rigidly start end (- count)))))
  1863. (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
  1864. (defun python-shift-right (start end &optional count)
  1865. "Shift lines in region COUNT (the prefix arg) columns to the right.
  1866. COUNT defaults to `python-indent'. If region isn't active, just shift
  1867. current line. The region shifted includes the lines in which START and
  1868. END lie."
  1869. (interactive
  1870. (if mark-active
  1871. (list (region-beginning) (region-end) current-prefix-arg)
  1872. (list (line-beginning-position) (line-end-position) current-prefix-arg)))
  1873. (if count
  1874. (setq count (prefix-numeric-value count))
  1875. (setq count python-indent))
  1876. (indent-rigidly start end count))
  1877. (defun python-outline-level ()
  1878. "`outline-level' function for Python mode.
  1879. The level is the number of `python-indent' steps of indentation
  1880. of current line."
  1881. (1+ (/ (current-indentation) python-indent)))
  1882. ;; Fixme: Consider top-level assignments, imports, &c.
  1883. (defun python-current-defun (&optional length-limit)
  1884. "`add-log-current-defun-function' for Python."
  1885. (save-excursion
  1886. ;; Move up the tree of nested `class' and `def' blocks until we
  1887. ;; get to zero indentation, accumulating the defined names.
  1888. (let ((accum)
  1889. (length -1))
  1890. (catch 'done
  1891. (while (or (null length-limit)
  1892. (null (cdr accum))
  1893. (< length length-limit))
  1894. (let ((started-from (point)))
  1895. (python-beginning-of-block)
  1896. (end-of-line)
  1897. (beginning-of-defun)
  1898. (when (= (point) started-from)
  1899. (throw 'done nil)))
  1900. (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
  1901. (group (1+ (or word (syntax symbol))))))
  1902. (push (match-string 1) accum)
  1903. (setq length (+ length 1 (length (car accum)))))
  1904. (when (= (current-indentation) 0)
  1905. (throw 'done nil))))
  1906. (when accum
  1907. (when (and length-limit (> length length-limit))
  1908. (setcar accum ".."))
  1909. (mapconcat 'identity accum ".")))))
  1910. (defun python-mark-block ()
  1911. "Mark the block around point.
  1912. Uses `python-beginning-of-block', `python-end-of-block'."
  1913. (interactive)
  1914. (push-mark)
  1915. (python-beginning-of-block)
  1916. (push-mark (point) nil t)
  1917. (python-end-of-block)
  1918. (exchange-point-and-mark))
  1919. ;; Fixme: Provide a find-function-like command to find source of a
  1920. ;; definition (separate from BicycleRepairMan). Complicated by
  1921. ;; finding the right qualified name.
  1922. ;;;; Completion.
  1923. ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
  1924. (defvar python-imports "None"
  1925. "String of top-level import statements updated by `python-find-imports'.")
  1926. (make-variable-buffer-local 'python-imports)
  1927. ;; Fixme: Should font-lock try to run this when it deals with an import?
  1928. ;; Maybe not a good idea if it gets run multiple times when the
  1929. ;; statement is being edited, and is more likely to end up with
  1930. ;; something syntactically incorrect.
  1931. ;; However, what we should do is to trundle up the block tree from point
  1932. ;; to extract imports that appear to be in scope, and add those.
  1933. (defun python-find-imports ()
  1934. "Find top-level imports, updating `python-imports'."
  1935. (interactive)
  1936. (save-excursion
  1937. (let (lines)
  1938. (goto-char (point-min))
  1939. (while (re-search-forward "^import\\>\\|^from\\>" nil t)
  1940. (unless (syntax-ppss-context (syntax-ppss))
  1941. (let ((start (line-beginning-position)))
  1942. ;; Skip over continued lines.
  1943. (while (and (eq ?\\ (char-before (line-end-position)))
  1944. (= 0 (forward-line 1)))
  1945. t)
  1946. (push (buffer-substring start (line-beginning-position 2))
  1947. lines))))
  1948. (setq python-imports
  1949. (if lines
  1950. (apply #'concat
  1951. ;; This is probably best left out since you're unlikely to need the
  1952. ;; doc for a function in the buffer and the import will lose if the
  1953. ;; Python sub-process' working directory isn't the same as the
  1954. ;; buffer's.
  1955. ;; (if buffer-file-name
  1956. ;; (concat
  1957. ;; "import "
  1958. ;; (file-name-sans-extension
  1959. ;; (file-name-nondirectory buffer-file-name))))
  1960. (nreverse lines))
  1961. "None"))
  1962. (when lines
  1963. (set-text-properties 0 (length python-imports) nil python-imports)
  1964. ;; The output ends up in the wrong place if the string we
  1965. ;; send contains newlines (from the imports).
  1966. (setq python-imports
  1967. (replace-regexp-in-string "\n" "\\n"
  1968. (format "%S" python-imports) t t))))))
  1969. ;; Fixme: This fails the first time if the sub-process isn't already
  1970. ;; running. Presumably a timing issue with i/o to the process.
  1971. (defun python-symbol-completions (symbol)
  1972. "Return a list of completions of the string SYMBOL from Python process.
  1973. The list is sorted.
  1974. Uses `python-imports' to load modules against which to complete."
  1975. (when (stringp symbol)
  1976. (let ((completions
  1977. (condition-case ()
  1978. (car (read-from-string
  1979. (python-send-receive
  1980. (format "emacs.complete(%S,%s)"
  1981. (substring-no-properties symbol)
  1982. python-imports))))
  1983. (error nil))))
  1984. (sort
  1985. ;; We can get duplicates from the above -- don't know why.
  1986. (delete-dups completions)
  1987. #'string<))))
  1988. (defun python-completion-at-point ()
  1989. (let ((end (point))
  1990. (start (save-excursion
  1991. (and (re-search-backward
  1992. (rx (or buffer-start (regexp "[^[:alnum:]._]"))
  1993. (group (1+ (regexp "[[:alnum:]._]"))) point)
  1994. nil t)
  1995. (match-beginning 1)))))
  1996. (when start
  1997. (list start end
  1998. (completion-table-dynamic 'python-symbol-completions)))))
  1999. ;;;; FFAP support
  2000. (defun python-module-path (module)
  2001. "Function for `ffap-alist' to return path to MODULE."
  2002. (python-send-receive (format "emacs.modpath (%S)" module)))
  2003. (eval-after-load "ffap"
  2004. '(push '(python-mode . python-module-path) ffap-alist))
  2005. ;;;; Find-function support
  2006. ;; Fixme: key binding?
  2007. (defun python-find-function (name)
  2008. "Find source of definition of function NAME.
  2009. Interactively, prompt for name."
  2010. (interactive
  2011. (let ((symbol (with-syntax-table python-dotty-syntax-table
  2012. (current-word)))
  2013. (enable-recursive-minibuffers t))
  2014. (list (read-string (if symbol
  2015. (format "Find location of (default %s): " symbol)
  2016. "Find location of: ")
  2017. nil nil symbol))))
  2018. (unless python-imports
  2019. (error "Not called from buffer visiting Python file"))
  2020. (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
  2021. name python-imports)))
  2022. (loc (car (read-from-string loc)))
  2023. (file (car loc))
  2024. (line (cdr loc)))
  2025. (unless file (error "Don't know where `%s' is defined" name))
  2026. (pop-to-buffer (find-file-noselect file))
  2027. (when (integerp line)
  2028. (goto-char (point-min))
  2029. (forward-line (1- line)))))
  2030. ;;;; Skeletons
  2031. (defcustom python-use-skeletons nil
  2032. "Non-nil means template skeletons will be automagically inserted.
  2033. This happens when pressing \"if<SPACE>\", for example, to prompt for
  2034. the if condition."
  2035. :type 'boolean
  2036. :group 'python)
  2037. (define-abbrev-table 'python-mode-abbrev-table ()
  2038. "Abbrev table for Python mode."
  2039. :case-fixed t
  2040. ;; Allow / inside abbrevs.
  2041. :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
  2042. ;; Only expand in code.
  2043. :enable-function (lambda () (not (python-in-string/comment))))
  2044. (eval-when-compile
  2045. ;; Define a user-level skeleton and add it to the abbrev table.
  2046. (defmacro def-python-skeleton (name &rest elements)
  2047. (declare (indent 2))
  2048. (let* ((name (symbol-name name))
  2049. (function (intern (concat "python-insert-" name))))
  2050. `(progn
  2051. ;; Usual technique for inserting a skeleton, but expand
  2052. ;; to the original abbrev instead if in a comment or string.
  2053. (when python-use-skeletons
  2054. (define-abbrev python-mode-abbrev-table ,name ""
  2055. ',function
  2056. nil t)) ; system abbrev
  2057. (define-skeleton ,function
  2058. ,(format "Insert Python \"%s\" template." name)
  2059. ,@elements)))))
  2060. ;; From `skeleton-further-elements' set below:
  2061. ;; `<': outdent a level;
  2062. ;; `^': delete indentation on current line and also previous newline.
  2063. ;; Not quite like `delete-indentation'. Assumes point is at
  2064. ;; beginning of indentation.
  2065. (def-python-skeleton if
  2066. "Condition: "
  2067. "if " str ":" \n
  2068. > -1 ; Fixme: I don't understand the spurious space this removes.
  2069. _ \n
  2070. ("other condition, %s: "
  2071. < ; Avoid wrong indentation after block opening.
  2072. "elif " str ":" \n
  2073. > _ \n nil)
  2074. '(python-else) | ^)
  2075. (define-skeleton python-else
  2076. "Auxiliary skeleton."
  2077. nil
  2078. (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
  2079. (signal 'quit t))
  2080. < "else:" \n
  2081. > _ \n)
  2082. (def-python-skeleton while
  2083. "Condition: "
  2084. "while " str ":" \n
  2085. > -1 _ \n
  2086. '(python-else) | ^)
  2087. (def-python-skeleton for
  2088. "Target, %s: "
  2089. "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
  2090. > -1 _ \n
  2091. '(python-else) | ^)
  2092. (def-python-skeleton try/except
  2093. nil
  2094. "try:" \n
  2095. > -1 _ \n
  2096. ("Exception, %s: "
  2097. < "except " str '(python-target) ":" \n
  2098. > _ \n nil)
  2099. < "except:" \n
  2100. > _ \n
  2101. '(python-else) | ^)
  2102. (define-skeleton python-target
  2103. "Auxiliary skeleton."
  2104. "Target, %s: " ", " str | -2)
  2105. (def-python-skeleton try/finally
  2106. nil
  2107. "try:" \n
  2108. > -1 _ \n
  2109. < "finally:" \n
  2110. > _ \n)
  2111. (def-python-skeleton def
  2112. "Name: "
  2113. "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
  2114. str) "):" \n
  2115. "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
  2116. > _ \n)
  2117. (def-python-skeleton class
  2118. "Name: "
  2119. "class " str " (" ("Inheritance, %s: "
  2120. (unless (equal ?\( (char-before)) ", ")
  2121. str)
  2122. & ")" | -2 ; close list or remove opening
  2123. ":" \n
  2124. "\"\"\"" - "\"\"\"" \n
  2125. > _ \n)
  2126. (defvar python-default-template "if"
  2127. "Default template to expand by `python-expand-template'.
  2128. Updated on each expansion.")
  2129. (defun python-expand-template (name)
  2130. "Expand template named NAME.
  2131. Interactively, prompt for the name with completion."
  2132. (interactive
  2133. (list (completing-read (format "Template to expand (default %s): "
  2134. python-default-template)
  2135. python-mode-abbrev-table nil t nil nil
  2136. python-default-template)))
  2137. (if (equal "" name)
  2138. (setq name python-default-template)
  2139. (setq python-default-template name))
  2140. (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
  2141. (if sym
  2142. (abbrev-insert sym)
  2143. (error "Undefined template: %s" name))))
  2144. ;;;; Bicycle Repair Man support
  2145. (autoload 'pymacs-load "pymacs" nil t)
  2146. (autoload 'brm-init "bikeemacs")
  2147. (defvar brm-menu)
  2148. ;; I'm not sure how useful BRM really is, and it's certainly dangerous
  2149. ;; the way it modifies files outside Emacs... Also note that the
  2150. ;; current BRM loses with tabs used for indentation -- I submitted a
  2151. ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
  2152. (defun python-setup-brm ()
  2153. "Set up Bicycle Repair Man refactoring tool (if available).
  2154. Note that the `refactoring' features change files independently of
  2155. Emacs and may modify and save the contents of the current buffer
  2156. without confirmation."
  2157. (interactive)
  2158. (condition-case data
  2159. (unless (fboundp 'brm-rename)
  2160. (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
  2161. (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
  2162. (features (cons 'python-mode features))) ; and requires this
  2163. (brm-init) ; second line of normal recipe
  2164. (remove-hook 'python-mode-hook ; undo this from `brm-init'
  2165. (lambda () (easy-menu-add brm-menu)))
  2166. (easy-menu-define
  2167. python-brm-menu python-mode-map
  2168. "Bicycle Repair Man"
  2169. '("BicycleRepairMan"
  2170. :help "Interface to navigation and refactoring tool"
  2171. "Queries"
  2172. ["Find References" brm-find-references
  2173. :help "Find references to name at point in compilation buffer"]
  2174. ["Find Definition" brm-find-definition
  2175. :help "Find definition of name at point"]
  2176. "-"
  2177. "Refactoring"
  2178. ["Rename" brm-rename
  2179. :help "Replace name at point with a new name everywhere"]
  2180. ["Extract Method" brm-extract-method
  2181. :active (and mark-active (not buffer-read-only))
  2182. :help "Replace statements in region with a method"]
  2183. ["Extract Local Variable" brm-extract-local-variable
  2184. :active (and mark-active (not buffer-read-only))
  2185. :help "Replace expression in region with an assignment"]
  2186. ["Inline Local Variable" brm-inline-local-variable
  2187. :help
  2188. "Substitute uses of variable at point with its definition"]
  2189. ;; Fixme: Should check for anything to revert.
  2190. ["Undo Last Refactoring" brm-undo :help ""]))))
  2191. (error (error "BicycleRepairMan setup failed: %s" data))))
  2192. ;;;; Modes.
  2193. ;; pdb tracking is alert once this file is loaded, but takes no action if
  2194. ;; `python-pdbtrack-do-tracking-p' is nil.
  2195. (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
  2196. (defvar outline-heading-end-regexp)
  2197. (defvar eldoc-documentation-function)
  2198. (defvar python-mode-running) ;Dynamically scoped var.
  2199. ;;;###autoload
  2200. (define-derived-mode python-mode prog-mode "Python"
  2201. "Major mode for editing Python files.
  2202. Turns on Font Lock mode unconditionally since it is currently required
  2203. for correct parsing of the source.
  2204. See also `jython-mode', which is actually invoked if the buffer appears to
  2205. contain Jython code. See also `run-python' and associated Python mode
  2206. commands for running Python under Emacs.
  2207. The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
  2208. with nested `def' and `class' blocks. They take the innermost one as
  2209. current without distinguishing method and class definitions. Used multiple
  2210. times, they move over others at the same indentation level until they reach
  2211. the end of definitions at that level, when they move up a level.
  2212. \\<python-mode-map>
  2213. Colon is electric: it outdents the line if appropriate, e.g. for
  2214. an else statement. \\[python-backspace] at the beginning of an indented statement
  2215. deletes a level of indentation to close the current block; otherwise it
  2216. deletes a character backward. TAB indents the current line relative to
  2217. the preceding code. Successive TABs, with no intervening command, cycle
  2218. through the possibilities for indentation on the basis of enclosing blocks.
  2219. \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
  2220. effect outside them.
  2221. Supports Eldoc mode (only for functions, using a Python process),
  2222. Info-Look and Imenu. In Outline minor mode, `class' and `def'
  2223. lines count as headers. Symbol completion is available in the
  2224. same way as in the Python shell using the `rlcompleter' module
  2225. and this is added to the Hippie Expand functions locally if
  2226. Hippie Expand mode is turned on. Completion of symbols of the
  2227. form x.y only works if the components are literal
  2228. module/attribute names, not variables. An abbrev table is set up
  2229. with skeleton expansions for compound statement templates.
  2230. \\{python-mode-map}"
  2231. :group 'python
  2232. (set (make-local-variable 'font-lock-defaults)
  2233. '(python-font-lock-keywords nil nil nil nil
  2234. ;; This probably isn't worth it.
  2235. ;; (font-lock-syntactic-face-function
  2236. ;; . python-font-lock-syntactic-face-function)
  2237. ))
  2238. (set (make-local-variable 'syntax-propertize-function)
  2239. python-syntax-propertize-function)
  2240. (set (make-local-variable 'parse-sexp-lookup-properties) t)
  2241. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  2242. (set (make-local-variable 'comment-start) "# ")
  2243. (set (make-local-variable 'indent-line-function) #'python-indent-line)
  2244. (set (make-local-variable 'indent-region-function) #'python-indent-region)
  2245. (set (make-local-variable 'paragraph-start) "\\s-*$")
  2246. (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
  2247. (set (make-local-variable 'require-final-newline) mode-require-final-newline)
  2248. (set (make-local-variable 'add-log-current-defun-function)
  2249. #'python-current-defun)
  2250. (set (make-local-variable 'outline-regexp)
  2251. (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
  2252. "for" "if" "try" "while" "with")
  2253. symbol-end))
  2254. (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
  2255. (set (make-local-variable 'outline-level) #'python-outline-level)
  2256. (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
  2257. (set (make-local-variable 'beginning-of-defun-function)
  2258. 'python-beginning-of-defun)
  2259. (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
  2260. (add-hook 'which-func-functions 'python-which-func nil t)
  2261. (setq imenu-create-index-function #'python-imenu-create-index)
  2262. (set (make-local-variable 'eldoc-documentation-function)
  2263. #'python-eldoc-function)
  2264. (add-hook 'eldoc-mode-hook
  2265. (lambda () (run-python nil t)) ; need it running
  2266. nil t)
  2267. (add-hook 'completion-at-point-functions
  2268. 'python-completion-at-point nil 'local)
  2269. ;; Fixme: should be in hideshow. This seems to be of limited use
  2270. ;; since it isn't (can't be) indentation-based. Also hide-level
  2271. ;; doesn't seem to work properly.
  2272. (add-to-list 'hs-special-modes-alist
  2273. `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
  2274. ,(lambda (_arg)
  2275. (python-end-of-defun)
  2276. (skip-chars-backward " \t\n"))
  2277. nil))
  2278. (set (make-local-variable 'skeleton-further-elements)
  2279. '((< '(backward-delete-char-untabify (min python-indent
  2280. (current-column))))
  2281. (^ '(- (1+ (current-indentation))))))
  2282. ;; Python defines TABs as being 8-char wide.
  2283. (set (make-local-variable 'tab-width) 8)
  2284. (when python-guess-indent (python-guess-indent))
  2285. ;; Let's make it harder for the user to shoot himself in the foot.
  2286. (unless (= tab-width python-indent)
  2287. (setq indent-tabs-mode nil))
  2288. (set (make-local-variable 'python-command) python-python-command)
  2289. (python-find-imports)
  2290. (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
  2291. (let ((python-mode-running t))
  2292. (python-maybe-jython))))
  2293. ;; Not done automatically in Emacs 21 or 22.
  2294. (defcustom python-mode-hook nil
  2295. "Hook run when entering Python mode."
  2296. :group 'python
  2297. :type 'hook)
  2298. (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
  2299. (custom-add-option 'python-mode-hook
  2300. (lambda ()
  2301. "Turn off Indent Tabs mode."
  2302. (setq indent-tabs-mode nil)))
  2303. (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
  2304. (custom-add-option 'python-mode-hook 'abbrev-mode)
  2305. (custom-add-option 'python-mode-hook 'python-setup-brm)
  2306. ;;;###autoload
  2307. (define-derived-mode jython-mode python-mode "Jython"
  2308. "Major mode for editing Jython files.
  2309. Like `python-mode', but sets up parameters for Jython subprocesses.
  2310. Runs `jython-mode-hook' after `python-mode-hook'."
  2311. :group 'python
  2312. (set (make-local-variable 'python-command) python-jython-command))
  2313. ;; pdbtrack features
  2314. (defun python-pdbtrack-overlay-arrow (activation)
  2315. "Activate or deactivate arrow at beginning-of-line in current buffer."
  2316. (if activation
  2317. (progn
  2318. (setq overlay-arrow-position (make-marker)
  2319. overlay-arrow-string "=>"
  2320. python-pdbtrack-is-tracking-p t)
  2321. (set-marker overlay-arrow-position
  2322. (line-beginning-position)
  2323. (current-buffer)))
  2324. (setq overlay-arrow-position nil
  2325. python-pdbtrack-is-tracking-p nil)))
  2326. (defun python-pdbtrack-track-stack-file (_text)
  2327. "Show the file indicated by the pdb stack entry line, in a separate window.
  2328. Activity is disabled if the buffer-local variable
  2329. `python-pdbtrack-do-tracking-p' is nil.
  2330. We depend on the pdb input prompt being a match for
  2331. `python-pdbtrack-input-prompt'.
  2332. If the traceback target file path is invalid, we look for the
  2333. most recently visited python-mode buffer which either has the
  2334. name of the current function or class, or which defines the
  2335. function or class. This is to provide for scripts not in the
  2336. local file system (e.g., Zope's 'Script \(Python)', but it's not
  2337. Zope specific). If you put a copy of the script in a buffer
  2338. named for the script and activate python-mode, then pdbtrack will
  2339. find it."
  2340. ;; Instead of trying to piece things together from partial text
  2341. ;; (which can be almost useless depending on Emacs version), we
  2342. ;; monitor to the point where we have the next pdb prompt, and then
  2343. ;; check all text from comint-last-input-end to process-mark.
  2344. ;;
  2345. ;; Also, we're very conservative about clearing the overlay arrow,
  2346. ;; to minimize residue. This means, for instance, that executing
  2347. ;; other pdb commands wipe out the highlight. You can always do a
  2348. ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
  2349. (let* ((origbuf (current-buffer))
  2350. (currproc (get-buffer-process origbuf)))
  2351. (if (not (and currproc python-pdbtrack-do-tracking-p))
  2352. (python-pdbtrack-overlay-arrow nil)
  2353. (let* ((procmark (process-mark currproc))
  2354. (block (buffer-substring (max comint-last-input-end
  2355. (- procmark
  2356. python-pdbtrack-track-range))
  2357. procmark))
  2358. target target_fname target_lineno target_buffer)
  2359. (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
  2360. (python-pdbtrack-overlay-arrow nil)
  2361. (setq block (ansi-color-filter-apply block))
  2362. (setq target (python-pdbtrack-get-source-buffer block))
  2363. (if (stringp target)
  2364. (progn
  2365. (python-pdbtrack-overlay-arrow nil)
  2366. (message "pdbtrack: %s" target))
  2367. (setq target_lineno (car target)
  2368. target_buffer (cadr target)
  2369. target_fname (buffer-file-name target_buffer))
  2370. (switch-to-buffer-other-window target_buffer)
  2371. (goto-char (point-min))
  2372. (forward-line (1- target_lineno))
  2373. (message "pdbtrack: line %s, file %s" target_lineno target_fname)
  2374. (python-pdbtrack-overlay-arrow t)
  2375. (pop-to-buffer origbuf t)
  2376. ;; in large shell buffers, above stuff may cause point to lag output
  2377. (goto-char procmark)
  2378. )))))
  2379. )
  2380. (defun python-pdbtrack-get-source-buffer (block)
  2381. "Return line number and buffer of code indicated by block's traceback text.
  2382. We look first to visit the file indicated in the trace.
  2383. Failing that, we look for the most recently visited python-mode buffer
  2384. with the same name or having the named function.
  2385. If we're unable find the source code we return a string describing the
  2386. problem."
  2387. (if (not (string-match python-pdbtrack-stack-entry-regexp block))
  2388. "Traceback cue not found"
  2389. (let* ((filename (match-string 1 block))
  2390. (lineno (string-to-number (match-string 2 block)))
  2391. (funcname (match-string 3 block))
  2392. funcbuffer)
  2393. (cond ((file-exists-p filename)
  2394. (list lineno (find-file-noselect filename)))
  2395. ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
  2396. (if (string-match "/Script (Python)$" filename)
  2397. ;; Add in number of lines for leading '##' comments:
  2398. (setq lineno
  2399. (+ lineno
  2400. (with-current-buffer funcbuffer
  2401. (if (equal (point-min)(point-max))
  2402. 0
  2403. (count-lines
  2404. (point-min)
  2405. (max (point-min)
  2406. (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
  2407. (buffer-substring
  2408. (point-min) (point-max)))
  2409. )))))))
  2410. (list lineno funcbuffer))
  2411. ((= (elt filename 0) ?\<)
  2412. (format "(Non-file source: '%s')" filename))
  2413. (t (format "Not found: %s(), %s" funcname filename)))
  2414. )
  2415. )
  2416. )
  2417. (defun python-pdbtrack-grub-for-buffer (funcname _lineno)
  2418. "Find recent Python mode buffer named, or having function named FUNCNAME."
  2419. (let ((buffers (buffer-list))
  2420. buf
  2421. got)
  2422. (while (and buffers (not got))
  2423. (setq buf (car buffers)
  2424. buffers (cdr buffers))
  2425. (if (and (with-current-buffer buf
  2426. (string= major-mode "python-mode"))
  2427. (or (string-match funcname (buffer-name buf))
  2428. (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
  2429. funcname "\\s-*(")
  2430. (with-current-buffer buf
  2431. (buffer-substring (point-min)
  2432. (point-max))))))
  2433. (setq got buf)))
  2434. got))
  2435. ;; Python subprocess utilities and filters
  2436. (defun python-execute-file (proc filename)
  2437. "Send to Python interpreter process PROC \"execfile('FILENAME')\".
  2438. Make that process's buffer visible and force display. Also make
  2439. comint believe the user typed this string so that
  2440. `kill-output-from-shell' does The Right Thing."
  2441. (let ((curbuf (current-buffer))
  2442. (procbuf (process-buffer proc))
  2443. ; (comint-scroll-to-bottom-on-output t)
  2444. (msg (format "## working on region in file %s...\n" filename))
  2445. ;; add some comment, so that we can filter it out of history
  2446. (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
  2447. (unwind-protect
  2448. (with-current-buffer procbuf
  2449. (goto-char (point-max))
  2450. (move-marker (process-mark proc) (point))
  2451. (funcall (process-filter proc) proc msg))
  2452. (set-buffer curbuf))
  2453. (process-send-string proc cmd)))
  2454. (defun python-pdbtrack-toggle-stack-tracking (arg)
  2455. (interactive "P")
  2456. (if (not (get-buffer-process (current-buffer)))
  2457. (error "No process associated with buffer '%s'" (current-buffer)))
  2458. ;; missing or 0 is toggle, >0 turn on, <0 turn off
  2459. (if (or (not arg)
  2460. (zerop (setq arg (prefix-numeric-value arg))))
  2461. (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
  2462. (setq python-pdbtrack-do-tracking-p (> arg 0)))
  2463. (message "%sabled Python's pdbtrack"
  2464. (if python-pdbtrack-do-tracking-p "En" "Dis")))
  2465. (defun turn-on-pdbtrack ()
  2466. (interactive)
  2467. (python-pdbtrack-toggle-stack-tracking 1))
  2468. (defun turn-off-pdbtrack ()
  2469. (interactive)
  2470. (python-pdbtrack-toggle-stack-tracking 0))
  2471. (defun python-sentinel (_proc _msg)
  2472. (setq overlay-arrow-position nil))
  2473. (defun python-unload-function ()
  2474. "Unload the Python library."
  2475. (remove-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
  2476. (setq minor-mode-alist (assq-delete-all 'python-pdbtrack-is-tracking-p
  2477. minor-mode-alist))
  2478. (dolist (error '("^No symbol" "^Can't shift all lines enough"))
  2479. (setq debug-ignored-errors (delete error debug-ignored-errors)))
  2480. ;; continue standard unloading
  2481. nil)
  2482. (provide 'python)
  2483. (provide 'python-21)
  2484. ;;; python.el ends here