python-mode.el 128 KB

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