python-mode.el 124 KB

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