python.el 211 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229
  1. ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2003-2017 Free Software Foundation, Inc.
  3. ;; Author: Fabián E. Gallina <fgallina@gnu.org>
  4. ;; URL: https://github.com/fgallina/python.el
  5. ;; Version: 0.25.2
  6. ;; Package-Requires: ((emacs "24.1") (cl-lib "1.0"))
  7. ;; Maintainer: emacs-devel@gnu.org
  8. ;; Created: Jul 2010
  9. ;; Keywords: languages
  10. ;; This file is part of GNU Emacs.
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published
  13. ;; by the Free Software Foundation, either version 3 of the License,
  14. ;; or (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful, but
  16. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. ;; General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;; Commentary:
  22. ;; Major mode for editing Python files with some fontification and
  23. ;; indentation bits extracted from original Dave Love's python.el
  24. ;; found in GNU/Emacs.
  25. ;; Implements Syntax highlighting, Indentation, Movement, Shell
  26. ;; interaction, Shell completion, Shell virtualenv support, Shell
  27. ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
  28. ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
  29. ;; Syntax highlighting: Fontification of code is provided and supports
  30. ;; python's triple quoted strings properly.
  31. ;; Indentation: Automatic indentation with indentation cycling is
  32. ;; provided, it allows you to navigate different available levels of
  33. ;; indentation by hitting <tab> several times. Also electric-indent-mode
  34. ;; is supported such that when inserting a colon the current line is
  35. ;; dedented automatically if needed.
  36. ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
  37. ;; properly implemented. There are also specialized
  38. ;; `forward-sentence' and `backward-sentence' replacements called
  39. ;; `python-nav-forward-block', `python-nav-backward-block'
  40. ;; respectively which navigate between beginning of blocks of code.
  41. ;; Extra functions `python-nav-forward-statement',
  42. ;; `python-nav-backward-statement',
  43. ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
  44. ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
  45. ;; `python-nav-if-name-main' are included but no bound to any key. At
  46. ;; last but not least the specialized `python-nav-forward-sexp' allows
  47. ;; easy navigation between code blocks. If you prefer `cc-mode'-like
  48. ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
  49. ;; enough, You can do that using the `python-mode-hook':
  50. ;; (add-hook 'python-mode-hook
  51. ;; (lambda () (setq forward-sexp-function nil)))
  52. ;; Shell interaction: is provided and allows opening Python shells
  53. ;; inside Emacs and executing any block of code of your current buffer
  54. ;; in that inferior Python process.
  55. ;; Besides that only the standard CPython (2.x and 3.x) shell and
  56. ;; IPython are officially supported out of the box, the interaction
  57. ;; should support any other readline based Python shells as well
  58. ;; (e.g. Jython and PyPy have been reported to work). You can change
  59. ;; your default interpreter and commandline arguments by setting the
  60. ;; `python-shell-interpreter' and `python-shell-interpreter-args'
  61. ;; variables. This example enables IPython globally:
  62. ;; (setq python-shell-interpreter "ipython"
  63. ;; python-shell-interpreter-args "-i")
  64. ;; Using the "console" subcommand to start IPython in server-client
  65. ;; mode is known to fail intermittently due a bug on IPython itself
  66. ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
  67. ;; There seems to be a race condition in the IPython server (A.K.A
  68. ;; kernel) when code is sent while it is still initializing, sometimes
  69. ;; causing the shell to get stalled. With that said, if an IPython
  70. ;; kernel is already running, "console --existing" seems to work fine.
  71. ;; Running IPython on Windows needs more tweaking. The way you should
  72. ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
  73. ;; is as follows (of course you need to modify the paths according to
  74. ;; your system):
  75. ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
  76. ;; python-shell-interpreter-args
  77. ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
  78. ;; Missing or delayed output used to happen due to differences between
  79. ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
  80. ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
  81. ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
  82. ;; controls whether `python-shell-calculate-process-environment'
  83. ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
  84. ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
  85. ;; The interaction relies upon having prompts for input (e.g. ">>> "
  86. ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
  87. ;; IPython) detected properly. Failing that Emacs may hang but, in
  88. ;; the case that happens, you can recover with \\[keyboard-quit]. To
  89. ;; avoid this issue, a two-step prompt autodetection mechanism is
  90. ;; provided: the first step is manual and consists of a collection of
  91. ;; regular expressions matching common prompts for Python shells
  92. ;; stored in `python-shell-prompt-input-regexps' and
  93. ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
  94. ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
  95. ;; `python-shell-prompt-output-regexp' which are appended to the
  96. ;; former automatically when a shell spawns; the second step is
  97. ;; automatic and depends on the `python-shell-prompt-detect' helper
  98. ;; function. See its docstring for details on global variables that
  99. ;; modify its behavior.
  100. ;; Shell completion: hitting tab will try to complete the current
  101. ;; word. The two built-in mechanisms depend on Python's readline
  102. ;; module: the "native" completion is tried first and is activated
  103. ;; when `python-shell-completion-native-enable' is non-nil, the
  104. ;; current `python-shell-interpreter' is not a member of the
  105. ;; `python-shell-completion-native-disabled-interpreters' variable and
  106. ;; `python-shell-completion-native-setup' succeeds; the "fallback" or
  107. ;; "legacy" mechanism works by executing Python code in the background
  108. ;; and enables auto-completion for shells that do not support
  109. ;; receiving escape sequences (with some limitations, i.e. completion
  110. ;; in blocks does not work). The code executed for the "fallback"
  111. ;; completion can be found in `python-shell-completion-setup-code' and
  112. ;; `python-shell-completion-string-code' variables. Their default
  113. ;; values enable completion for both CPython and IPython, and probably
  114. ;; any readline based shell (it's known to work with PyPy). If your
  115. ;; Python installation lacks readline (like CPython for Windows),
  116. ;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
  117. ;; should suffice. To troubleshoot why you are not getting any
  118. ;; completions, you can try the following in your Python shell:
  119. ;; >>> import readline, rlcompleter
  120. ;; If you see an error, then you need to either install pyreadline or
  121. ;; setup custom code that avoids that dependency.
  122. ;; Shell virtualenv support: The shell also contains support for
  123. ;; virtualenvs and other special environment modifications thanks to
  124. ;; `python-shell-process-environment' and `python-shell-exec-path'.
  125. ;; These two variables allows you to modify execution paths and
  126. ;; environment variables to make easy for you to setup virtualenv rules
  127. ;; or behavior modifications when running shells. Here is an example
  128. ;; of how to make shell processes to be run using the /path/to/env/
  129. ;; virtualenv:
  130. ;; (setq python-shell-process-environment
  131. ;; (list
  132. ;; (format "PATH=%s" (mapconcat
  133. ;; 'identity
  134. ;; (reverse
  135. ;; (cons (getenv "PATH")
  136. ;; '("/path/to/env/bin/")))
  137. ;; ":"))
  138. ;; "VIRTUAL_ENV=/path/to/env/"))
  139. ;; (python-shell-exec-path . ("/path/to/env/bin/"))
  140. ;; Since the above is cumbersome and can be programmatically
  141. ;; calculated, the variable `python-shell-virtualenv-root' is
  142. ;; provided. When this variable is set with the path of the
  143. ;; virtualenv to use, `process-environment' and `exec-path' get proper
  144. ;; values in order to run shells inside the specified virtualenv. So
  145. ;; the following will achieve the same as the previous example:
  146. ;; (setq python-shell-virtualenv-root "/path/to/env/")
  147. ;; Also the `python-shell-extra-pythonpaths' variable have been
  148. ;; introduced as simple way of adding paths to the PYTHONPATH without
  149. ;; affecting existing values.
  150. ;; Shell package support: you can enable a package in the current
  151. ;; shell so that relative imports work properly using the
  152. ;; `python-shell-package-enable' command.
  153. ;; Shell remote support: remote Python shells are started with the
  154. ;; correct environment for files opened remotely through tramp, also
  155. ;; respecting dir-local variables provided `enable-remote-dir-locals'
  156. ;; is non-nil. The logic for this is transparently handled by the
  157. ;; `python-shell-with-environment' macro.
  158. ;; Shell syntax highlighting: when enabled current input in shell is
  159. ;; highlighted. The variable `python-shell-font-lock-enable' controls
  160. ;; activation of this feature globally when shells are started.
  161. ;; Activation/deactivation can be also controlled on the fly via the
  162. ;; `python-shell-font-lock-toggle' command.
  163. ;; Pdb tracking: when you execute a block of code that contains some
  164. ;; call to pdb (or ipdb) it will prompt the block of code and will
  165. ;; follow the execution of pdb marking the current line with an arrow.
  166. ;; Symbol completion: you can complete the symbol at point. It uses
  167. ;; the shell completion in background so you should run
  168. ;; `python-shell-send-buffer' from time to time to get better results.
  169. ;; Skeletons: skeletons are provided for simple inserting of things like class,
  170. ;; def, for, import, if, try, and while. These skeletons are
  171. ;; integrated with abbrev. If you have `abbrev-mode' activated and
  172. ;; `python-skeleton-autoinsert' is set to t, then whenever you type
  173. ;; the name of any of those defined and hit SPC, they will be
  174. ;; automatically expanded. As an alternative you can use the defined
  175. ;; skeleton commands: `python-skeleton-<foo>'.
  176. ;; FFAP: You can find the filename for a given module when using ffap
  177. ;; out of the box. This feature needs an inferior python shell
  178. ;; running.
  179. ;; Code check: Check the current file for errors with `python-check'
  180. ;; using the program defined in `python-check-command'.
  181. ;; Eldoc: returns documentation for object at point by using the
  182. ;; inferior python subprocess to inspect its documentation. As you
  183. ;; might guessed you should run `python-shell-send-buffer' from time
  184. ;; to time to get better results too.
  185. ;; Imenu: There are two index building functions to be used as
  186. ;; `imenu-create-index-function': `python-imenu-create-index' (the
  187. ;; default one, builds the alist in form of a tree) and
  188. ;; `python-imenu-create-flat-index'. See also
  189. ;; `python-imenu-format-item-label-function',
  190. ;; `python-imenu-format-parent-item-label-function',
  191. ;; `python-imenu-format-parent-item-jump-label-function' variables for
  192. ;; changing the way labels are formatted in the tree version.
  193. ;; If you used python-mode.el you may miss auto-indentation when
  194. ;; inserting newlines. To achieve the same behavior you have two
  195. ;; options:
  196. ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
  197. ;; default) and use RET. If this mode is disabled use
  198. ;; `newline-and-indent', bound to C-j.
  199. ;; 2) Add the following hook in your .emacs:
  200. ;; (add-hook 'python-mode-hook
  201. ;; #'(lambda ()
  202. ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
  203. ;; I'd recommend the first one since you'll get the same behavior for
  204. ;; all modes out-of-the-box.
  205. ;;; Installation:
  206. ;; Add this to your .emacs:
  207. ;; (add-to-list 'load-path "/folder/containing/file")
  208. ;; (require 'python)
  209. ;;; TODO:
  210. ;;; Code:
  211. (require 'ansi-color)
  212. (require 'cl-lib)
  213. (require 'comint)
  214. (require 'json)
  215. (require 'tramp-sh)
  216. ;; Avoid compiler warnings
  217. (defvar view-return-to-alist)
  218. (defvar compilation-error-regexp-alist)
  219. (defvar outline-heading-end-regexp)
  220. (autoload 'comint-mode "comint")
  221. (autoload 'help-function-arglist "help-fns")
  222. ;;;###autoload
  223. (add-to-list 'auto-mode-alist (cons (purecopy "\\.pyw?\\'") 'python-mode))
  224. ;;;###autoload
  225. (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
  226. (defgroup python nil
  227. "Python Language's flying circus support for Emacs."
  228. :group 'languages
  229. :version "24.3"
  230. :link '(emacs-commentary-link "python"))
  231. ;;; 24.x Compat
  232. (unless (fboundp 'prog-widen)
  233. (defun prog-widen ()
  234. (widen)))
  235. (unless (fboundp 'prog-first-column)
  236. (defun prog-first-column ()
  237. 0))
  238. ;;; Bindings
  239. (defvar python-mode-map
  240. (let ((map (make-sparse-keymap)))
  241. ;; Movement
  242. (define-key map [remap backward-sentence] 'python-nav-backward-block)
  243. (define-key map [remap forward-sentence] 'python-nav-forward-block)
  244. (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
  245. (define-key map [remap mark-defun] 'python-mark-defun)
  246. (define-key map "\C-c\C-j" 'imenu)
  247. ;; Indent specific
  248. (define-key map "\177" 'python-indent-dedent-line-backspace)
  249. (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
  250. (define-key map "\C-c<" 'python-indent-shift-left)
  251. (define-key map "\C-c>" 'python-indent-shift-right)
  252. ;; Skeletons
  253. (define-key map "\C-c\C-tc" 'python-skeleton-class)
  254. (define-key map "\C-c\C-td" 'python-skeleton-def)
  255. (define-key map "\C-c\C-tf" 'python-skeleton-for)
  256. (define-key map "\C-c\C-ti" 'python-skeleton-if)
  257. (define-key map "\C-c\C-tm" 'python-skeleton-import)
  258. (define-key map "\C-c\C-tt" 'python-skeleton-try)
  259. (define-key map "\C-c\C-tw" 'python-skeleton-while)
  260. ;; Shell interaction
  261. (define-key map "\C-c\C-p" 'run-python)
  262. (define-key map "\C-c\C-s" 'python-shell-send-string)
  263. (define-key map "\C-c\C-r" 'python-shell-send-region)
  264. (define-key map "\C-\M-x" 'python-shell-send-defun)
  265. (define-key map "\C-c\C-c" 'python-shell-send-buffer)
  266. (define-key map "\C-c\C-l" 'python-shell-send-file)
  267. (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
  268. ;; Some util commands
  269. (define-key map "\C-c\C-v" 'python-check)
  270. (define-key map "\C-c\C-f" 'python-eldoc-at-point)
  271. (define-key map "\C-c\C-d" 'python-describe-at-point)
  272. ;; Utilities
  273. (substitute-key-definition 'complete-symbol 'completion-at-point
  274. map global-map)
  275. (easy-menu-define python-menu map "Python Mode menu"
  276. `("Python"
  277. :help "Python-specific Features"
  278. ["Shift region left" python-indent-shift-left :active mark-active
  279. :help "Shift region left by a single indentation step"]
  280. ["Shift region right" python-indent-shift-right :active mark-active
  281. :help "Shift region right by a single indentation step"]
  282. "-"
  283. ["Start of def/class" beginning-of-defun
  284. :help "Go to start of outermost definition around point"]
  285. ["End of def/class" end-of-defun
  286. :help "Go to end of definition around point"]
  287. ["Mark def/class" mark-defun
  288. :help "Mark outermost definition around point"]
  289. ["Jump to def/class" imenu
  290. :help "Jump to a class or function definition"]
  291. "--"
  292. ("Skeletons")
  293. "---"
  294. ["Start interpreter" run-python
  295. :help "Run inferior Python process in a separate buffer"]
  296. ["Switch to shell" python-shell-switch-to-shell
  297. :help "Switch to running inferior Python process"]
  298. ["Eval string" python-shell-send-string
  299. :help "Eval string in inferior Python session"]
  300. ["Eval buffer" python-shell-send-buffer
  301. :help "Eval buffer in inferior Python session"]
  302. ["Eval region" python-shell-send-region
  303. :help "Eval region in inferior Python session"]
  304. ["Eval defun" python-shell-send-defun
  305. :help "Eval defun in inferior Python session"]
  306. ["Eval file" python-shell-send-file
  307. :help "Eval file in inferior Python session"]
  308. ["Debugger" pdb :help "Run pdb under GUD"]
  309. "----"
  310. ["Check file" python-check
  311. :help "Check file for errors"]
  312. ["Help on symbol" python-eldoc-at-point
  313. :help "Get help on symbol at point"]
  314. ["Complete symbol" completion-at-point
  315. :help "Complete symbol before point"]))
  316. map)
  317. "Keymap for `python-mode'.")
  318. ;;; Python specialized rx
  319. (eval-and-compile
  320. (defconst python-rx-constituents
  321. `((block-start . ,(rx symbol-start
  322. (or "def" "class" "if" "elif" "else" "try"
  323. "except" "finally" "for" "while" "with"
  324. ;; Python 3.5+ PEP492
  325. (and "async" (+ space)
  326. (or "def" "for" "with")))
  327. symbol-end))
  328. (dedenter . ,(rx symbol-start
  329. (or "elif" "else" "except" "finally")
  330. symbol-end))
  331. (block-ender . ,(rx symbol-start
  332. (or
  333. "break" "continue" "pass" "raise" "return")
  334. symbol-end))
  335. (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
  336. (* (any word ?_))))
  337. (defun . ,(rx symbol-start
  338. (or "def" "class"
  339. ;; Python 3.5+ PEP492
  340. (and "async" (+ space) "def"))
  341. symbol-end))
  342. (if-name-main . ,(rx line-start "if" (+ space) "__name__"
  343. (+ space) "==" (+ space)
  344. (any ?' ?\") "__main__" (any ?' ?\")
  345. (* space) ?:))
  346. (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
  347. (open-paren . ,(rx (or "{" "[" "(")))
  348. (close-paren . ,(rx (or "}" "]" ")")))
  349. (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
  350. ;; FIXME: rx should support (not simple-operator).
  351. (not-simple-operator . ,(rx
  352. (not
  353. (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
  354. ;; FIXME: Use regexp-opt.
  355. (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
  356. "=" "%" "**" "//" "<<" ">>" "<=" "!="
  357. "==" ">=" "is" "not")))
  358. ;; FIXME: Use regexp-opt.
  359. (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
  360. ">>=" "<<=" "&=" "^=" "|=")))
  361. (string-delimiter . ,(rx (and
  362. ;; Match even number of backslashes.
  363. (or (not (any ?\\ ?\' ?\")) point
  364. ;; Quotes might be preceded by a escaped quote.
  365. (and (or (not (any ?\\)) point) ?\\
  366. (* ?\\ ?\\) (any ?\' ?\")))
  367. (* ?\\ ?\\)
  368. ;; Match single or triple quotes of any kind.
  369. (group (or "\"" "\"\"\"" "'" "'''")))))
  370. (coding-cookie . ,(rx line-start ?# (* space)
  371. (or
  372. ;; # coding=<encoding name>
  373. (: "coding" (or ?: ?=) (* space) (group-n 1 (+ (or word ?-))))
  374. ;; # -*- coding: <encoding name> -*-
  375. (: "-*-" (* space) "coding:" (* space)
  376. (group-n 1 (+ (or word ?-))) (* space) "-*-")
  377. ;; # vim: set fileencoding=<encoding name> :
  378. (: "vim:" (* space) "set" (+ space)
  379. "fileencoding" (* space) ?= (* space)
  380. (group-n 1 (+ (or word ?-))) (* space) ":")))))
  381. "Additional Python specific sexps for `python-rx'")
  382. (defmacro python-rx (&rest regexps)
  383. "Python mode specialized rx macro.
  384. This variant of `rx' supports common Python named REGEXPS."
  385. (let ((rx-constituents (append python-rx-constituents rx-constituents)))
  386. (cond ((null regexps)
  387. (error "No regexp"))
  388. ((cdr regexps)
  389. (rx-to-string `(and ,@regexps) t))
  390. (t
  391. (rx-to-string (car regexps) t))))))
  392. ;;; Font-lock and syntax
  393. (eval-and-compile
  394. (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
  395. (pcase type
  396. (`'comment
  397. `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
  398. (and (nth 4 ppss) (nth 8 ppss))))
  399. (`'string
  400. `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
  401. (and (nth 3 ppss) (nth 8 ppss))))
  402. (`'paren
  403. `(nth 1 (or ,syntax-ppss (syntax-ppss))))
  404. (_ form))))
  405. (defun python-syntax-context (type &optional syntax-ppss)
  406. "Return non-nil if point is on TYPE using SYNTAX-PPSS.
  407. TYPE can be `comment', `string' or `paren'. It returns the start
  408. character address of the specified TYPE."
  409. (declare (compiler-macro python-syntax--context-compiler-macro))
  410. (let ((ppss (or syntax-ppss (syntax-ppss))))
  411. (pcase type
  412. (`comment (and (nth 4 ppss) (nth 8 ppss)))
  413. (`string (and (nth 3 ppss) (nth 8 ppss)))
  414. (`paren (nth 1 ppss))
  415. (_ nil))))
  416. (defun python-syntax-context-type (&optional syntax-ppss)
  417. "Return the context type using SYNTAX-PPSS.
  418. The type returned can be `comment', `string' or `paren'."
  419. (let ((ppss (or syntax-ppss (syntax-ppss))))
  420. (cond
  421. ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
  422. ((nth 1 ppss) 'paren))))
  423. (defsubst python-syntax-comment-or-string-p (&optional ppss)
  424. "Return non-nil if PPSS is inside comment or string."
  425. (nth 8 (or ppss (syntax-ppss))))
  426. (defsubst python-syntax-closing-paren-p ()
  427. "Return non-nil if char after point is a closing paren."
  428. (eql (syntax-class (syntax-after (point)))
  429. (syntax-class (string-to-syntax ")"))))
  430. (define-obsolete-function-alias
  431. 'python-info-ppss-context #'python-syntax-context "24.3")
  432. (define-obsolete-function-alias
  433. 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
  434. (define-obsolete-function-alias
  435. 'python-info-ppss-comment-or-string-p
  436. #'python-syntax-comment-or-string-p "24.3")
  437. (defun python-font-lock-syntactic-face-function (state)
  438. "Return syntactic face given STATE."
  439. (if (nth 3 state)
  440. (if (python-info-docstring-p state)
  441. font-lock-doc-face
  442. font-lock-string-face)
  443. font-lock-comment-face))
  444. (defvar python-font-lock-keywords
  445. ;; Keywords
  446. `(,(rx symbol-start
  447. (or
  448. "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
  449. "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
  450. "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
  451. "try"
  452. ;; Python 2:
  453. "print" "exec"
  454. ;; Python 3:
  455. ;; False, None, and True are listed as keywords on the Python 3
  456. ;; documentation, but since they also qualify as constants they are
  457. ;; fontified like that in order to keep font-lock consistent between
  458. ;; Python versions.
  459. "nonlocal"
  460. ;; Python 3.5+ PEP492
  461. (and "async" (+ space) (or "def" "for" "with"))
  462. "await"
  463. ;; Extra:
  464. "self")
  465. symbol-end)
  466. ;; functions
  467. (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
  468. (1 font-lock-function-name-face))
  469. ;; classes
  470. (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
  471. (1 font-lock-type-face))
  472. ;; Constants
  473. (,(rx symbol-start
  474. (or
  475. "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
  476. ;; copyright, license, credits, quit and exit are added by the site
  477. ;; module and they are not intended to be used in programs
  478. "copyright" "credits" "exit" "license" "quit")
  479. symbol-end) . font-lock-constant-face)
  480. ;; Decorators.
  481. (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
  482. (0+ "." (1+ (or word ?_)))))
  483. (1 font-lock-type-face))
  484. ;; Builtin Exceptions
  485. (,(rx symbol-start
  486. (or
  487. ;; Python 2 and 3:
  488. "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
  489. "BufferError" "BytesWarning" "DeprecationWarning" "EOFError"
  490. "EnvironmentError" "Exception" "FloatingPointError" "FutureWarning"
  491. "GeneratorExit" "IOError" "ImportError" "ImportWarning"
  492. "IndentationError" "IndexError" "KeyError" "KeyboardInterrupt"
  493. "LookupError" "MemoryError" "NameError" "NotImplementedError"
  494. "OSError" "OverflowError" "PendingDeprecationWarning"
  495. "ReferenceError" "RuntimeError" "RuntimeWarning" "StopIteration"
  496. "SyntaxError" "SyntaxWarning" "SystemError" "SystemExit" "TabError"
  497. "TypeError" "UnboundLocalError" "UnicodeDecodeError"
  498. "UnicodeEncodeError" "UnicodeError" "UnicodeTranslateError"
  499. "UnicodeWarning" "UserWarning" "ValueError" "Warning"
  500. "ZeroDivisionError"
  501. ;; Python 2:
  502. "StandardError"
  503. ;; Python 3:
  504. "BlockingIOError" "BrokenPipeError" "ChildProcessError"
  505. "ConnectionAbortedError" "ConnectionError" "ConnectionRefusedError"
  506. "ConnectionResetError" "FileExistsError" "FileNotFoundError"
  507. "InterruptedError" "IsADirectoryError" "NotADirectoryError"
  508. "PermissionError" "ProcessLookupError" "RecursionError"
  509. "ResourceWarning" "StopAsyncIteration" "TimeoutError"
  510. ;; OS specific
  511. "VMSError" "WindowsError"
  512. )
  513. symbol-end) . font-lock-type-face)
  514. ;; Builtins
  515. (,(rx symbol-start
  516. (or
  517. "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
  518. "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
  519. "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
  520. "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
  521. "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
  522. "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
  523. "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
  524. "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
  525. "__import__"
  526. ;; Python 2:
  527. "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
  528. "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
  529. "intern"
  530. ;; Python 3:
  531. "ascii" "bytearray" "bytes" "exec"
  532. ;; Extra:
  533. "__all__" "__doc__" "__name__" "__package__")
  534. symbol-end) . font-lock-builtin-face)
  535. ;; assignments
  536. ;; support for a = b = c = 5
  537. (,(lambda (limit)
  538. (let ((re (python-rx (group (+ (any word ?. ?_)))
  539. (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
  540. assignment-operator))
  541. (res nil))
  542. (while (and (setq res (re-search-forward re limit t))
  543. (or (python-syntax-context 'paren)
  544. (equal (char-after (point)) ?=))))
  545. res))
  546. (1 font-lock-variable-name-face nil nil))
  547. ;; support for a, b, c = (1, 2, 3)
  548. (,(lambda (limit)
  549. (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
  550. (* ?, (* space) (+ (any word ?. ?_)) (* space))
  551. ?, (* space) (+ (any word ?. ?_)) (* space)
  552. assignment-operator))
  553. (res nil))
  554. (while (and (setq res (re-search-forward re limit t))
  555. (goto-char (match-end 1))
  556. (python-syntax-context 'paren)))
  557. res))
  558. (1 font-lock-variable-name-face nil nil))))
  559. (defconst python-syntax-propertize-function
  560. (syntax-propertize-rules
  561. ((python-rx string-delimiter)
  562. (0 (ignore (python-syntax-stringify))))))
  563. (defconst python--prettify-symbols-alist
  564. '(("lambda" . ?λ)
  565. ("and" . ?∧)
  566. ("or" . ?∨)))
  567. (defsubst python-syntax-count-quotes (quote-char &optional point limit)
  568. "Count number of quotes around point (max is 3).
  569. QUOTE-CHAR is the quote char to count. Optional argument POINT is
  570. the point where scan starts (defaults to current point), and LIMIT
  571. is used to limit the scan."
  572. (let ((i 0))
  573. (while (and (< i 3)
  574. (or (not limit) (< (+ point i) limit))
  575. (eq (char-after (+ point i)) quote-char))
  576. (setq i (1+ i)))
  577. i))
  578. (defun python-syntax-stringify ()
  579. "Put `syntax-table' property correctly on single/triple quotes."
  580. (let* ((num-quotes (length (match-string-no-properties 1)))
  581. (ppss (prog2
  582. (backward-char num-quotes)
  583. (syntax-ppss)
  584. (forward-char num-quotes)))
  585. (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
  586. (quote-starting-pos (- (point) num-quotes))
  587. (quote-ending-pos (point))
  588. (num-closing-quotes
  589. (and string-start
  590. (python-syntax-count-quotes
  591. (char-before) string-start quote-starting-pos))))
  592. (cond ((and string-start (= num-closing-quotes 0))
  593. ;; This set of quotes doesn't match the string starting
  594. ;; kind. Do nothing.
  595. nil)
  596. ((not string-start)
  597. ;; This set of quotes delimit the start of a string.
  598. (put-text-property quote-starting-pos (1+ quote-starting-pos)
  599. 'syntax-table (string-to-syntax "|")))
  600. ((= num-quotes num-closing-quotes)
  601. ;; This set of quotes delimit the end of a string.
  602. (put-text-property (1- quote-ending-pos) quote-ending-pos
  603. 'syntax-table (string-to-syntax "|")))
  604. ((> num-quotes num-closing-quotes)
  605. ;; This may only happen whenever a triple quote is closing
  606. ;; a single quoted string. Add string delimiter syntax to
  607. ;; all three quotes.
  608. (put-text-property quote-starting-pos quote-ending-pos
  609. 'syntax-table (string-to-syntax "|"))))))
  610. (defvar python-mode-syntax-table
  611. (let ((table (make-syntax-table)))
  612. ;; Give punctuation syntax to ASCII that normally has symbol
  613. ;; syntax or has word syntax and isn't a letter.
  614. (let ((symbol (string-to-syntax "_"))
  615. (sst (standard-syntax-table)))
  616. (dotimes (i 128)
  617. (unless (= i ?_)
  618. (if (equal symbol (aref sst i))
  619. (modify-syntax-entry i "." table)))))
  620. (modify-syntax-entry ?$ "." table)
  621. (modify-syntax-entry ?% "." table)
  622. ;; exceptions
  623. (modify-syntax-entry ?# "<" table)
  624. (modify-syntax-entry ?\n ">" table)
  625. (modify-syntax-entry ?' "\"" table)
  626. (modify-syntax-entry ?` "$" table)
  627. table)
  628. "Syntax table for Python files.")
  629. (defvar python-dotty-syntax-table
  630. (let ((table (make-syntax-table python-mode-syntax-table)))
  631. (modify-syntax-entry ?. "w" table)
  632. (modify-syntax-entry ?_ "w" table)
  633. table)
  634. "Dotty syntax table for Python files.
  635. It makes underscores and dots word constituent chars.")
  636. ;;; Indentation
  637. (defcustom python-indent-offset 4
  638. "Default indentation offset for Python."
  639. :group 'python
  640. :type 'integer
  641. :safe 'integerp)
  642. (defcustom python-indent-guess-indent-offset t
  643. "Non-nil tells Python mode to guess `python-indent-offset' value."
  644. :type 'boolean
  645. :group 'python
  646. :safe 'booleanp)
  647. (defcustom python-indent-guess-indent-offset-verbose t
  648. "Non-nil means to emit a warning when indentation guessing fails."
  649. :version "25.1"
  650. :type 'boolean
  651. :group 'python
  652. :safe' booleanp)
  653. (defcustom python-indent-trigger-commands
  654. '(indent-for-tab-command yas-expand yas/expand)
  655. "Commands that might trigger a `python-indent-line' call."
  656. :type '(repeat symbol)
  657. :group 'python)
  658. (define-obsolete-variable-alias
  659. 'python-indent 'python-indent-offset "24.3")
  660. (define-obsolete-variable-alias
  661. 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
  662. (defvar python-indent-current-level 0
  663. "Deprecated var available for compatibility.")
  664. (defvar python-indent-levels '(0)
  665. "Deprecated var available for compatibility.")
  666. (make-obsolete-variable
  667. 'python-indent-current-level
  668. "The indentation API changed to avoid global state.
  669. The function `python-indent-calculate-levels' does not use it
  670. anymore. If you were defadvising it and or depended on this
  671. variable for indentation customizations, refactor your code to
  672. work on `python-indent-calculate-indentation' instead."
  673. "24.5")
  674. (make-obsolete-variable
  675. 'python-indent-levels
  676. "The indentation API changed to avoid global state.
  677. The function `python-indent-calculate-levels' does not use it
  678. anymore. If you were defadvising it and or depended on this
  679. variable for indentation customizations, refactor your code to
  680. work on `python-indent-calculate-indentation' instead."
  681. "24.5")
  682. (defun python-indent-guess-indent-offset ()
  683. "Guess and set `python-indent-offset' for the current buffer."
  684. (interactive)
  685. (save-excursion
  686. (save-restriction
  687. (prog-widen)
  688. (goto-char (point-min))
  689. (let ((block-end))
  690. (while (and (not block-end)
  691. (re-search-forward
  692. (python-rx line-start block-start) nil t))
  693. (when (and
  694. (not (python-syntax-context-type))
  695. (progn
  696. (goto-char (line-end-position))
  697. (python-util-forward-comment -1)
  698. (if (equal (char-before) ?:)
  699. t
  700. (forward-line 1)
  701. (when (python-info-block-continuation-line-p)
  702. (while (and (python-info-continuation-line-p)
  703. (not (eobp)))
  704. (forward-line 1))
  705. (python-util-forward-comment -1)
  706. (when (equal (char-before) ?:)
  707. t)))))
  708. (setq block-end (point-marker))))
  709. (let ((indentation
  710. (when block-end
  711. (goto-char block-end)
  712. (python-util-forward-comment)
  713. (current-indentation))))
  714. (if (and indentation (not (zerop indentation)))
  715. (set (make-local-variable 'python-indent-offset) indentation)
  716. (when python-indent-guess-indent-offset-verbose
  717. (message "Can't guess python-indent-offset, using defaults: %s"
  718. python-indent-offset))))))))
  719. (defun python-indent-context ()
  720. "Get information about the current indentation context.
  721. Context is returned in a cons with the form (STATUS . START).
  722. STATUS can be one of the following:
  723. keyword
  724. -------
  725. :after-comment
  726. - Point is after a comment line.
  727. - START is the position of the \"#\" character.
  728. :inside-string
  729. - Point is inside string.
  730. - START is the position of the first quote that starts it.
  731. :no-indent
  732. - No possible indentation case matches.
  733. - START is always zero.
  734. :inside-paren
  735. - Fallback case when point is inside paren.
  736. - START is the first non space char position *after* the open paren.
  737. :inside-paren-at-closing-nested-paren
  738. - Point is on a line that contains a nested paren closer.
  739. - START is the position of the open paren it closes.
  740. :inside-paren-at-closing-paren
  741. - Point is on a line that contains a paren closer.
  742. - START is the position of the open paren.
  743. :inside-paren-newline-start
  744. - Point is inside a paren with items starting in their own line.
  745. - START is the position of the open paren.
  746. :inside-paren-newline-start-from-block
  747. - Point is inside a paren with items starting in their own line
  748. from a block start.
  749. - START is the position of the open paren.
  750. :after-backslash
  751. - Fallback case when point is after backslash.
  752. - START is the char after the position of the backslash.
  753. :after-backslash-assignment-continuation
  754. - Point is after a backslashed assignment.
  755. - START is the char after the position of the backslash.
  756. :after-backslash-block-continuation
  757. - Point is after a backslashed block continuation.
  758. - START is the char after the position of the backslash.
  759. :after-backslash-dotted-continuation
  760. - Point is after a backslashed dotted continuation. Previous
  761. line must contain a dot to align with.
  762. - START is the char after the position of the backslash.
  763. :after-backslash-first-line
  764. - First line following a backslashed continuation.
  765. - START is the char after the position of the backslash.
  766. :after-block-end
  767. - Point is after a line containing a block ender.
  768. - START is the position where the ender starts.
  769. :after-block-start
  770. - Point is after a line starting a block.
  771. - START is the position where the block starts.
  772. :after-line
  773. - Point is after a simple line.
  774. - START is the position where the previous line starts.
  775. :at-dedenter-block-start
  776. - Point is on a line starting a dedenter block.
  777. - START is the position where the dedenter block starts."
  778. (save-restriction
  779. (prog-widen)
  780. (let ((ppss (save-excursion
  781. (beginning-of-line)
  782. (syntax-ppss))))
  783. (cond
  784. ;; Beginning of buffer.
  785. ((= (line-number-at-pos) 1)
  786. (cons :no-indent 0))
  787. ;; Inside a string.
  788. ((let ((start (python-syntax-context 'string ppss)))
  789. (when start
  790. (cons (if (python-info-docstring-p)
  791. :inside-docstring
  792. :inside-string) start))))
  793. ;; Inside a paren.
  794. ((let* ((start (python-syntax-context 'paren ppss))
  795. (starts-in-newline
  796. (when start
  797. (save-excursion
  798. (goto-char start)
  799. (forward-char)
  800. (not
  801. (= (line-number-at-pos)
  802. (progn
  803. (python-util-forward-comment)
  804. (line-number-at-pos))))))))
  805. (when start
  806. (cond
  807. ;; Current line only holds the closing paren.
  808. ((save-excursion
  809. (skip-syntax-forward " ")
  810. (when (and (python-syntax-closing-paren-p)
  811. (progn
  812. (forward-char 1)
  813. (not (python-syntax-context 'paren))))
  814. (cons :inside-paren-at-closing-paren start))))
  815. ;; Current line only holds a closing paren for nested.
  816. ((save-excursion
  817. (back-to-indentation)
  818. (python-syntax-closing-paren-p))
  819. (cons :inside-paren-at-closing-nested-paren start))
  820. ;; This line starts from a opening block in its own line.
  821. ((save-excursion
  822. (goto-char start)
  823. (when (and
  824. starts-in-newline
  825. (save-excursion
  826. (back-to-indentation)
  827. (looking-at (python-rx block-start))))
  828. (cons
  829. :inside-paren-newline-start-from-block start))))
  830. (starts-in-newline
  831. (cons :inside-paren-newline-start start))
  832. ;; General case.
  833. (t (cons :inside-paren
  834. (save-excursion
  835. (goto-char (1+ start))
  836. (skip-syntax-forward "(" 1)
  837. (skip-syntax-forward " ")
  838. (point))))))))
  839. ;; After backslash.
  840. ((let ((start (when (not (python-syntax-comment-or-string-p ppss))
  841. (python-info-line-ends-backslash-p
  842. (1- (line-number-at-pos))))))
  843. (when start
  844. (cond
  845. ;; Continuation of dotted expression.
  846. ((save-excursion
  847. (back-to-indentation)
  848. (when (eq (char-after) ?\.)
  849. ;; Move point back until it's not inside a paren.
  850. (while (prog2
  851. (forward-line -1)
  852. (and (not (bobp))
  853. (python-syntax-context 'paren))))
  854. (goto-char (line-end-position))
  855. (while (and (search-backward
  856. "." (line-beginning-position) t)
  857. (python-syntax-context-type)))
  858. ;; Ensure previous statement has dot to align with.
  859. (when (and (eq (char-after) ?\.)
  860. (not (python-syntax-context-type)))
  861. (cons :after-backslash-dotted-continuation (point))))))
  862. ;; Continuation of block definition.
  863. ((let ((block-continuation-start
  864. (python-info-block-continuation-line-p)))
  865. (when block-continuation-start
  866. (save-excursion
  867. (goto-char block-continuation-start)
  868. (re-search-forward
  869. (python-rx block-start (* space))
  870. (line-end-position) t)
  871. (cons :after-backslash-block-continuation (point))))))
  872. ;; Continuation of assignment.
  873. ((let ((assignment-continuation-start
  874. (python-info-assignment-continuation-line-p)))
  875. (when assignment-continuation-start
  876. (save-excursion
  877. (goto-char assignment-continuation-start)
  878. (cons :after-backslash-assignment-continuation (point))))))
  879. ;; First line after backslash continuation start.
  880. ((save-excursion
  881. (goto-char start)
  882. (when (or (= (line-number-at-pos) 1)
  883. (not (python-info-beginning-of-backslash
  884. (1- (line-number-at-pos)))))
  885. (cons :after-backslash-first-line start))))
  886. ;; General case.
  887. (t (cons :after-backslash start))))))
  888. ;; After beginning of block.
  889. ((let ((start (save-excursion
  890. (back-to-indentation)
  891. (python-util-forward-comment -1)
  892. (when (equal (char-before) ?:)
  893. (python-nav-beginning-of-block)))))
  894. (when start
  895. (cons :after-block-start start))))
  896. ;; At dedenter statement.
  897. ((let ((start (python-info-dedenter-statement-p)))
  898. (when start
  899. (cons :at-dedenter-block-start start))))
  900. ;; After normal line, comment or ender (default case).
  901. ((save-excursion
  902. (back-to-indentation)
  903. (skip-chars-backward " \t\n")
  904. (if (bobp)
  905. (cons :no-indent 0)
  906. (python-nav-beginning-of-statement)
  907. (cons
  908. (cond ((python-info-current-line-comment-p)
  909. :after-comment)
  910. ((save-excursion
  911. (goto-char (line-end-position))
  912. (python-util-forward-comment -1)
  913. (python-nav-beginning-of-statement)
  914. (looking-at (python-rx block-ender)))
  915. :after-block-end)
  916. (t :after-line))
  917. (point)))))))))
  918. (defun python-indent--calculate-indentation ()
  919. "Internal implementation of `python-indent-calculate-indentation'.
  920. May return an integer for the maximum possible indentation at
  921. current context or a list of integers. The latter case is only
  922. happening for :at-dedenter-block-start context since the
  923. possibilities can be narrowed to specific indentation points."
  924. (save-restriction
  925. (prog-widen)
  926. (save-excursion
  927. (pcase (python-indent-context)
  928. (`(:no-indent . ,_) (prog-first-column)) ; usually 0
  929. (`(,(or :after-line
  930. :after-comment
  931. :inside-string
  932. :after-backslash
  933. :inside-paren-at-closing-paren
  934. :inside-paren-at-closing-nested-paren) . ,start)
  935. ;; Copy previous indentation.
  936. (goto-char start)
  937. (current-indentation))
  938. (`(:inside-docstring . ,start)
  939. (let* ((line-indentation (current-indentation))
  940. (base-indent (progn
  941. (goto-char start)
  942. (current-indentation))))
  943. (max line-indentation base-indent)))
  944. (`(,(or :after-block-start
  945. :after-backslash-first-line
  946. :inside-paren-newline-start) . ,start)
  947. ;; Add one indentation level.
  948. (goto-char start)
  949. (+ (current-indentation) python-indent-offset))
  950. (`(,(or :inside-paren
  951. :after-backslash-block-continuation
  952. :after-backslash-assignment-continuation
  953. :after-backslash-dotted-continuation) . ,start)
  954. ;; Use the column given by the context.
  955. (goto-char start)
  956. (current-column))
  957. (`(:after-block-end . ,start)
  958. ;; Subtract one indentation level.
  959. (goto-char start)
  960. (- (current-indentation) python-indent-offset))
  961. (`(:at-dedenter-block-start . ,_)
  962. ;; List all possible indentation levels from opening blocks.
  963. (let ((opening-block-start-points
  964. (python-info-dedenter-opening-block-positions)))
  965. (if (not opening-block-start-points)
  966. (prog-first-column) ; if not found default to first column
  967. (mapcar (lambda (pos)
  968. (save-excursion
  969. (goto-char pos)
  970. (current-indentation)))
  971. opening-block-start-points))))
  972. (`(,(or :inside-paren-newline-start-from-block) . ,start)
  973. ;; Add two indentation levels to make the suite stand out.
  974. (goto-char start)
  975. (+ (current-indentation) (* python-indent-offset 2)))))))
  976. (defun python-indent--calculate-levels (indentation)
  977. "Calculate levels list given INDENTATION.
  978. Argument INDENTATION can either be an integer or a list of
  979. integers. Levels are returned in ascending order, and in the
  980. case INDENTATION is a list, this order is enforced."
  981. (if (listp indentation)
  982. (sort (copy-sequence indentation) #'<)
  983. (nconc (number-sequence (prog-first-column) (1- indentation)
  984. python-indent-offset)
  985. (list indentation))))
  986. (defun python-indent--previous-level (levels indentation)
  987. "Return previous level from LEVELS relative to INDENTATION."
  988. (let* ((levels (sort (copy-sequence levels) #'>))
  989. (default (car levels)))
  990. (catch 'return
  991. (dolist (level levels)
  992. (when (funcall #'< level indentation)
  993. (throw 'return level)))
  994. default)))
  995. (defun python-indent-calculate-indentation (&optional previous)
  996. "Calculate indentation.
  997. Get indentation of PREVIOUS level when argument is non-nil.
  998. Return the max level of the cycle when indentation reaches the
  999. minimum."
  1000. (let* ((indentation (python-indent--calculate-indentation))
  1001. (levels (python-indent--calculate-levels indentation)))
  1002. (if previous
  1003. (python-indent--previous-level levels (current-indentation))
  1004. (if levels
  1005. (apply #'max levels)
  1006. (prog-first-column)))))
  1007. (defun python-indent-line (&optional previous)
  1008. "Internal implementation of `python-indent-line-function'.
  1009. Use the PREVIOUS level when argument is non-nil, otherwise indent
  1010. to the maximum available level. When indentation is the minimum
  1011. possible and PREVIOUS is non-nil, cycle back to the maximum
  1012. level."
  1013. (let ((follow-indentation-p
  1014. ;; Check if point is within indentation.
  1015. (and (<= (line-beginning-position) (point))
  1016. (>= (+ (line-beginning-position)
  1017. (current-indentation))
  1018. (point)))))
  1019. (save-excursion
  1020. (indent-line-to
  1021. (python-indent-calculate-indentation previous))
  1022. (python-info-dedenter-opening-block-message))
  1023. (when follow-indentation-p
  1024. (back-to-indentation))))
  1025. (defun python-indent-calculate-levels ()
  1026. "Return possible indentation levels."
  1027. (python-indent--calculate-levels
  1028. (python-indent--calculate-indentation)))
  1029. (defun python-indent-line-function ()
  1030. "`indent-line-function' for Python mode.
  1031. When the variable `last-command' is equal to one of the symbols
  1032. inside `python-indent-trigger-commands' it cycles possible
  1033. indentation levels from right to left."
  1034. (python-indent-line
  1035. (and (memq this-command python-indent-trigger-commands)
  1036. (eq last-command this-command))))
  1037. (defun python-indent-dedent-line ()
  1038. "De-indent current line."
  1039. (interactive "*")
  1040. (when (and (not (bolp))
  1041. (not (python-syntax-comment-or-string-p))
  1042. (= (current-indentation) (current-column)))
  1043. (python-indent-line t)
  1044. t))
  1045. (defun python-indent-dedent-line-backspace (arg)
  1046. "De-indent current line.
  1047. Argument ARG is passed to `backward-delete-char-untabify' when
  1048. point is not in between the indentation."
  1049. (interactive "*p")
  1050. (unless (python-indent-dedent-line)
  1051. (backward-delete-char-untabify arg)))
  1052. (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
  1053. (defun python-indent-region (start end)
  1054. "Indent a Python region automagically.
  1055. Called from a program, START and END specify the region to indent."
  1056. (let ((deactivate-mark nil))
  1057. (save-excursion
  1058. (goto-char end)
  1059. (setq end (point-marker))
  1060. (goto-char start)
  1061. (or (bolp) (forward-line 1))
  1062. (while (< (point) end)
  1063. (or (and (bolp) (eolp))
  1064. (when (and
  1065. ;; Skip if previous line is empty or a comment.
  1066. (save-excursion
  1067. (let ((line-is-comment-p
  1068. (python-info-current-line-comment-p)))
  1069. (forward-line -1)
  1070. (not
  1071. (or (and (python-info-current-line-comment-p)
  1072. ;; Unless this line is a comment too.
  1073. (not line-is-comment-p))
  1074. (python-info-current-line-empty-p)))))
  1075. ;; Don't mess with strings, unless it's the
  1076. ;; enclosing set of quotes or a docstring.
  1077. (or (not (python-syntax-context 'string))
  1078. (eq
  1079. (syntax-after
  1080. (+ (1- (point))
  1081. (current-indentation)
  1082. (python-syntax-count-quotes (char-after) (point))))
  1083. (string-to-syntax "|"))
  1084. (python-info-docstring-p))
  1085. ;; Skip if current line is a block start, a
  1086. ;; dedenter or block ender.
  1087. (save-excursion
  1088. (back-to-indentation)
  1089. (not (looking-at
  1090. (python-rx
  1091. (or block-start dedenter block-ender))))))
  1092. (python-indent-line)))
  1093. (forward-line 1))
  1094. (move-marker end nil))))
  1095. (defun python-indent-shift-left (start end &optional count)
  1096. "Shift lines contained in region START END by COUNT columns to the left.
  1097. COUNT defaults to `python-indent-offset'. If region isn't
  1098. active, the current line is shifted. The shifted region includes
  1099. the lines in which START and END lie. An error is signaled if
  1100. any lines in the region are indented less than COUNT columns."
  1101. (interactive
  1102. (if mark-active
  1103. (list (region-beginning) (region-end) current-prefix-arg)
  1104. (list (line-beginning-position) (line-end-position) current-prefix-arg)))
  1105. (if count
  1106. (setq count (prefix-numeric-value count))
  1107. (setq count python-indent-offset))
  1108. (when (> count 0)
  1109. (let ((deactivate-mark nil))
  1110. (save-excursion
  1111. (goto-char start)
  1112. (while (< (point) end)
  1113. (if (and (< (current-indentation) count)
  1114. (not (looking-at "[ \t]*$")))
  1115. (user-error "Can't shift all lines enough"))
  1116. (forward-line))
  1117. (indent-rigidly start end (- count))))))
  1118. (defun python-indent-shift-right (start end &optional count)
  1119. "Shift lines contained in region START END by COUNT columns to the right.
  1120. COUNT defaults to `python-indent-offset'. If region isn't
  1121. active, the current line is shifted. The shifted region includes
  1122. the lines in which START and END lie."
  1123. (interactive
  1124. (if mark-active
  1125. (list (region-beginning) (region-end) current-prefix-arg)
  1126. (list (line-beginning-position) (line-end-position) current-prefix-arg)))
  1127. (let ((deactivate-mark nil))
  1128. (setq count (if count (prefix-numeric-value count)
  1129. python-indent-offset))
  1130. (indent-rigidly start end count)))
  1131. (defun python-indent-post-self-insert-function ()
  1132. "Adjust indentation after insertion of some characters.
  1133. This function is intended to be added to `post-self-insert-hook.'
  1134. If a line renders a paren alone, after adding a char before it,
  1135. the line will be re-indented automatically if needed."
  1136. (when (and electric-indent-mode
  1137. (eq (char-before) last-command-event))
  1138. (cond
  1139. ;; Electric indent inside parens
  1140. ((and
  1141. (not (bolp))
  1142. (let ((paren-start (python-syntax-context 'paren)))
  1143. ;; Check that point is inside parens.
  1144. (when paren-start
  1145. (not
  1146. ;; Filter the case where input is happening in the same
  1147. ;; line where the open paren is.
  1148. (= (line-number-at-pos)
  1149. (line-number-at-pos paren-start)))))
  1150. ;; When content has been added before the closing paren or a
  1151. ;; comma has been inserted, it's ok to do the trick.
  1152. (or
  1153. (memq (char-after) '(?\) ?\] ?\}))
  1154. (eq (char-before) ?,)))
  1155. (save-excursion
  1156. (goto-char (line-beginning-position))
  1157. (let ((indentation (python-indent-calculate-indentation)))
  1158. (when (and (numberp indentation) (< (current-indentation) indentation))
  1159. (indent-line-to indentation)))))
  1160. ;; Electric colon
  1161. ((and (eq ?: last-command-event)
  1162. (memq ?: electric-indent-chars)
  1163. (not current-prefix-arg)
  1164. ;; Trigger electric colon only at end of line
  1165. (eolp)
  1166. ;; Avoid re-indenting on extra colon
  1167. (not (equal ?: (char-before (1- (point)))))
  1168. (not (python-syntax-comment-or-string-p)))
  1169. ;; Just re-indent dedenters
  1170. (let ((dedenter-pos (python-info-dedenter-statement-p))
  1171. (current-pos (point)))
  1172. (when dedenter-pos
  1173. (save-excursion
  1174. (goto-char dedenter-pos)
  1175. (python-indent-line)
  1176. (unless (= (line-number-at-pos dedenter-pos)
  1177. (line-number-at-pos current-pos))
  1178. ;; Reindent region if this is a multiline statement
  1179. (python-indent-region dedenter-pos current-pos)))))))))
  1180. ;;; Mark
  1181. (defun python-mark-defun (&optional allow-extend)
  1182. "Put mark at end of this defun, point at beginning.
  1183. The defun marked is the one that contains point or follows point.
  1184. Interactively (or with ALLOW-EXTEND non-nil), if this command is
  1185. repeated or (in Transient Mark mode) if the mark is active, it
  1186. marks the next defun after the ones already marked."
  1187. (interactive "p")
  1188. (when (python-info-looking-at-beginning-of-defun)
  1189. (end-of-line 1))
  1190. (mark-defun allow-extend))
  1191. ;;; Navigation
  1192. (defvar python-nav-beginning-of-defun-regexp
  1193. (python-rx line-start (* space) defun (+ space) (group symbol-name))
  1194. "Regexp matching class or function definition.
  1195. The name of the defun should be grouped so it can be retrieved
  1196. via `match-string'.")
  1197. (defun python-nav--beginning-of-defun (&optional arg)
  1198. "Internal implementation of `python-nav-beginning-of-defun'.
  1199. With positive ARG search backwards, else search forwards."
  1200. (when (or (null arg) (= arg 0)) (setq arg 1))
  1201. (let* ((re-search-fn (if (> arg 0)
  1202. #'re-search-backward
  1203. #'re-search-forward))
  1204. (line-beg-pos (line-beginning-position))
  1205. (line-content-start (+ line-beg-pos (current-indentation)))
  1206. (pos (point-marker))
  1207. (beg-indentation
  1208. (and (> arg 0)
  1209. (save-excursion
  1210. (while (and
  1211. (not (python-info-looking-at-beginning-of-defun))
  1212. (python-nav-backward-block)))
  1213. (or (and (python-info-looking-at-beginning-of-defun)
  1214. (+ (current-indentation) python-indent-offset))
  1215. 0))))
  1216. (found
  1217. (progn
  1218. (when (and (< arg 0)
  1219. (python-info-looking-at-beginning-of-defun))
  1220. (end-of-line 1))
  1221. (while (and (funcall re-search-fn
  1222. python-nav-beginning-of-defun-regexp nil t)
  1223. (or (python-syntax-context-type)
  1224. ;; Handle nested defuns when moving
  1225. ;; backwards by checking indentation.
  1226. (and (> arg 0)
  1227. (not (= (current-indentation) 0))
  1228. (>= (current-indentation) beg-indentation)))))
  1229. (and (python-info-looking-at-beginning-of-defun)
  1230. (or (not (= (line-number-at-pos pos)
  1231. (line-number-at-pos)))
  1232. (and (>= (point) line-beg-pos)
  1233. (<= (point) line-content-start)
  1234. (> pos line-content-start)))))))
  1235. (if found
  1236. (or (beginning-of-line 1) t)
  1237. (and (goto-char pos) nil))))
  1238. (defun python-nav-beginning-of-defun (&optional arg)
  1239. "Move point to `beginning-of-defun'.
  1240. With positive ARG search backwards else search forward.
  1241. ARG nil or 0 defaults to 1. When searching backwards,
  1242. nested defuns are handled with care depending on current
  1243. point position. Return non-nil if point is moved to
  1244. `beginning-of-defun'."
  1245. (when (or (null arg) (= arg 0)) (setq arg 1))
  1246. (let ((found))
  1247. (while (and (not (= arg 0))
  1248. (let ((keep-searching-p
  1249. (python-nav--beginning-of-defun arg)))
  1250. (when (and keep-searching-p (null found))
  1251. (setq found t))
  1252. keep-searching-p))
  1253. (setq arg (if (> arg 0) (1- arg) (1+ arg))))
  1254. found))
  1255. (defun python-nav-end-of-defun ()
  1256. "Move point to the end of def or class.
  1257. Returns nil if point is not in a def or class."
  1258. (interactive)
  1259. (let ((beg-defun-indent)
  1260. (beg-pos (point)))
  1261. (when (or (python-info-looking-at-beginning-of-defun)
  1262. (python-nav-beginning-of-defun 1)
  1263. (python-nav-beginning-of-defun -1))
  1264. (setq beg-defun-indent (current-indentation))
  1265. (while (progn
  1266. (python-nav-end-of-statement)
  1267. (python-util-forward-comment 1)
  1268. (and (> (current-indentation) beg-defun-indent)
  1269. (not (eobp)))))
  1270. (python-util-forward-comment -1)
  1271. (forward-line 1)
  1272. ;; Ensure point moves forward.
  1273. (and (> beg-pos (point)) (goto-char beg-pos)))))
  1274. (defun python-nav--syntactically (fn poscompfn &optional contextfn)
  1275. "Move point using FN avoiding places with specific context.
  1276. FN must take no arguments. POSCOMPFN is a two arguments function
  1277. used to compare current and previous point after it is moved
  1278. using FN, this is normally a less-than or greater-than
  1279. comparison. Optional argument CONTEXTFN defaults to
  1280. `python-syntax-context-type' and is used for checking current
  1281. point context, it must return a non-nil value if this point must
  1282. be skipped."
  1283. (let ((contextfn (or contextfn 'python-syntax-context-type))
  1284. (start-pos (point-marker))
  1285. (prev-pos))
  1286. (catch 'found
  1287. (while t
  1288. (let* ((newpos
  1289. (and (funcall fn) (point-marker)))
  1290. (context (funcall contextfn)))
  1291. (cond ((and (not context) newpos
  1292. (or (and (not prev-pos) newpos)
  1293. (and prev-pos newpos
  1294. (funcall poscompfn newpos prev-pos))))
  1295. (throw 'found (point-marker)))
  1296. ((and newpos context)
  1297. (setq prev-pos (point)))
  1298. (t (when (not newpos) (goto-char start-pos))
  1299. (throw 'found nil))))))))
  1300. (defun python-nav--forward-defun (arg)
  1301. "Internal implementation of python-nav-{backward,forward}-defun.
  1302. Uses ARG to define which function to call, and how many times
  1303. repeat it."
  1304. (let ((found))
  1305. (while (and (> arg 0)
  1306. (setq found
  1307. (python-nav--syntactically
  1308. (lambda ()
  1309. (re-search-forward
  1310. python-nav-beginning-of-defun-regexp nil t))
  1311. '>)))
  1312. (setq arg (1- arg)))
  1313. (while (and (< arg 0)
  1314. (setq found
  1315. (python-nav--syntactically
  1316. (lambda ()
  1317. (re-search-backward
  1318. python-nav-beginning-of-defun-regexp nil t))
  1319. '<)))
  1320. (setq arg (1+ arg)))
  1321. found))
  1322. (defun python-nav-backward-defun (&optional arg)
  1323. "Navigate to closer defun backward ARG times.
  1324. Unlikely `python-nav-beginning-of-defun' this doesn't care about
  1325. nested definitions."
  1326. (interactive "^p")
  1327. (python-nav--forward-defun (- (or arg 1))))
  1328. (defun python-nav-forward-defun (&optional arg)
  1329. "Navigate to closer defun forward ARG times.
  1330. Unlikely `python-nav-beginning-of-defun' this doesn't care about
  1331. nested definitions."
  1332. (interactive "^p")
  1333. (python-nav--forward-defun (or arg 1)))
  1334. (defun python-nav-beginning-of-statement ()
  1335. "Move to start of current statement."
  1336. (interactive "^")
  1337. (back-to-indentation)
  1338. (let* ((ppss (syntax-ppss))
  1339. (context-point
  1340. (or
  1341. (python-syntax-context 'paren ppss)
  1342. (python-syntax-context 'string ppss))))
  1343. (cond ((bobp))
  1344. (context-point
  1345. (goto-char context-point)
  1346. (python-nav-beginning-of-statement))
  1347. ((save-excursion
  1348. (forward-line -1)
  1349. (python-info-line-ends-backslash-p))
  1350. (forward-line -1)
  1351. (python-nav-beginning-of-statement))))
  1352. (point-marker))
  1353. (defun python-nav-end-of-statement (&optional noend)
  1354. "Move to end of current statement.
  1355. Optional argument NOEND is internal and makes the logic to not
  1356. jump to the end of line when moving forward searching for the end
  1357. of the statement."
  1358. (interactive "^")
  1359. (let (string-start bs-pos)
  1360. (while (and (or noend (goto-char (line-end-position)))
  1361. (not (eobp))
  1362. (cond ((setq string-start (python-syntax-context 'string))
  1363. (goto-char string-start)
  1364. (if (python-syntax-context 'paren)
  1365. ;; Ended up inside a paren, roll again.
  1366. (python-nav-end-of-statement t)
  1367. ;; This is not inside a paren, move to the
  1368. ;; end of this string.
  1369. (goto-char (+ (point)
  1370. (python-syntax-count-quotes
  1371. (char-after (point)) (point))))
  1372. (or (re-search-forward (rx (syntax string-delimiter)) nil t)
  1373. (goto-char (point-max)))))
  1374. ((python-syntax-context 'paren)
  1375. ;; The statement won't end before we've escaped
  1376. ;; at least one level of parenthesis.
  1377. (condition-case err
  1378. (goto-char (scan-lists (point) 1 -1))
  1379. (scan-error (goto-char (nth 3 err)))))
  1380. ((setq bs-pos (python-info-line-ends-backslash-p))
  1381. (goto-char bs-pos)
  1382. (forward-line 1))))))
  1383. (point-marker))
  1384. (defun python-nav-backward-statement (&optional arg)
  1385. "Move backward to previous statement.
  1386. With ARG, repeat. See `python-nav-forward-statement'."
  1387. (interactive "^p")
  1388. (or arg (setq arg 1))
  1389. (python-nav-forward-statement (- arg)))
  1390. (defun python-nav-forward-statement (&optional arg)
  1391. "Move forward to next statement.
  1392. With ARG, repeat. With negative argument, move ARG times
  1393. backward to previous statement."
  1394. (interactive "^p")
  1395. (or arg (setq arg 1))
  1396. (while (> arg 0)
  1397. (python-nav-end-of-statement)
  1398. (python-util-forward-comment)
  1399. (python-nav-beginning-of-statement)
  1400. (setq arg (1- arg)))
  1401. (while (< arg 0)
  1402. (python-nav-beginning-of-statement)
  1403. (python-util-forward-comment -1)
  1404. (python-nav-beginning-of-statement)
  1405. (setq arg (1+ arg))))
  1406. (defun python-nav-beginning-of-block ()
  1407. "Move to start of current block."
  1408. (interactive "^")
  1409. (let ((starting-pos (point)))
  1410. (if (progn
  1411. (python-nav-beginning-of-statement)
  1412. (looking-at (python-rx block-start)))
  1413. (point-marker)
  1414. ;; Go to first line beginning a statement
  1415. (while (and (not (bobp))
  1416. (or (and (python-nav-beginning-of-statement) nil)
  1417. (python-info-current-line-comment-p)
  1418. (python-info-current-line-empty-p)))
  1419. (forward-line -1))
  1420. (let ((block-matching-indent
  1421. (- (current-indentation) python-indent-offset)))
  1422. (while
  1423. (and (python-nav-backward-block)
  1424. (> (current-indentation) block-matching-indent)))
  1425. (if (and (looking-at (python-rx block-start))
  1426. (= (current-indentation) block-matching-indent))
  1427. (point-marker)
  1428. (and (goto-char starting-pos) nil))))))
  1429. (defun python-nav-end-of-block ()
  1430. "Move to end of current block."
  1431. (interactive "^")
  1432. (when (python-nav-beginning-of-block)
  1433. (let ((block-indentation (current-indentation)))
  1434. (python-nav-end-of-statement)
  1435. (while (and (forward-line 1)
  1436. (not (eobp))
  1437. (or (and (> (current-indentation) block-indentation)
  1438. (or (python-nav-end-of-statement) t))
  1439. (python-info-current-line-comment-p)
  1440. (python-info-current-line-empty-p))))
  1441. (python-util-forward-comment -1)
  1442. (point-marker))))
  1443. (defun python-nav-backward-block (&optional arg)
  1444. "Move backward to previous block of code.
  1445. With ARG, repeat. See `python-nav-forward-block'."
  1446. (interactive "^p")
  1447. (or arg (setq arg 1))
  1448. (python-nav-forward-block (- arg)))
  1449. (defun python-nav-forward-block (&optional arg)
  1450. "Move forward to next block of code.
  1451. With ARG, repeat. With negative argument, move ARG times
  1452. backward to previous block."
  1453. (interactive "^p")
  1454. (or arg (setq arg 1))
  1455. (let ((block-start-regexp
  1456. (python-rx line-start (* whitespace) block-start))
  1457. (starting-pos (point)))
  1458. (while (> arg 0)
  1459. (python-nav-end-of-statement)
  1460. (while (and
  1461. (re-search-forward block-start-regexp nil t)
  1462. (python-syntax-context-type)))
  1463. (setq arg (1- arg)))
  1464. (while (< arg 0)
  1465. (python-nav-beginning-of-statement)
  1466. (while (and
  1467. (re-search-backward block-start-regexp nil t)
  1468. (python-syntax-context-type)))
  1469. (setq arg (1+ arg)))
  1470. (python-nav-beginning-of-statement)
  1471. (if (not (looking-at (python-rx block-start)))
  1472. (and (goto-char starting-pos) nil)
  1473. (and (not (= (point) starting-pos)) (point-marker)))))
  1474. (defun python-nav--lisp-forward-sexp (&optional arg)
  1475. "Standard version `forward-sexp'.
  1476. It ignores completely the value of `forward-sexp-function' by
  1477. setting it to nil before calling `forward-sexp'. With positive
  1478. ARG move forward only one sexp, else move backwards."
  1479. (let ((forward-sexp-function)
  1480. (arg (if (or (not arg) (> arg 0)) 1 -1)))
  1481. (forward-sexp arg)))
  1482. (defun python-nav--lisp-forward-sexp-safe (&optional arg)
  1483. "Safe version of standard `forward-sexp'.
  1484. When at end of sexp (i.e. looking at a opening/closing paren)
  1485. skips it instead of throwing an error. With positive ARG move
  1486. forward only one sexp, else move backwards."
  1487. (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
  1488. (paren-regexp
  1489. (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
  1490. (search-fn
  1491. (if (> arg 0) #'re-search-forward #'re-search-backward)))
  1492. (condition-case nil
  1493. (python-nav--lisp-forward-sexp arg)
  1494. (error
  1495. (while (and (funcall search-fn paren-regexp nil t)
  1496. (python-syntax-context 'paren)))))))
  1497. (defun python-nav--forward-sexp (&optional dir safe skip-parens-p)
  1498. "Move to forward sexp.
  1499. With positive optional argument DIR direction move forward, else
  1500. backwards. When optional argument SAFE is non-nil do not throw
  1501. errors when at end of sexp, skip it instead. With optional
  1502. argument SKIP-PARENS-P force sexp motion to ignore parenthesized
  1503. expressions when looking at them in either direction."
  1504. (setq dir (or dir 1))
  1505. (unless (= dir 0)
  1506. (let* ((forward-p (if (> dir 0)
  1507. (and (setq dir 1) t)
  1508. (and (setq dir -1) nil)))
  1509. (context-type (python-syntax-context-type)))
  1510. (cond
  1511. ((memq context-type '(string comment))
  1512. ;; Inside of a string, get out of it.
  1513. (let ((forward-sexp-function))
  1514. (forward-sexp dir)))
  1515. ((and (not skip-parens-p)
  1516. (or (eq context-type 'paren)
  1517. (if forward-p
  1518. (eq (syntax-class (syntax-after (point)))
  1519. (car (string-to-syntax "(")))
  1520. (eq (syntax-class (syntax-after (1- (point))))
  1521. (car (string-to-syntax ")"))))))
  1522. ;; Inside a paren or looking at it, lisp knows what to do.
  1523. (if safe
  1524. (python-nav--lisp-forward-sexp-safe dir)
  1525. (python-nav--lisp-forward-sexp dir)))
  1526. (t
  1527. ;; This part handles the lispy feel of
  1528. ;; `python-nav-forward-sexp'. Knowing everything about the
  1529. ;; current context and the context of the next sexp tries to
  1530. ;; follow the lisp sexp motion commands in a symmetric manner.
  1531. (let* ((context
  1532. (cond
  1533. ((python-info-beginning-of-block-p) 'block-start)
  1534. ((python-info-end-of-block-p) 'block-end)
  1535. ((python-info-beginning-of-statement-p) 'statement-start)
  1536. ((python-info-end-of-statement-p) 'statement-end)))
  1537. (next-sexp-pos
  1538. (save-excursion
  1539. (if safe
  1540. (python-nav--lisp-forward-sexp-safe dir)
  1541. (python-nav--lisp-forward-sexp dir))
  1542. (point)))
  1543. (next-sexp-context
  1544. (save-excursion
  1545. (goto-char next-sexp-pos)
  1546. (cond
  1547. ((python-info-beginning-of-block-p) 'block-start)
  1548. ((python-info-end-of-block-p) 'block-end)
  1549. ((python-info-beginning-of-statement-p) 'statement-start)
  1550. ((python-info-end-of-statement-p) 'statement-end)
  1551. ((python-info-statement-starts-block-p) 'starts-block)
  1552. ((python-info-statement-ends-block-p) 'ends-block)))))
  1553. (if forward-p
  1554. (cond ((and (not (eobp))
  1555. (python-info-current-line-empty-p))
  1556. (python-util-forward-comment dir)
  1557. (python-nav--forward-sexp dir safe skip-parens-p))
  1558. ((eq context 'block-start)
  1559. (python-nav-end-of-block))
  1560. ((eq context 'statement-start)
  1561. (python-nav-end-of-statement))
  1562. ((and (memq context '(statement-end block-end))
  1563. (eq next-sexp-context 'ends-block))
  1564. (goto-char next-sexp-pos)
  1565. (python-nav-end-of-block))
  1566. ((and (memq context '(statement-end block-end))
  1567. (eq next-sexp-context 'starts-block))
  1568. (goto-char next-sexp-pos)
  1569. (python-nav-end-of-block))
  1570. ((memq context '(statement-end block-end))
  1571. (goto-char next-sexp-pos)
  1572. (python-nav-end-of-statement))
  1573. (t (goto-char next-sexp-pos)))
  1574. (cond ((and (not (bobp))
  1575. (python-info-current-line-empty-p))
  1576. (python-util-forward-comment dir)
  1577. (python-nav--forward-sexp dir safe skip-parens-p))
  1578. ((eq context 'block-end)
  1579. (python-nav-beginning-of-block))
  1580. ((eq context 'statement-end)
  1581. (python-nav-beginning-of-statement))
  1582. ((and (memq context '(statement-start block-start))
  1583. (eq next-sexp-context 'starts-block))
  1584. (goto-char next-sexp-pos)
  1585. (python-nav-beginning-of-block))
  1586. ((and (memq context '(statement-start block-start))
  1587. (eq next-sexp-context 'ends-block))
  1588. (goto-char next-sexp-pos)
  1589. (python-nav-beginning-of-block))
  1590. ((memq context '(statement-start block-start))
  1591. (goto-char next-sexp-pos)
  1592. (python-nav-beginning-of-statement))
  1593. (t (goto-char next-sexp-pos))))))))))
  1594. (defun python-nav-forward-sexp (&optional arg safe skip-parens-p)
  1595. "Move forward across expressions.
  1596. With ARG, do it that many times. Negative arg -N means move
  1597. backward N times. When optional argument SAFE is non-nil do not
  1598. throw errors when at end of sexp, skip it instead. With optional
  1599. argument SKIP-PARENS-P force sexp motion to ignore parenthesized
  1600. expressions when looking at them in either direction (forced to t
  1601. in interactive calls)."
  1602. (interactive "^p")
  1603. (or arg (setq arg 1))
  1604. ;; Do not follow parens on interactive calls. This hack to detect
  1605. ;; if the function was called interactively copes with the way
  1606. ;; `forward-sexp' works by calling `forward-sexp-function', losing
  1607. ;; interactive detection by checking `current-prefix-arg'. The
  1608. ;; reason to make this distinction is that lisp functions like
  1609. ;; `blink-matching-open' get confused causing issues like the one in
  1610. ;; Bug#16191. With this approach the user gets a symmetric behavior
  1611. ;; when working interactively while called functions expecting
  1612. ;; paren-based sexp motion work just fine.
  1613. (or
  1614. skip-parens-p
  1615. (setq skip-parens-p
  1616. (memq real-this-command
  1617. (list
  1618. #'forward-sexp #'backward-sexp
  1619. #'python-nav-forward-sexp #'python-nav-backward-sexp
  1620. #'python-nav-forward-sexp-safe #'python-nav-backward-sexp))))
  1621. (while (> arg 0)
  1622. (python-nav--forward-sexp 1 safe skip-parens-p)
  1623. (setq arg (1- arg)))
  1624. (while (< arg 0)
  1625. (python-nav--forward-sexp -1 safe skip-parens-p)
  1626. (setq arg (1+ arg))))
  1627. (defun python-nav-backward-sexp (&optional arg safe skip-parens-p)
  1628. "Move backward across expressions.
  1629. With ARG, do it that many times. Negative arg -N means move
  1630. forward N times. When optional argument SAFE is non-nil do not
  1631. throw errors when at end of sexp, skip it instead. With optional
  1632. argument SKIP-PARENS-P force sexp motion to ignore parenthesized
  1633. expressions when looking at them in either direction (forced to t
  1634. in interactive calls)."
  1635. (interactive "^p")
  1636. (or arg (setq arg 1))
  1637. (python-nav-forward-sexp (- arg) safe skip-parens-p))
  1638. (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p)
  1639. "Move forward safely across expressions.
  1640. With ARG, do it that many times. Negative arg -N means move
  1641. backward N times. With optional argument SKIP-PARENS-P force
  1642. sexp motion to ignore parenthesized expressions when looking at
  1643. them in either direction (forced to t in interactive calls)."
  1644. (interactive "^p")
  1645. (python-nav-forward-sexp arg t skip-parens-p))
  1646. (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p)
  1647. "Move backward safely across expressions.
  1648. With ARG, do it that many times. Negative arg -N means move
  1649. forward N times. With optional argument SKIP-PARENS-P force sexp
  1650. motion to ignore parenthesized expressions when looking at them in
  1651. either direction (forced to t in interactive calls)."
  1652. (interactive "^p")
  1653. (python-nav-backward-sexp arg t skip-parens-p))
  1654. (defun python-nav--up-list (&optional dir)
  1655. "Internal implementation of `python-nav-up-list'.
  1656. DIR is always 1 or -1 and comes sanitized from
  1657. `python-nav-up-list' calls."
  1658. (let ((context (python-syntax-context-type))
  1659. (forward-p (> dir 0)))
  1660. (cond
  1661. ((memq context '(string comment)))
  1662. ((eq context 'paren)
  1663. (let ((forward-sexp-function))
  1664. (up-list dir)))
  1665. ((and forward-p (python-info-end-of-block-p))
  1666. (let ((parent-end-pos
  1667. (save-excursion
  1668. (let ((indentation (and
  1669. (python-nav-beginning-of-block)
  1670. (current-indentation))))
  1671. (while (and indentation
  1672. (> indentation 0)
  1673. (>= (current-indentation) indentation)
  1674. (python-nav-backward-block)))
  1675. (python-nav-end-of-block)))))
  1676. (and (> (or parent-end-pos (point)) (point))
  1677. (goto-char parent-end-pos))))
  1678. (forward-p (python-nav-end-of-block))
  1679. ((and (not forward-p)
  1680. (> (current-indentation) 0)
  1681. (python-info-beginning-of-block-p))
  1682. (let ((prev-block-pos
  1683. (save-excursion
  1684. (let ((indentation (current-indentation)))
  1685. (while (and (python-nav-backward-block)
  1686. (>= (current-indentation) indentation))))
  1687. (point))))
  1688. (and (> (point) prev-block-pos)
  1689. (goto-char prev-block-pos))))
  1690. ((not forward-p) (python-nav-beginning-of-block)))))
  1691. (defun python-nav-up-list (&optional arg)
  1692. "Move forward out of one level of parentheses (or blocks).
  1693. With ARG, do this that many times.
  1694. A negative argument means move backward but still to a less deep spot.
  1695. This command assumes point is not in a string or comment."
  1696. (interactive "^p")
  1697. (or arg (setq arg 1))
  1698. (while (> arg 0)
  1699. (python-nav--up-list 1)
  1700. (setq arg (1- arg)))
  1701. (while (< arg 0)
  1702. (python-nav--up-list -1)
  1703. (setq arg (1+ arg))))
  1704. (defun python-nav-backward-up-list (&optional arg)
  1705. "Move backward out of one level of parentheses (or blocks).
  1706. With ARG, do this that many times.
  1707. A negative argument means move forward but still to a less deep spot.
  1708. This command assumes point is not in a string or comment."
  1709. (interactive "^p")
  1710. (or arg (setq arg 1))
  1711. (python-nav-up-list (- arg)))
  1712. (defun python-nav-if-name-main ()
  1713. "Move point at the beginning the __main__ block.
  1714. When \"if __name__ == \\='__main__\\=':\" is found returns its
  1715. position, else returns nil."
  1716. (interactive)
  1717. (let ((point (point))
  1718. (found (catch 'found
  1719. (goto-char (point-min))
  1720. (while (re-search-forward
  1721. (python-rx line-start
  1722. "if" (+ space)
  1723. "__name__" (+ space)
  1724. "==" (+ space)
  1725. (group-n 1 (or ?\" ?\'))
  1726. "__main__" (backref 1) (* space) ":")
  1727. nil t)
  1728. (when (not (python-syntax-context-type))
  1729. (beginning-of-line)
  1730. (throw 'found t))))))
  1731. (if found
  1732. (point)
  1733. (ignore (goto-char point)))))
  1734. ;;; Shell integration
  1735. (defcustom python-shell-buffer-name "Python"
  1736. "Default buffer name for Python interpreter."
  1737. :type 'string
  1738. :group 'python
  1739. :safe 'stringp)
  1740. (defcustom python-shell-interpreter "python"
  1741. "Default Python interpreter for shell."
  1742. :type 'string
  1743. :group 'python)
  1744. (defcustom python-shell-internal-buffer-name "Python Internal"
  1745. "Default buffer name for the Internal Python interpreter."
  1746. :type 'string
  1747. :group 'python
  1748. :safe 'stringp)
  1749. (defcustom python-shell-interpreter-args "-i"
  1750. "Default arguments for the Python interpreter."
  1751. :type 'string
  1752. :group 'python)
  1753. (defcustom python-shell-interpreter-interactive-arg "-i"
  1754. "Interpreter argument to force it to run interactively."
  1755. :type 'string
  1756. :version "24.4")
  1757. (defcustom python-shell-prompt-detect-enabled t
  1758. "Non-nil enables autodetection of interpreter prompts."
  1759. :type 'boolean
  1760. :safe 'booleanp
  1761. :version "24.4")
  1762. (defcustom python-shell-prompt-detect-failure-warning t
  1763. "Non-nil enables warnings when detection of prompts fail."
  1764. :type 'boolean
  1765. :safe 'booleanp
  1766. :version "24.4")
  1767. (defcustom python-shell-prompt-input-regexps
  1768. '(">>> " "\\.\\.\\. " ; Python
  1769. "In \\[[0-9]+\\]: " ; IPython
  1770. " \\.\\.\\.: " ; IPython
  1771. ;; Using ipdb outside IPython may fail to cleanup and leave static
  1772. ;; IPython prompts activated, this adds some safeguard for that.
  1773. "In : " "\\.\\.\\.: ")
  1774. "List of regular expressions matching input prompts."
  1775. :type '(repeat string)
  1776. :version "24.4")
  1777. (defcustom python-shell-prompt-output-regexps
  1778. '("" ; Python
  1779. "Out\\[[0-9]+\\]: " ; IPython
  1780. "Out :") ; ipdb safeguard
  1781. "List of regular expressions matching output prompts."
  1782. :type '(repeat string)
  1783. :version "24.4")
  1784. (defcustom python-shell-prompt-regexp ">>> "
  1785. "Regular expression matching top level input prompt of Python shell.
  1786. It should not contain a caret (^) at the beginning."
  1787. :type 'string)
  1788. (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
  1789. "Regular expression matching block input prompt of Python shell.
  1790. It should not contain a caret (^) at the beginning."
  1791. :type 'string)
  1792. (defcustom python-shell-prompt-output-regexp ""
  1793. "Regular expression matching output prompt of Python shell.
  1794. It should not contain a caret (^) at the beginning."
  1795. :type 'string)
  1796. (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
  1797. "Regular expression matching pdb input prompt of Python shell.
  1798. It should not contain a caret (^) at the beginning."
  1799. :type 'string)
  1800. (define-obsolete-variable-alias
  1801. 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
  1802. (defcustom python-shell-font-lock-enable t
  1803. "Should syntax highlighting be enabled in the Python shell buffer?
  1804. Restart the Python shell after changing this variable for it to take effect."
  1805. :type 'boolean
  1806. :group 'python
  1807. :safe 'booleanp)
  1808. (defcustom python-shell-unbuffered t
  1809. "Should shell output be unbuffered?.
  1810. When non-nil, this may prevent delayed and missing output in the
  1811. Python shell. See commentary for details."
  1812. :type 'boolean
  1813. :group 'python
  1814. :safe 'booleanp)
  1815. (defcustom python-shell-process-environment nil
  1816. "List of overridden environment variables for subprocesses to inherit.
  1817. Each element should be a string of the form ENVVARNAME=VALUE.
  1818. When this variable is non-nil, values are exported into the
  1819. process environment before starting it. Any variables already
  1820. present in the current environment are superseded by variables
  1821. set here."
  1822. :type '(repeat string)
  1823. :group 'python)
  1824. (defcustom python-shell-extra-pythonpaths nil
  1825. "List of extra pythonpaths for Python shell.
  1826. When this variable is non-nil, values added at the beginning of
  1827. the PYTHONPATH before starting processes. Any values present
  1828. here that already exists in PYTHONPATH are moved to the beginning
  1829. of the list so that they are prioritized when looking for
  1830. modules."
  1831. :type '(repeat string)
  1832. :group 'python)
  1833. (defcustom python-shell-exec-path nil
  1834. "List of paths for searching executables.
  1835. When this variable is non-nil, values added at the beginning of
  1836. the PATH before starting processes. Any values present here that
  1837. already exists in PATH are moved to the beginning of the list so
  1838. that they are prioritized when looking for executables."
  1839. :type '(repeat string)
  1840. :group 'python)
  1841. (defcustom python-shell-remote-exec-path nil
  1842. "List of paths to be ensured remotely for searching executables.
  1843. When this variable is non-nil, values are exported into remote
  1844. hosts PATH before starting processes. Values defined in
  1845. `python-shell-exec-path' will take precedence to paths defined
  1846. here. Normally you wont use this variable directly unless you
  1847. plan to ensure a particular set of paths to all Python shell
  1848. executed through tramp connections."
  1849. :version "25.1"
  1850. :type '(repeat string)
  1851. :group 'python)
  1852. (defcustom python-shell-virtualenv-root nil
  1853. "Path to virtualenv root.
  1854. This variable, when set to a string, makes the environment to be
  1855. modified such that shells are started within the specified
  1856. virtualenv."
  1857. :type '(choice (const nil) string)
  1858. :group 'python)
  1859. (define-obsolete-variable-alias
  1860. 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
  1861. (defcustom python-shell-setup-codes nil
  1862. "List of code run by `python-shell-send-setup-codes'."
  1863. :type '(repeat symbol)
  1864. :group 'python)
  1865. (defcustom python-shell-compilation-regexp-alist
  1866. `((,(rx line-start (1+ (any " \t")) "File \""
  1867. (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
  1868. "\", line " (group (1+ digit)))
  1869. 1 2)
  1870. (,(rx " in file " (group (1+ not-newline)) " on line "
  1871. (group (1+ digit)))
  1872. 1 2)
  1873. (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
  1874. "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
  1875. 1 2))
  1876. "`compilation-error-regexp-alist' for inferior Python."
  1877. :type '(alist string)
  1878. :group 'python)
  1879. (defmacro python-shell--add-to-path-with-priority (pathvar paths)
  1880. "Modify PATHVAR and ensure PATHS are added only once at beginning."
  1881. `(dolist (path (reverse ,paths))
  1882. (cl-delete path ,pathvar :test #'string=)
  1883. (cl-pushnew path ,pathvar :test #'string=)))
  1884. (defun python-shell-calculate-pythonpath ()
  1885. "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
  1886. (let ((pythonpath
  1887. (split-string
  1888. (or (getenv "PYTHONPATH") "") path-separator 'omit)))
  1889. (python-shell--add-to-path-with-priority
  1890. pythonpath python-shell-extra-pythonpaths)
  1891. (mapconcat 'identity pythonpath path-separator)))
  1892. (defun python-shell-calculate-process-environment ()
  1893. "Calculate `process-environment' or `tramp-remote-process-environment'.
  1894. Prepends `python-shell-process-environment', sets extra
  1895. pythonpaths from `python-shell-extra-pythonpaths' and sets a few
  1896. virtualenv related vars. If `default-directory' points to a
  1897. remote host, the returned value is intended for
  1898. `tramp-remote-process-environment'."
  1899. (let* ((remote-p (file-remote-p default-directory))
  1900. (process-environment (if remote-p
  1901. tramp-remote-process-environment
  1902. process-environment))
  1903. (virtualenv (when python-shell-virtualenv-root
  1904. (directory-file-name python-shell-virtualenv-root))))
  1905. (dolist (env python-shell-process-environment)
  1906. (pcase-let ((`(,key ,value) (split-string env "=")))
  1907. (setenv key value)))
  1908. (when python-shell-unbuffered
  1909. (setenv "PYTHONUNBUFFERED" "1"))
  1910. (when python-shell-extra-pythonpaths
  1911. (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
  1912. (if (not virtualenv)
  1913. process-environment
  1914. (setenv "PYTHONHOME" nil)
  1915. (setenv "VIRTUAL_ENV" virtualenv))
  1916. process-environment))
  1917. (defun python-shell-calculate-exec-path ()
  1918. "Calculate `exec-path'.
  1919. Prepends `python-shell-exec-path' and adds the binary directory
  1920. for virtualenv if `python-shell-virtualenv-root' is set. If
  1921. `default-directory' points to a remote host, the returned value
  1922. appends `python-shell-remote-exec-path' instead of `exec-path'."
  1923. (let ((new-path (copy-sequence
  1924. (if (file-remote-p default-directory)
  1925. python-shell-remote-exec-path
  1926. exec-path))))
  1927. (python-shell--add-to-path-with-priority
  1928. new-path python-shell-exec-path)
  1929. (if (not python-shell-virtualenv-root)
  1930. new-path
  1931. (python-shell--add-to-path-with-priority
  1932. new-path
  1933. (list (expand-file-name "bin" python-shell-virtualenv-root)))
  1934. new-path)))
  1935. (defun python-shell-tramp-refresh-remote-path (vec paths)
  1936. "Update VEC's remote-path giving PATHS priority."
  1937. (let ((remote-path (tramp-get-connection-property vec "remote-path" nil)))
  1938. (when remote-path
  1939. (python-shell--add-to-path-with-priority remote-path paths)
  1940. (tramp-set-connection-property vec "remote-path" remote-path)
  1941. (tramp-set-remote-path vec))))
  1942. (defun python-shell-tramp-refresh-process-environment (vec env)
  1943. "Update VEC's process environment with ENV."
  1944. ;; Stolen from `tramp-open-connection-setup-interactive-shell'.
  1945. (let ((env (append (when (fboundp #'tramp-get-remote-locale)
  1946. ;; Emacs<24.4 compat.
  1947. (list (tramp-get-remote-locale vec)))
  1948. (copy-sequence env)))
  1949. (tramp-end-of-heredoc
  1950. (if (boundp 'tramp-end-of-heredoc)
  1951. tramp-end-of-heredoc
  1952. (md5 tramp-end-of-output)))
  1953. unset vars item)
  1954. (while env
  1955. (setq item (split-string (car env) "=" 'omit))
  1956. (setcdr item (mapconcat 'identity (cdr item) "="))
  1957. (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
  1958. (push (format "%s %s" (car item) (cdr item)) vars)
  1959. (push (car item) unset))
  1960. (setq env (cdr env)))
  1961. (when vars
  1962. (tramp-send-command
  1963. vec
  1964. (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
  1965. tramp-end-of-heredoc
  1966. (mapconcat 'identity vars "\n")
  1967. tramp-end-of-heredoc)
  1968. t))
  1969. (when unset
  1970. (tramp-send-command
  1971. vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
  1972. (defmacro python-shell-with-environment (&rest body)
  1973. "Modify shell environment during execution of BODY.
  1974. Temporarily sets `process-environment' and `exec-path' during
  1975. execution of body. If `default-directory' points to a remote
  1976. machine then modifies `tramp-remote-process-environment' and
  1977. `python-shell-remote-exec-path' instead."
  1978. (declare (indent 0) (debug (body)))
  1979. (let ((vec (make-symbol "vec")))
  1980. `(progn
  1981. (let* ((,vec
  1982. (when (file-remote-p default-directory)
  1983. (ignore-errors
  1984. (tramp-dissect-file-name default-directory 'noexpand))))
  1985. (process-environment
  1986. (if ,vec
  1987. process-environment
  1988. (python-shell-calculate-process-environment)))
  1989. (exec-path
  1990. (if ,vec
  1991. exec-path
  1992. (python-shell-calculate-exec-path)))
  1993. (tramp-remote-process-environment
  1994. (if ,vec
  1995. (python-shell-calculate-process-environment)
  1996. tramp-remote-process-environment)))
  1997. (when (tramp-get-connection-process ,vec)
  1998. ;; For already existing connections, the new exec path must
  1999. ;; be re-set, otherwise it won't take effect. One example
  2000. ;; of such case is when remote dir-locals are read and
  2001. ;; *then* subprocesses are triggered within the same
  2002. ;; connection.
  2003. (python-shell-tramp-refresh-remote-path
  2004. ,vec (python-shell-calculate-exec-path))
  2005. ;; The `tramp-remote-process-environment' variable is only
  2006. ;; effective when the started process is an interactive
  2007. ;; shell, otherwise (like in the case of processes started
  2008. ;; with `process-file') the environment is not changed.
  2009. ;; This makes environment modifications effective
  2010. ;; unconditionally.
  2011. (python-shell-tramp-refresh-process-environment
  2012. ,vec tramp-remote-process-environment))
  2013. ,(macroexp-progn body)))))
  2014. (defvar python-shell--prompt-calculated-input-regexp nil
  2015. "Calculated input prompt regexp for inferior python shell.
  2016. Do not set this variable directly, instead use
  2017. `python-shell-prompt-set-calculated-regexps'.")
  2018. (defvar python-shell--prompt-calculated-output-regexp nil
  2019. "Calculated output prompt regexp for inferior python shell.
  2020. Do not set this variable directly, instead use
  2021. `python-shell-set-prompt-regexp'.")
  2022. (defun python-shell-prompt-detect ()
  2023. "Detect prompts for the current `python-shell-interpreter'.
  2024. When prompts can be retrieved successfully from the
  2025. `python-shell-interpreter' run with
  2026. `python-shell-interpreter-interactive-arg', returns a list of
  2027. three elements, where the first two are input prompts and the
  2028. last one is an output prompt. When no prompts can be detected
  2029. and `python-shell-prompt-detect-failure-warning' is non-nil,
  2030. shows a warning with instructions to avoid hangs and returns nil.
  2031. When `python-shell-prompt-detect-enabled' is nil avoids any
  2032. detection and just returns nil."
  2033. (when python-shell-prompt-detect-enabled
  2034. (python-shell-with-environment
  2035. (let* ((code (concat
  2036. "import sys\n"
  2037. "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
  2038. ;; JSON is built manually for compatibility
  2039. "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
  2040. "print (ps_json)\n"
  2041. "sys.exit(0)\n"))
  2042. (interpreter python-shell-interpreter)
  2043. (interpreter-arg python-shell-interpreter-interactive-arg)
  2044. (output
  2045. (with-temp-buffer
  2046. ;; TODO: improve error handling by using
  2047. ;; `condition-case' and displaying the error message to
  2048. ;; the user in the no-prompts warning.
  2049. (ignore-errors
  2050. (let ((code-file (python-shell--save-temp-file code)))
  2051. ;; Use `process-file' as it is remote-host friendly.
  2052. (process-file
  2053. interpreter
  2054. code-file
  2055. '(t nil)
  2056. nil
  2057. interpreter-arg)
  2058. ;; Try to cleanup
  2059. (delete-file code-file)))
  2060. (buffer-string)))
  2061. (prompts
  2062. (catch 'prompts
  2063. (dolist (line (split-string output "\n" t))
  2064. (let ((res
  2065. ;; Check if current line is a valid JSON array
  2066. (and (string= (substring line 0 2) "[\"")
  2067. (ignore-errors
  2068. ;; Return prompts as a list, not vector
  2069. (append (json-read-from-string line) nil)))))
  2070. ;; The list must contain 3 strings, where the first
  2071. ;; is the input prompt, the second is the block
  2072. ;; prompt and the last one is the output prompt. The
  2073. ;; input prompt is the only one that can't be empty.
  2074. (when (and (= (length res) 3)
  2075. (cl-every #'stringp res)
  2076. (not (string= (car res) "")))
  2077. (throw 'prompts res))))
  2078. nil)))
  2079. (when (and (not prompts)
  2080. python-shell-prompt-detect-failure-warning)
  2081. (lwarn
  2082. '(python python-shell-prompt-regexp)
  2083. :warning
  2084. (concat
  2085. "Python shell prompts cannot be detected.\n"
  2086. "If your emacs session hangs when starting python shells\n"
  2087. "recover with `keyboard-quit' and then try fixing the\n"
  2088. "interactive flag for your interpreter by adjusting the\n"
  2089. "`python-shell-interpreter-interactive-arg' or add regexps\n"
  2090. "matching shell prompts in the directory-local friendly vars:\n"
  2091. " + `python-shell-prompt-regexp'\n"
  2092. " + `python-shell-prompt-block-regexp'\n"
  2093. " + `python-shell-prompt-output-regexp'\n"
  2094. "Or alternatively in:\n"
  2095. " + `python-shell-prompt-input-regexps'\n"
  2096. " + `python-shell-prompt-output-regexps'")))
  2097. prompts))))
  2098. (defun python-shell-prompt-validate-regexps ()
  2099. "Validate all user provided regexps for prompts.
  2100. Signals `user-error' if any of these vars contain invalid
  2101. regexps: `python-shell-prompt-regexp',
  2102. `python-shell-prompt-block-regexp',
  2103. `python-shell-prompt-pdb-regexp',
  2104. `python-shell-prompt-output-regexp',
  2105. `python-shell-prompt-input-regexps',
  2106. `python-shell-prompt-output-regexps'."
  2107. (dolist (symbol (list 'python-shell-prompt-input-regexps
  2108. 'python-shell-prompt-output-regexps
  2109. 'python-shell-prompt-regexp
  2110. 'python-shell-prompt-block-regexp
  2111. 'python-shell-prompt-pdb-regexp
  2112. 'python-shell-prompt-output-regexp))
  2113. (dolist (regexp (let ((regexps (symbol-value symbol)))
  2114. (if (listp regexps)
  2115. regexps
  2116. (list regexps))))
  2117. (when (not (python-util-valid-regexp-p regexp))
  2118. (user-error "Invalid regexp %s in `%s'"
  2119. regexp symbol)))))
  2120. (defun python-shell-prompt-set-calculated-regexps ()
  2121. "Detect and set input and output prompt regexps.
  2122. Build and set the values for `python-shell-input-prompt-regexp'
  2123. and `python-shell-output-prompt-regexp' using the values from
  2124. `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
  2125. `python-shell-prompt-pdb-regexp',
  2126. `python-shell-prompt-output-regexp',
  2127. `python-shell-prompt-input-regexps',
  2128. `python-shell-prompt-output-regexps' and detected prompts from
  2129. `python-shell-prompt-detect'."
  2130. (when (not (and python-shell--prompt-calculated-input-regexp
  2131. python-shell--prompt-calculated-output-regexp))
  2132. (let* ((detected-prompts (python-shell-prompt-detect))
  2133. (input-prompts nil)
  2134. (output-prompts nil)
  2135. (build-regexp
  2136. (lambda (prompts)
  2137. (concat "^\\("
  2138. (mapconcat #'identity
  2139. (sort prompts
  2140. (lambda (a b)
  2141. (let ((length-a (length a))
  2142. (length-b (length b)))
  2143. (if (= length-a length-b)
  2144. (string< a b)
  2145. (> (length a) (length b))))))
  2146. "\\|")
  2147. "\\)"))))
  2148. ;; Validate ALL regexps
  2149. (python-shell-prompt-validate-regexps)
  2150. ;; Collect all user defined input prompts
  2151. (dolist (prompt (append python-shell-prompt-input-regexps
  2152. (list python-shell-prompt-regexp
  2153. python-shell-prompt-block-regexp
  2154. python-shell-prompt-pdb-regexp)))
  2155. (cl-pushnew prompt input-prompts :test #'string=))
  2156. ;; Collect all user defined output prompts
  2157. (dolist (prompt (cons python-shell-prompt-output-regexp
  2158. python-shell-prompt-output-regexps))
  2159. (cl-pushnew prompt output-prompts :test #'string=))
  2160. ;; Collect detected prompts if any
  2161. (when detected-prompts
  2162. (dolist (prompt (butlast detected-prompts))
  2163. (setq prompt (regexp-quote prompt))
  2164. (cl-pushnew prompt input-prompts :test #'string=))
  2165. (cl-pushnew (regexp-quote
  2166. (car (last detected-prompts)))
  2167. output-prompts :test #'string=))
  2168. ;; Set input and output prompt regexps from collected prompts
  2169. (setq python-shell--prompt-calculated-input-regexp
  2170. (funcall build-regexp input-prompts)
  2171. python-shell--prompt-calculated-output-regexp
  2172. (funcall build-regexp output-prompts)))))
  2173. (defun python-shell-get-process-name (dedicated)
  2174. "Calculate the appropriate process name for inferior Python process.
  2175. If DEDICATED is t returns a string with the form
  2176. `python-shell-buffer-name'[`buffer-name'] else returns the value
  2177. of `python-shell-buffer-name'."
  2178. (if dedicated
  2179. (format "%s[%s]" python-shell-buffer-name (buffer-name))
  2180. python-shell-buffer-name))
  2181. (defun python-shell-internal-get-process-name ()
  2182. "Calculate the appropriate process name for Internal Python process.
  2183. The name is calculated from `python-shell-global-buffer-name' and
  2184. the `buffer-name'."
  2185. (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
  2186. (defun python-shell-calculate-command ()
  2187. "Calculate the string used to execute the inferior Python process."
  2188. (format "%s %s"
  2189. ;; `python-shell-make-comint' expects to be able to
  2190. ;; `split-string-and-unquote' the result of this function.
  2191. (combine-and-quote-strings (list python-shell-interpreter))
  2192. python-shell-interpreter-args))
  2193. (define-obsolete-function-alias
  2194. 'python-shell-parse-command
  2195. #'python-shell-calculate-command "25.1")
  2196. (defvar python-shell--package-depth 10)
  2197. (defun python-shell-package-enable (directory package)
  2198. "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
  2199. (interactive
  2200. (let* ((dir (expand-file-name
  2201. (read-directory-name
  2202. "Package root: "
  2203. (file-name-directory
  2204. (or (buffer-file-name) default-directory)))))
  2205. (name (completing-read
  2206. "Package: "
  2207. (python-util-list-packages
  2208. dir python-shell--package-depth))))
  2209. (list dir name)))
  2210. (python-shell-send-string
  2211. (format
  2212. (concat
  2213. "import os.path;import sys;"
  2214. "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
  2215. "__package__ = '''%s''';"
  2216. "import %s")
  2217. directory package package)
  2218. (python-shell-get-process)))
  2219. (defun python-shell-accept-process-output (process &optional timeout regexp)
  2220. "Accept PROCESS output with TIMEOUT until REGEXP is found.
  2221. Optional argument TIMEOUT is the timeout argument to
  2222. `accept-process-output' calls. Optional argument REGEXP
  2223. overrides the regexp to match the end of output, defaults to
  2224. `comint-prompt-regexp.'. Returns non-nil when output was
  2225. properly captured.
  2226. This utility is useful in situations where the output may be
  2227. received in chunks, since `accept-process-output' gives no
  2228. guarantees they will be grabbed in a single call. An example use
  2229. case for this would be the CPython shell start-up, where the
  2230. banner and the initial prompt are received separately."
  2231. (let ((regexp (or regexp comint-prompt-regexp)))
  2232. (catch 'found
  2233. (while t
  2234. (when (not (accept-process-output process timeout))
  2235. (throw 'found nil))
  2236. (when (looking-back
  2237. regexp (car (python-util-comint-last-prompt)))
  2238. (throw 'found t))))))
  2239. (defun python-shell-comint-end-of-output-p (output)
  2240. "Return non-nil if OUTPUT is ends with input prompt."
  2241. (string-match
  2242. ;; XXX: It seems on macOS an extra carriage return is attached
  2243. ;; at the end of output, this handles that too.
  2244. (concat
  2245. "\r?\n?"
  2246. ;; Remove initial caret from calculated regexp
  2247. (replace-regexp-in-string
  2248. (rx string-start ?^) ""
  2249. python-shell--prompt-calculated-input-regexp)
  2250. (rx eos))
  2251. output))
  2252. (define-obsolete-function-alias
  2253. 'python-comint-output-filter-function
  2254. 'ansi-color-filter-apply
  2255. "25.1")
  2256. (defun python-comint-postoutput-scroll-to-bottom (output)
  2257. "Faster version of `comint-postoutput-scroll-to-bottom'.
  2258. Avoids `recenter' calls until OUTPUT is completely sent."
  2259. (when (and (not (string= "" output))
  2260. (python-shell-comint-end-of-output-p
  2261. (ansi-color-filter-apply output)))
  2262. (comint-postoutput-scroll-to-bottom output))
  2263. output)
  2264. (defvar python-shell--parent-buffer nil)
  2265. (defmacro python-shell-with-shell-buffer (&rest body)
  2266. "Execute the forms in BODY with the shell buffer temporarily current.
  2267. Signals an error if no shell buffer is available for current buffer."
  2268. (declare (indent 0) (debug t))
  2269. (let ((shell-process (make-symbol "shell-process")))
  2270. `(let ((,shell-process (python-shell-get-process-or-error)))
  2271. (with-current-buffer (process-buffer ,shell-process)
  2272. ,@body))))
  2273. (defvar python-shell--font-lock-buffer nil)
  2274. (defun python-shell-font-lock-get-or-create-buffer ()
  2275. "Get or create a font-lock buffer for current inferior process."
  2276. (python-shell-with-shell-buffer
  2277. (if python-shell--font-lock-buffer
  2278. python-shell--font-lock-buffer
  2279. (let ((process-name
  2280. (process-name (get-buffer-process (current-buffer)))))
  2281. (generate-new-buffer
  2282. (format " *%s-font-lock*" process-name))))))
  2283. (defun python-shell-font-lock-kill-buffer ()
  2284. "Kill the font-lock buffer safely."
  2285. (when (and python-shell--font-lock-buffer
  2286. (buffer-live-p python-shell--font-lock-buffer))
  2287. (kill-buffer python-shell--font-lock-buffer)
  2288. (when (derived-mode-p 'inferior-python-mode)
  2289. (setq python-shell--font-lock-buffer nil))))
  2290. (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
  2291. "Execute the forms in BODY in the font-lock buffer.
  2292. The value returned is the value of the last form in BODY. See
  2293. also `with-current-buffer'."
  2294. (declare (indent 0) (debug t))
  2295. `(python-shell-with-shell-buffer
  2296. (save-current-buffer
  2297. (when (not (and python-shell--font-lock-buffer
  2298. (get-buffer python-shell--font-lock-buffer)))
  2299. (setq python-shell--font-lock-buffer
  2300. (python-shell-font-lock-get-or-create-buffer)))
  2301. (set-buffer python-shell--font-lock-buffer)
  2302. (when (not font-lock-mode)
  2303. (font-lock-mode 1))
  2304. (set (make-local-variable 'delay-mode-hooks) t)
  2305. (let ((python-indent-guess-indent-offset nil))
  2306. (when (not (derived-mode-p 'python-mode))
  2307. (python-mode))
  2308. ,@body))))
  2309. (defun python-shell-font-lock-cleanup-buffer ()
  2310. "Cleanup the font-lock buffer.
  2311. Provided as a command because this might be handy if something
  2312. goes wrong and syntax highlighting in the shell gets messed up."
  2313. (interactive)
  2314. (python-shell-with-shell-buffer
  2315. (python-shell-font-lock-with-font-lock-buffer
  2316. (erase-buffer))))
  2317. (defun python-shell-font-lock-comint-output-filter-function (output)
  2318. "Clean up the font-lock buffer after any OUTPUT."
  2319. (if (and (not (string= "" output))
  2320. ;; Is end of output and is not just a prompt.
  2321. (not (member
  2322. (python-shell-comint-end-of-output-p
  2323. (ansi-color-filter-apply output))
  2324. '(nil 0))))
  2325. ;; If output is other than an input prompt then "real" output has
  2326. ;; been received and the font-lock buffer must be cleaned up.
  2327. (python-shell-font-lock-cleanup-buffer)
  2328. ;; Otherwise just add a newline.
  2329. (python-shell-font-lock-with-font-lock-buffer
  2330. (goto-char (point-max))
  2331. (newline)))
  2332. output)
  2333. (defun python-shell-font-lock-post-command-hook ()
  2334. "Fontifies current line in shell buffer."
  2335. (let ((prompt-end (cdr (python-util-comint-last-prompt))))
  2336. (when (and prompt-end (> (point) prompt-end)
  2337. (process-live-p (get-buffer-process (current-buffer))))
  2338. (let* ((input (buffer-substring-no-properties
  2339. prompt-end (point-max)))
  2340. (deactivate-mark nil)
  2341. (start-pos prompt-end)
  2342. (buffer-undo-list t)
  2343. (font-lock-buffer-pos nil)
  2344. (replacement
  2345. (python-shell-font-lock-with-font-lock-buffer
  2346. (delete-region (line-beginning-position)
  2347. (point-max))
  2348. (setq font-lock-buffer-pos (point))
  2349. (insert input)
  2350. ;; Ensure buffer is fontified, keeping it
  2351. ;; compatible with Emacs < 24.4.
  2352. (if (fboundp 'font-lock-ensure)
  2353. (funcall 'font-lock-ensure)
  2354. (font-lock-default-fontify-buffer))
  2355. (buffer-substring font-lock-buffer-pos
  2356. (point-max))))
  2357. (replacement-length (length replacement))
  2358. (i 0))
  2359. ;; Inject text properties to get input fontified.
  2360. (while (not (= i replacement-length))
  2361. (let* ((plist (text-properties-at i replacement))
  2362. (next-change (or (next-property-change i replacement)
  2363. replacement-length))
  2364. (plist (let ((face (plist-get plist 'face)))
  2365. (if (not face)
  2366. plist
  2367. ;; Replace FACE text properties with
  2368. ;; FONT-LOCK-FACE so input is fontified.
  2369. (plist-put plist 'face nil)
  2370. (plist-put plist 'font-lock-face face)))))
  2371. (set-text-properties
  2372. (+ start-pos i) (+ start-pos next-change) plist)
  2373. (setq i next-change)))))))
  2374. (defun python-shell-font-lock-turn-on (&optional msg)
  2375. "Turn on shell font-lock.
  2376. With argument MSG show activation message."
  2377. (interactive "p")
  2378. (python-shell-with-shell-buffer
  2379. (python-shell-font-lock-kill-buffer)
  2380. (set (make-local-variable 'python-shell--font-lock-buffer) nil)
  2381. (add-hook 'post-command-hook
  2382. #'python-shell-font-lock-post-command-hook nil 'local)
  2383. (add-hook 'kill-buffer-hook
  2384. #'python-shell-font-lock-kill-buffer nil 'local)
  2385. (add-hook 'comint-output-filter-functions
  2386. #'python-shell-font-lock-comint-output-filter-function
  2387. 'append 'local)
  2388. (when msg
  2389. (message "Shell font-lock is enabled"))))
  2390. (defun python-shell-font-lock-turn-off (&optional msg)
  2391. "Turn off shell font-lock.
  2392. With argument MSG show deactivation message."
  2393. (interactive "p")
  2394. (python-shell-with-shell-buffer
  2395. (python-shell-font-lock-kill-buffer)
  2396. (when (python-util-comint-last-prompt)
  2397. ;; Cleanup current fontification
  2398. (remove-text-properties
  2399. (cdr (python-util-comint-last-prompt))
  2400. (line-end-position)
  2401. '(face nil font-lock-face nil)))
  2402. (set (make-local-variable 'python-shell--font-lock-buffer) nil)
  2403. (remove-hook 'post-command-hook
  2404. #'python-shell-font-lock-post-command-hook 'local)
  2405. (remove-hook 'kill-buffer-hook
  2406. #'python-shell-font-lock-kill-buffer 'local)
  2407. (remove-hook 'comint-output-filter-functions
  2408. #'python-shell-font-lock-comint-output-filter-function
  2409. 'local)
  2410. (when msg
  2411. (message "Shell font-lock is disabled"))))
  2412. (defun python-shell-font-lock-toggle (&optional msg)
  2413. "Toggle font-lock for shell.
  2414. With argument MSG show activation/deactivation message."
  2415. (interactive "p")
  2416. (python-shell-with-shell-buffer
  2417. (set (make-local-variable 'python-shell-font-lock-enable)
  2418. (not python-shell-font-lock-enable))
  2419. (if python-shell-font-lock-enable
  2420. (python-shell-font-lock-turn-on msg)
  2421. (python-shell-font-lock-turn-off msg))
  2422. python-shell-font-lock-enable))
  2423. (defvar python-shell--first-prompt-received-output-buffer nil)
  2424. (defvar python-shell--first-prompt-received nil)
  2425. (defcustom python-shell-first-prompt-hook nil
  2426. "Hook run upon first (non-pdb) shell prompt detection.
  2427. This is the place for shell setup functions that need to wait for
  2428. output. Since the first prompt is ensured, this helps the
  2429. current process to not hang waiting for output by safeguarding
  2430. interactive actions can be performed. This is useful to safely
  2431. attach setup code for long-running processes that eventually
  2432. provide a shell."
  2433. :version "25.1"
  2434. :type 'hook
  2435. :group 'python)
  2436. (defun python-shell-comint-watch-for-first-prompt-output-filter (output)
  2437. "Run `python-shell-first-prompt-hook' when first prompt is found in OUTPUT."
  2438. (when (not python-shell--first-prompt-received)
  2439. (set (make-local-variable 'python-shell--first-prompt-received-output-buffer)
  2440. (concat python-shell--first-prompt-received-output-buffer
  2441. (ansi-color-filter-apply output)))
  2442. (when (python-shell-comint-end-of-output-p
  2443. python-shell--first-prompt-received-output-buffer)
  2444. (if (string-match-p
  2445. (concat python-shell-prompt-pdb-regexp (rx eos))
  2446. (or python-shell--first-prompt-received-output-buffer ""))
  2447. ;; Skip pdb prompts and reset the buffer.
  2448. (setq python-shell--first-prompt-received-output-buffer nil)
  2449. (set (make-local-variable 'python-shell--first-prompt-received) t)
  2450. (setq python-shell--first-prompt-received-output-buffer nil)
  2451. (with-current-buffer (current-buffer)
  2452. (let ((inhibit-quit nil))
  2453. (run-hooks 'python-shell-first-prompt-hook))))))
  2454. output)
  2455. ;; Used to hold user interactive overrides to
  2456. ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
  2457. ;; will be made buffer-local by `inferior-python-mode':
  2458. (defvar python-shell--interpreter)
  2459. (defvar python-shell--interpreter-args)
  2460. (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
  2461. "Major mode for Python inferior process.
  2462. Runs a Python interpreter as a subprocess of Emacs, with Python
  2463. I/O through an Emacs buffer. Variables `python-shell-interpreter'
  2464. and `python-shell-interpreter-args' control which Python
  2465. interpreter is run. Variables
  2466. `python-shell-prompt-regexp',
  2467. `python-shell-prompt-output-regexp',
  2468. `python-shell-prompt-block-regexp',
  2469. `python-shell-font-lock-enable',
  2470. `python-shell-completion-setup-code',
  2471. `python-shell-completion-string-code',
  2472. `python-eldoc-setup-code', `python-eldoc-string-code',
  2473. `python-ffap-setup-code' and `python-ffap-string-code' can
  2474. customize this mode for different Python interpreters.
  2475. This mode resets `comint-output-filter-functions' locally, so you
  2476. may want to re-add custom functions to it using the
  2477. `inferior-python-mode-hook'.
  2478. You can also add additional setup code to be run at
  2479. initialization of the interpreter via `python-shell-setup-codes'
  2480. variable.
  2481. \(Type \\[describe-mode] in the process buffer for a list of commands.)"
  2482. (when python-shell--parent-buffer
  2483. (python-util-clone-local-variables python-shell--parent-buffer))
  2484. (set (make-local-variable 'indent-tabs-mode) nil)
  2485. ;; Users can interactively override default values for
  2486. ;; `python-shell-interpreter' and `python-shell-interpreter-args'
  2487. ;; when calling `run-python'. This ensures values let-bound in
  2488. ;; `python-shell-make-comint' are locally set if needed.
  2489. (set (make-local-variable 'python-shell-interpreter)
  2490. (or python-shell--interpreter python-shell-interpreter))
  2491. (set (make-local-variable 'python-shell-interpreter-args)
  2492. (or python-shell--interpreter-args python-shell-interpreter-args))
  2493. (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
  2494. (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
  2495. (python-shell-prompt-set-calculated-regexps)
  2496. (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
  2497. (set (make-local-variable 'comint-prompt-read-only) t)
  2498. (setq mode-line-process '(":%s"))
  2499. (set (make-local-variable 'comint-output-filter-functions)
  2500. '(ansi-color-process-output
  2501. python-shell-comint-watch-for-first-prompt-output-filter
  2502. python-pdbtrack-comint-output-filter-function
  2503. python-comint-postoutput-scroll-to-bottom))
  2504. (set (make-local-variable 'compilation-error-regexp-alist)
  2505. python-shell-compilation-regexp-alist)
  2506. (add-hook 'completion-at-point-functions
  2507. #'python-shell-completion-at-point nil 'local)
  2508. (define-key inferior-python-mode-map "\t"
  2509. 'python-shell-completion-complete-or-indent)
  2510. (make-local-variable 'python-pdbtrack-buffers-to-kill)
  2511. (make-local-variable 'python-pdbtrack-tracked-buffer)
  2512. (make-local-variable 'python-shell-internal-last-output)
  2513. (when python-shell-font-lock-enable
  2514. (python-shell-font-lock-turn-on))
  2515. (compilation-shell-minor-mode 1))
  2516. (defun python-shell-make-comint (cmd proc-name &optional show internal)
  2517. "Create a Python shell comint buffer.
  2518. CMD is the Python command to be executed and PROC-NAME is the
  2519. process name the comint buffer will get. After the comint buffer
  2520. is created the `inferior-python-mode' is activated. When
  2521. optional argument SHOW is non-nil the buffer is shown. When
  2522. optional argument INTERNAL is non-nil this process is run on a
  2523. buffer with a name that starts with a space, following the Emacs
  2524. convention for temporary/internal buffers, and also makes sure
  2525. the user is not queried for confirmation when the process is
  2526. killed."
  2527. (save-excursion
  2528. (python-shell-with-environment
  2529. (let* ((proc-buffer-name
  2530. (format (if (not internal) "*%s*" " *%s*") proc-name)))
  2531. (when (not (comint-check-proc proc-buffer-name))
  2532. (let* ((cmdlist (split-string-and-unquote cmd))
  2533. (interpreter (car cmdlist))
  2534. (args (cdr cmdlist))
  2535. (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
  2536. interpreter nil args))
  2537. (python-shell--parent-buffer (current-buffer))
  2538. (process (get-buffer-process buffer))
  2539. ;; Users can override the interpreter and args
  2540. ;; interactively when calling `run-python', let-binding
  2541. ;; these allows having the new right values in all
  2542. ;; setup code that is done in `inferior-python-mode',
  2543. ;; which is important, especially for prompt detection.
  2544. (python-shell--interpreter interpreter)
  2545. (python-shell--interpreter-args
  2546. (mapconcat #'identity args " ")))
  2547. (with-current-buffer buffer
  2548. (inferior-python-mode))
  2549. (when show (display-buffer buffer))
  2550. (and internal (set-process-query-on-exit-flag process nil))))
  2551. proc-buffer-name))))
  2552. ;;;###autoload
  2553. (defun run-python (&optional cmd dedicated show)
  2554. "Run an inferior Python process.
  2555. Argument CMD defaults to `python-shell-calculate-command' return
  2556. value. When called interactively with `prefix-arg', it allows
  2557. the user to edit such value and choose whether the interpreter
  2558. should be DEDICATED for the current buffer. When numeric prefix
  2559. arg is other than 0 or 4 do not SHOW.
  2560. For a given buffer and same values of DEDICATED, if a process is
  2561. already running for it, it will do nothing. This means that if
  2562. the current buffer is using a global process, the user is still
  2563. able to switch it to use a dedicated one.
  2564. Runs the hook `inferior-python-mode-hook' after
  2565. `comint-mode-hook' is run. (Type \\[describe-mode] in the
  2566. process buffer for a list of commands.)"
  2567. (interactive
  2568. (if current-prefix-arg
  2569. (list
  2570. (read-shell-command "Run Python: " (python-shell-calculate-command))
  2571. (y-or-n-p "Make dedicated process? ")
  2572. (= (prefix-numeric-value current-prefix-arg) 4))
  2573. (list (python-shell-calculate-command) nil t)))
  2574. (get-buffer-process
  2575. (python-shell-make-comint
  2576. (or cmd (python-shell-calculate-command))
  2577. (python-shell-get-process-name dedicated) show)))
  2578. (defun run-python-internal ()
  2579. "Run an inferior Internal Python process.
  2580. Input and output via buffer named after
  2581. `python-shell-internal-buffer-name' and what
  2582. `python-shell-internal-get-process-name' returns.
  2583. This new kind of shell is intended to be used for generic
  2584. communication related to defined configurations; the main
  2585. difference with global or dedicated shells is that these ones are
  2586. attached to a configuration, not a buffer. This means that can
  2587. be used for example to retrieve the sys.path and other stuff,
  2588. without messing with user shells. Note that
  2589. `python-shell-font-lock-enable' and `inferior-python-mode-hook'
  2590. are set to nil for these shells, so setup codes are not sent at
  2591. startup."
  2592. (let ((python-shell-font-lock-enable nil)
  2593. (inferior-python-mode-hook nil))
  2594. (get-buffer-process
  2595. (python-shell-make-comint
  2596. (python-shell-calculate-command)
  2597. (python-shell-internal-get-process-name) nil t))))
  2598. (defun python-shell-get-buffer ()
  2599. "Return inferior Python buffer for current buffer.
  2600. If current buffer is in `inferior-python-mode', return it."
  2601. (if (derived-mode-p 'inferior-python-mode)
  2602. (current-buffer)
  2603. (let* ((dedicated-proc-name (python-shell-get-process-name t))
  2604. (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
  2605. (global-proc-name (python-shell-get-process-name nil))
  2606. (global-proc-buffer-name (format "*%s*" global-proc-name))
  2607. (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
  2608. (global-running (comint-check-proc global-proc-buffer-name)))
  2609. ;; Always prefer dedicated
  2610. (or (and dedicated-running dedicated-proc-buffer-name)
  2611. (and global-running global-proc-buffer-name)))))
  2612. (defun python-shell-get-process ()
  2613. "Return inferior Python process for current buffer."
  2614. (get-buffer-process (python-shell-get-buffer)))
  2615. (defun python-shell-get-process-or-error (&optional interactivep)
  2616. "Return inferior Python process for current buffer or signal error.
  2617. When argument INTERACTIVEP is non-nil, use `user-error' instead
  2618. of `error' with a user-friendly message."
  2619. (or (python-shell-get-process)
  2620. (if interactivep
  2621. (user-error
  2622. "Start a Python process first with `%s' or `%s'."
  2623. (substitute-command-keys "\\[run-python]")
  2624. ;; Get the binding.
  2625. (key-description
  2626. (where-is-internal
  2627. #'run-python overriding-local-map t)))
  2628. (error
  2629. "No inferior Python process running."))))
  2630. (defun python-shell-get-or-create-process (&optional cmd dedicated show)
  2631. "Get or create an inferior Python process for current buffer and return it.
  2632. Arguments CMD, DEDICATED and SHOW are those of `run-python' and
  2633. are used to start the shell. If those arguments are not
  2634. provided, `run-python' is called interactively and the user will
  2635. be asked for their values."
  2636. (let ((shell-process (python-shell-get-process)))
  2637. (when (not shell-process)
  2638. (if (not cmd)
  2639. ;; XXX: Refactor code such that calling `run-python'
  2640. ;; interactively is not needed anymore.
  2641. (call-interactively 'run-python)
  2642. (run-python cmd dedicated show)))
  2643. (or shell-process (python-shell-get-process))))
  2644. (make-obsolete
  2645. #'python-shell-get-or-create-process
  2646. "Instead call `python-shell-get-process' and create one if returns nil."
  2647. "25.1")
  2648. (defvar python-shell-internal-buffer nil
  2649. "Current internal shell buffer for the current buffer.
  2650. This is really not necessary at all for the code to work but it's
  2651. there for compatibility with CEDET.")
  2652. (defvar python-shell-internal-last-output nil
  2653. "Last output captured by the internal shell.
  2654. This is really not necessary at all for the code to work but it's
  2655. there for compatibility with CEDET.")
  2656. (defun python-shell-internal-get-or-create-process ()
  2657. "Get or create an inferior Internal Python process."
  2658. (let ((proc-name (python-shell-internal-get-process-name)))
  2659. (if (process-live-p proc-name)
  2660. (get-process proc-name)
  2661. (run-python-internal))))
  2662. (define-obsolete-function-alias
  2663. 'python-proc 'python-shell-internal-get-or-create-process "24.3")
  2664. (define-obsolete-variable-alias
  2665. 'python-buffer 'python-shell-internal-buffer "24.3")
  2666. (define-obsolete-variable-alias
  2667. 'python-preoutput-result 'python-shell-internal-last-output "24.3")
  2668. (defun python-shell--save-temp-file (string)
  2669. (let* ((temporary-file-directory
  2670. (if (file-remote-p default-directory)
  2671. (concat (file-remote-p default-directory) "/tmp")
  2672. temporary-file-directory))
  2673. (temp-file-name (make-temp-file "py"))
  2674. (coding-system-for-write (python-info-encoding)))
  2675. (with-temp-file temp-file-name
  2676. (insert string)
  2677. (delete-trailing-whitespace))
  2678. temp-file-name))
  2679. (defun python-shell-send-string (string &optional process msg)
  2680. "Send STRING to inferior Python PROCESS.
  2681. When optional argument MSG is non-nil, forces display of a
  2682. user-friendly message if there's no process running; defaults to
  2683. t when called interactively."
  2684. (interactive
  2685. (list (read-string "Python command: ") nil t))
  2686. (let ((process (or process (python-shell-get-process-or-error msg))))
  2687. (if (string-match ".\n+." string) ;Multiline.
  2688. (let* ((temp-file-name (python-shell--save-temp-file string))
  2689. (file-name (or (buffer-file-name) temp-file-name)))
  2690. (python-shell-send-file file-name process temp-file-name t))
  2691. (comint-send-string process string)
  2692. (when (or (not (string-match "\n\\'" string))
  2693. (string-match "\n[ \t].*\n?\\'" string))
  2694. (comint-send-string process "\n")))))
  2695. (defvar python-shell-output-filter-in-progress nil)
  2696. (defvar python-shell-output-filter-buffer nil)
  2697. (defun python-shell-output-filter (string)
  2698. "Filter used in `python-shell-send-string-no-output' to grab output.
  2699. STRING is the output received to this point from the process.
  2700. This filter saves received output from the process in
  2701. `python-shell-output-filter-buffer' and stops receiving it after
  2702. detecting a prompt at the end of the buffer."
  2703. (setq
  2704. string (ansi-color-filter-apply string)
  2705. python-shell-output-filter-buffer
  2706. (concat python-shell-output-filter-buffer string))
  2707. (when (python-shell-comint-end-of-output-p
  2708. python-shell-output-filter-buffer)
  2709. ;; Output ends when `python-shell-output-filter-buffer' contains
  2710. ;; the prompt attached at the end of it.
  2711. (setq python-shell-output-filter-in-progress nil
  2712. python-shell-output-filter-buffer
  2713. (substring python-shell-output-filter-buffer
  2714. 0 (match-beginning 0)))
  2715. (when (string-match
  2716. python-shell--prompt-calculated-output-regexp
  2717. python-shell-output-filter-buffer)
  2718. ;; Some shells, like IPython might append a prompt before the
  2719. ;; output, clean that.
  2720. (setq python-shell-output-filter-buffer
  2721. (substring python-shell-output-filter-buffer (match-end 0)))))
  2722. "")
  2723. (defun python-shell-send-string-no-output (string &optional process)
  2724. "Send STRING to PROCESS and inhibit output.
  2725. Return the output."
  2726. (let ((process (or process (python-shell-get-process-or-error)))
  2727. (comint-preoutput-filter-functions
  2728. '(python-shell-output-filter))
  2729. (python-shell-output-filter-in-progress t)
  2730. (inhibit-quit t))
  2731. (or
  2732. (with-local-quit
  2733. (python-shell-send-string string process)
  2734. (while python-shell-output-filter-in-progress
  2735. ;; `python-shell-output-filter' takes care of setting
  2736. ;; `python-shell-output-filter-in-progress' to NIL after it
  2737. ;; detects end of output.
  2738. (accept-process-output process))
  2739. (prog1
  2740. python-shell-output-filter-buffer
  2741. (setq python-shell-output-filter-buffer nil)))
  2742. (with-current-buffer (process-buffer process)
  2743. (comint-interrupt-subjob)))))
  2744. (defun python-shell-internal-send-string (string)
  2745. "Send STRING to the Internal Python interpreter.
  2746. Returns the output. See `python-shell-send-string-no-output'."
  2747. ;; XXX Remove `python-shell-internal-last-output' once CEDET is
  2748. ;; updated to support this new mode.
  2749. (setq python-shell-internal-last-output
  2750. (python-shell-send-string-no-output
  2751. ;; Makes this function compatible with the old
  2752. ;; python-send-receive. (At least for CEDET).
  2753. (replace-regexp-in-string "_emacs_out +" "" string)
  2754. (python-shell-internal-get-or-create-process))))
  2755. (define-obsolete-function-alias
  2756. 'python-send-receive 'python-shell-internal-send-string "24.3")
  2757. (define-obsolete-function-alias
  2758. 'python-send-string 'python-shell-internal-send-string "24.3")
  2759. (defun python-shell-buffer-substring (start end &optional nomain)
  2760. "Send buffer substring from START to END formatted for shell.
  2761. This is a wrapper over `buffer-substring' that takes care of
  2762. different transformations for the code sent to be evaluated in
  2763. the python shell:
  2764. 1. When optional argument NOMAIN is non-nil everything under an
  2765. \"if __name__ == \\='__main__\\='\" block will be removed.
  2766. 2. When a subregion of the buffer is sent, it takes care of
  2767. appending extra empty lines so tracebacks are correct.
  2768. 3. When the region sent is a substring of the current buffer, a
  2769. coding cookie is added.
  2770. 4. Wraps indented regions under an \"if True:\" block so the
  2771. interpreter evaluates them correctly."
  2772. (let* ((start (save-excursion
  2773. ;; Normalize start to the line beginning position.
  2774. (goto-char start)
  2775. (line-beginning-position)))
  2776. (substring (buffer-substring-no-properties start end))
  2777. (starts-at-point-min-p (save-restriction
  2778. (widen)
  2779. (= (point-min) start)))
  2780. (encoding (python-info-encoding))
  2781. (toplevel-p (zerop (save-excursion
  2782. (goto-char start)
  2783. (python-util-forward-comment 1)
  2784. (current-indentation))))
  2785. (fillstr (when (not starts-at-point-min-p)
  2786. (concat
  2787. (format "# -*- coding: %s -*-\n" encoding)
  2788. (make-string
  2789. ;; Subtract 2 because of the coding cookie.
  2790. (- (line-number-at-pos start) 2) ?\n)))))
  2791. (with-temp-buffer
  2792. (python-mode)
  2793. (when fillstr
  2794. (insert fillstr))
  2795. (insert substring)
  2796. (goto-char (point-min))
  2797. (when (not toplevel-p)
  2798. (insert "if True:")
  2799. (delete-region (point) (line-end-position)))
  2800. (when nomain
  2801. (let* ((if-name-main-start-end
  2802. (and nomain
  2803. (save-excursion
  2804. (when (python-nav-if-name-main)
  2805. (cons (point)
  2806. (progn (python-nav-forward-sexp-safe)
  2807. ;; Include ending newline
  2808. (forward-line 1)
  2809. (point)))))))
  2810. ;; Oh destructuring bind, how I miss you.
  2811. (if-name-main-start (car if-name-main-start-end))
  2812. (if-name-main-end (cdr if-name-main-start-end))
  2813. (fillstr (make-string
  2814. (- (line-number-at-pos if-name-main-end)
  2815. (line-number-at-pos if-name-main-start)) ?\n)))
  2816. (when if-name-main-start-end
  2817. (goto-char if-name-main-start)
  2818. (delete-region if-name-main-start if-name-main-end)
  2819. (insert fillstr))))
  2820. ;; Ensure there's only one coding cookie in the generated string.
  2821. (goto-char (point-min))
  2822. (when (looking-at-p (python-rx coding-cookie))
  2823. (forward-line 1)
  2824. (when (looking-at-p (python-rx coding-cookie))
  2825. (delete-region
  2826. (line-beginning-position) (line-end-position))))
  2827. (buffer-substring-no-properties (point-min) (point-max)))))
  2828. (defun python-shell-send-region (start end &optional send-main msg)
  2829. "Send the region delimited by START and END to inferior Python process.
  2830. When optional argument SEND-MAIN is non-nil, allow execution of
  2831. code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
  2832. When called interactively SEND-MAIN defaults to nil, unless it's
  2833. called with prefix argument. When optional argument MSG is
  2834. non-nil, forces display of a user-friendly message if there's no
  2835. process running; defaults to t when called interactively."
  2836. (interactive
  2837. (list (region-beginning) (region-end) current-prefix-arg t))
  2838. (let* ((string (python-shell-buffer-substring start end (not send-main)))
  2839. (process (python-shell-get-process-or-error msg))
  2840. (original-string (buffer-substring-no-properties start end))
  2841. (_ (string-match "\\`\n*\\(.*\\)" original-string)))
  2842. (message "Sent: %s..." (match-string 1 original-string))
  2843. (python-shell-send-string string process)))
  2844. (defun python-shell-send-buffer (&optional send-main msg)
  2845. "Send the entire buffer to inferior Python process.
  2846. When optional argument SEND-MAIN is non-nil, allow execution of
  2847. code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
  2848. When called interactively SEND-MAIN defaults to nil, unless it's
  2849. called with prefix argument. When optional argument MSG is
  2850. non-nil, forces display of a user-friendly message if there's no
  2851. process running; defaults to t when called interactively."
  2852. (interactive (list current-prefix-arg t))
  2853. (save-restriction
  2854. (widen)
  2855. (python-shell-send-region (point-min) (point-max) send-main msg)))
  2856. (defun python-shell-send-defun (&optional arg msg)
  2857. "Send the current defun to inferior Python process.
  2858. When argument ARG is non-nil do not include decorators. When
  2859. optional argument MSG is non-nil, forces display of a
  2860. user-friendly message if there's no process running; defaults to
  2861. t when called interactively."
  2862. (interactive (list current-prefix-arg t))
  2863. (save-excursion
  2864. (python-shell-send-region
  2865. (progn
  2866. (end-of-line 1)
  2867. (while (and (or (python-nav-beginning-of-defun)
  2868. (beginning-of-line 1))
  2869. (> (current-indentation) 0)))
  2870. (when (not arg)
  2871. (while (and (forward-line -1)
  2872. (looking-at (python-rx decorator))))
  2873. (forward-line 1))
  2874. (point-marker))
  2875. (progn
  2876. (or (python-nav-end-of-defun)
  2877. (end-of-line 1))
  2878. (point-marker))
  2879. nil ;; noop
  2880. msg)))
  2881. (defun python-shell-send-file (file-name &optional process temp-file-name
  2882. delete msg)
  2883. "Send FILE-NAME to inferior Python PROCESS.
  2884. If TEMP-FILE-NAME is passed then that file is used for processing
  2885. instead, while internally the shell will continue to use
  2886. FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
  2887. TEMP-FILE-NAME is deleted after evaluation is performed. When
  2888. optional argument MSG is non-nil, forces display of a
  2889. user-friendly message if there's no process running; defaults to
  2890. t when called interactively."
  2891. (interactive
  2892. (list
  2893. (read-file-name "File to send: ") ; file-name
  2894. nil ; process
  2895. nil ; temp-file-name
  2896. nil ; delete
  2897. t)) ; msg
  2898. (let* ((process (or process (python-shell-get-process-or-error msg)))
  2899. (encoding (with-temp-buffer
  2900. (insert-file-contents
  2901. (or temp-file-name file-name))
  2902. (python-info-encoding)))
  2903. (file-name (expand-file-name (file-local-name file-name)))
  2904. (temp-file-name (when temp-file-name
  2905. (expand-file-name
  2906. (file-local-name temp-file-name)))))
  2907. (python-shell-send-string
  2908. (format
  2909. (concat
  2910. "import codecs, os;"
  2911. "__pyfile = codecs.open('''%s''', encoding='''%s''');"
  2912. "__code = __pyfile.read().encode('''%s''');"
  2913. "__pyfile.close();"
  2914. (when (and delete temp-file-name)
  2915. (format "os.remove('''%s''');" temp-file-name))
  2916. "exec(compile(__code, '''%s''', 'exec'));")
  2917. (or temp-file-name file-name) encoding encoding file-name)
  2918. process)))
  2919. (defun python-shell-switch-to-shell (&optional msg)
  2920. "Switch to inferior Python process buffer.
  2921. When optional argument MSG is non-nil, forces display of a
  2922. user-friendly message if there's no process running; defaults to
  2923. t when called interactively."
  2924. (interactive "p")
  2925. (pop-to-buffer
  2926. (process-buffer (python-shell-get-process-or-error msg)) nil t))
  2927. (defun python-shell-send-setup-code ()
  2928. "Send all setup code for shell.
  2929. This function takes the list of setup code to send from the
  2930. `python-shell-setup-codes' list."
  2931. (when python-shell-setup-codes
  2932. (let ((process (python-shell-get-process))
  2933. (code (concat
  2934. (mapconcat
  2935. (lambda (elt)
  2936. (cond ((stringp elt) elt)
  2937. ((symbolp elt) (symbol-value elt))
  2938. (t "")))
  2939. python-shell-setup-codes
  2940. "\n\nprint ('python.el: sent setup code')"))))
  2941. (python-shell-send-string code process)
  2942. (python-shell-accept-process-output process))))
  2943. (add-hook 'python-shell-first-prompt-hook
  2944. #'python-shell-send-setup-code)
  2945. ;;; Shell completion
  2946. (defcustom python-shell-completion-setup-code
  2947. "
  2948. def __PYTHON_EL_get_completions(text):
  2949. completions = []
  2950. completer = None
  2951. try:
  2952. import readline
  2953. try:
  2954. import __builtin__
  2955. except ImportError:
  2956. # Python 3
  2957. import builtins as __builtin__
  2958. builtins = dir(__builtin__)
  2959. is_ipython = ('__IPYTHON__' in builtins or
  2960. '__IPYTHON__active' in builtins)
  2961. splits = text.split()
  2962. is_module = splits and splits[0] in ('from', 'import')
  2963. if is_ipython and is_module:
  2964. from IPython.core.completerlib import module_completion
  2965. completions = module_completion(text.strip())
  2966. elif is_ipython and '__IP' in builtins:
  2967. completions = __IP.complete(text)
  2968. elif is_ipython and 'get_ipython' in builtins:
  2969. completions = get_ipython().Completer.all_completions(text)
  2970. else:
  2971. # Try to reuse current completer.
  2972. completer = readline.get_completer()
  2973. if not completer:
  2974. # importing rlcompleter sets the completer, use it as a
  2975. # last resort to avoid breaking customizations.
  2976. import rlcompleter
  2977. completer = readline.get_completer()
  2978. if getattr(completer, 'PYTHON_EL_WRAPPED', False):
  2979. completer.print_mode = False
  2980. i = 0
  2981. while True:
  2982. completion = completer(text, i)
  2983. if not completion:
  2984. break
  2985. i += 1
  2986. completions.append(completion)
  2987. except:
  2988. pass
  2989. finally:
  2990. if getattr(completer, 'PYTHON_EL_WRAPPED', False):
  2991. completer.print_mode = True
  2992. return completions"
  2993. "Code used to setup completion in inferior Python processes."
  2994. :type 'string
  2995. :group 'python)
  2996. (defcustom python-shell-completion-string-code
  2997. "';'.join(__PYTHON_EL_get_completions('''%s'''))"
  2998. "Python code used to get a string of completions separated by semicolons.
  2999. The string passed to the function is the current python name or
  3000. the full statement in the case of imports."
  3001. :type 'string
  3002. :group 'python)
  3003. (define-obsolete-variable-alias
  3004. 'python-shell-completion-module-string-code
  3005. 'python-shell-completion-string-code
  3006. "24.4"
  3007. "Completion string code must also autocomplete modules.")
  3008. (define-obsolete-variable-alias
  3009. 'python-shell-completion-pdb-string-code
  3010. 'python-shell-completion-string-code
  3011. "25.1"
  3012. "Completion string code must work for (i)pdb.")
  3013. (defcustom python-shell-completion-native-disabled-interpreters
  3014. ;; PyPy's readline cannot handle some escape sequences yet.
  3015. (list "pypy")
  3016. "List of disabled interpreters.
  3017. When a match is found, native completion is disabled."
  3018. :version "25.1"
  3019. :type '(repeat string))
  3020. (defcustom python-shell-completion-native-enable t
  3021. "Enable readline based native completion."
  3022. :version "25.1"
  3023. :type 'boolean)
  3024. (defcustom python-shell-completion-native-output-timeout 5.0
  3025. "Time in seconds to wait for completion output before giving up."
  3026. :version "25.1"
  3027. :type 'float)
  3028. (defcustom python-shell-completion-native-try-output-timeout 1.0
  3029. "Time in seconds to wait for *trying* native completion output."
  3030. :version "25.1"
  3031. :type 'float)
  3032. (defvar python-shell-completion-native-redirect-buffer
  3033. " *Python completions redirect*"
  3034. "Buffer to be used to redirect output of readline commands.")
  3035. (defun python-shell-completion-native-interpreter-disabled-p ()
  3036. "Return non-nil if interpreter has native completion disabled."
  3037. (when python-shell-completion-native-disabled-interpreters
  3038. (string-match
  3039. (regexp-opt python-shell-completion-native-disabled-interpreters)
  3040. (file-name-nondirectory python-shell-interpreter))))
  3041. (defun python-shell-completion-native-try ()
  3042. "Return non-nil if can trigger native completion."
  3043. (let ((python-shell-completion-native-enable t)
  3044. (python-shell-completion-native-output-timeout
  3045. python-shell-completion-native-try-output-timeout))
  3046. (python-shell-completion-native-get-completions
  3047. (get-buffer-process (current-buffer))
  3048. nil "_")))
  3049. (defun python-shell-completion-native-setup ()
  3050. "Try to setup native completion, return non-nil on success."
  3051. (let ((process (python-shell-get-process)))
  3052. (with-current-buffer (process-buffer process)
  3053. (python-shell-send-string "
  3054. def __PYTHON_EL_native_completion_setup():
  3055. try:
  3056. import readline
  3057. try:
  3058. import __builtin__
  3059. except ImportError:
  3060. # Python 3
  3061. import builtins as __builtin__
  3062. builtins = dir(__builtin__)
  3063. is_ipython = ('__IPYTHON__' in builtins or
  3064. '__IPYTHON__active' in builtins)
  3065. class __PYTHON_EL_Completer:
  3066. '''Completer wrapper that prints candidates to stdout.
  3067. It wraps an existing completer function and changes its behavior so
  3068. that the user input is unchanged and real candidates are printed to
  3069. stdout.
  3070. Returned candidates are '0__dummy_completion__' and
  3071. '1__dummy_completion__' in that order ('0__dummy_completion__' is
  3072. returned repeatedly until all possible candidates are consumed).
  3073. The real candidates are printed to stdout so that they can be
  3074. easily retrieved through comint output redirect trickery.
  3075. '''
  3076. PYTHON_EL_WRAPPED = True
  3077. def __init__(self, completer):
  3078. self.completer = completer
  3079. self.last_completion = None
  3080. self.print_mode = True
  3081. def __call__(self, text, state):
  3082. if state == 0:
  3083. # Set the first dummy completion.
  3084. self.last_completion = None
  3085. completion = '0__dummy_completion__'
  3086. else:
  3087. completion = self.completer(text, state - 1)
  3088. if not completion:
  3089. if self.last_completion != '1__dummy_completion__':
  3090. # When no more completions are available, returning a
  3091. # dummy with non-sharing prefix allow ensuring output
  3092. # while preventing changes to current input.
  3093. # Coincidentally it's also the end of output.
  3094. completion = '1__dummy_completion__'
  3095. elif completion.endswith('('):
  3096. # Remove parens on callables as it breaks completion on
  3097. # arguments (e.g. str(Ari<tab>)).
  3098. completion = completion[:-1]
  3099. self.last_completion = completion
  3100. if completion in (
  3101. '0__dummy_completion__', '1__dummy_completion__'):
  3102. return completion
  3103. elif completion:
  3104. # For every non-dummy completion, return a repeated dummy
  3105. # one and print the real candidate so it can be retrieved
  3106. # by comint output filters.
  3107. if self.print_mode:
  3108. print (completion)
  3109. return '0__dummy_completion__'
  3110. else:
  3111. return completion
  3112. else:
  3113. return completion
  3114. completer = readline.get_completer()
  3115. if not completer:
  3116. # Used as last resort to avoid breaking customizations.
  3117. import rlcompleter
  3118. completer = readline.get_completer()
  3119. if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
  3120. # Wrap the existing completer function only once.
  3121. new_completer = __PYTHON_EL_Completer(completer)
  3122. if not is_ipython:
  3123. readline.set_completer(new_completer)
  3124. else:
  3125. # Try both initializations to cope with all IPython versions.
  3126. # This works fine for IPython 3.x but not for earlier:
  3127. readline.set_completer(new_completer)
  3128. # IPython<3 hacks readline such that `readline.set_completer`
  3129. # won't work. This workaround injects the new completer
  3130. # function into the existing instance directly:
  3131. instance = getattr(completer, 'im_self', completer.__self__)
  3132. instance.rlcomplete = new_completer
  3133. if readline.__doc__ and 'libedit' in readline.__doc__:
  3134. readline.parse_and_bind('bind ^I rl_complete')
  3135. else:
  3136. readline.parse_and_bind('tab: complete')
  3137. # Require just one tab to send output.
  3138. readline.parse_and_bind('set show-all-if-ambiguous on')
  3139. print ('python.el: native completion setup loaded')
  3140. except:
  3141. print ('python.el: native completion setup failed')
  3142. __PYTHON_EL_native_completion_setup()" process)
  3143. (when (and
  3144. (python-shell-accept-process-output
  3145. process python-shell-completion-native-try-output-timeout)
  3146. (save-excursion
  3147. (re-search-backward
  3148. (regexp-quote "python.el: native completion setup loaded") nil t 1)))
  3149. (python-shell-completion-native-try)))))
  3150. (defun python-shell-completion-native-turn-off (&optional msg)
  3151. "Turn off shell native completions.
  3152. With argument MSG show deactivation message."
  3153. (interactive "p")
  3154. (python-shell-with-shell-buffer
  3155. (set (make-local-variable 'python-shell-completion-native-enable) nil)
  3156. (when msg
  3157. (message "Shell native completion is disabled, using fallback"))))
  3158. (defun python-shell-completion-native-turn-on (&optional msg)
  3159. "Turn on shell native completions.
  3160. With argument MSG show deactivation message."
  3161. (interactive "p")
  3162. (python-shell-with-shell-buffer
  3163. (set (make-local-variable 'python-shell-completion-native-enable) t)
  3164. (python-shell-completion-native-turn-on-maybe msg)))
  3165. (defun python-shell-completion-native-turn-on-maybe (&optional msg)
  3166. "Turn on native completions if enabled and available.
  3167. With argument MSG show activation/deactivation message."
  3168. (interactive "p")
  3169. (python-shell-with-shell-buffer
  3170. (when python-shell-completion-native-enable
  3171. (cond
  3172. ((python-shell-completion-native-interpreter-disabled-p)
  3173. (python-shell-completion-native-turn-off msg))
  3174. ((python-shell-completion-native-setup)
  3175. (when msg
  3176. (message "Shell native completion is enabled.")))
  3177. (t (lwarn
  3178. '(python python-shell-completion-native-turn-on-maybe)
  3179. :warning
  3180. (concat
  3181. "Your `python-shell-interpreter' doesn't seem to "
  3182. "support readline, yet `python-shell-completion-native' "
  3183. (format "was t and %S is not part of the "
  3184. (file-name-nondirectory python-shell-interpreter))
  3185. "`python-shell-completion-native-disabled-interpreters' "
  3186. "list. Native completions have been disabled locally. "))
  3187. (python-shell-completion-native-turn-off msg))))))
  3188. (defun python-shell-completion-native-turn-on-maybe-with-msg ()
  3189. "Like `python-shell-completion-native-turn-on-maybe' but force messages."
  3190. (python-shell-completion-native-turn-on-maybe t))
  3191. (add-hook 'python-shell-first-prompt-hook
  3192. #'python-shell-completion-native-turn-on-maybe-with-msg)
  3193. (defun python-shell-completion-native-toggle (&optional msg)
  3194. "Toggle shell native completion.
  3195. With argument MSG show activation/deactivation message."
  3196. (interactive "p")
  3197. (python-shell-with-shell-buffer
  3198. (if python-shell-completion-native-enable
  3199. (python-shell-completion-native-turn-off msg)
  3200. (python-shell-completion-native-turn-on msg))
  3201. python-shell-completion-native-enable))
  3202. (defun python-shell-completion-native-get-completions (process import input)
  3203. "Get completions using native readline for PROCESS.
  3204. When IMPORT is non-nil takes precedence over INPUT for
  3205. completion."
  3206. (with-current-buffer (process-buffer process)
  3207. (let* ((input (or import input))
  3208. (original-filter-fn (process-filter process))
  3209. (redirect-buffer (get-buffer-create
  3210. python-shell-completion-native-redirect-buffer))
  3211. (trigger "\t")
  3212. (new-input (concat input trigger))
  3213. (input-length
  3214. (save-excursion
  3215. (+ (- (point-max) (comint-bol)) (length new-input))))
  3216. (delete-line-command (make-string input-length ?\b))
  3217. (input-to-send (concat new-input delete-line-command)))
  3218. ;; Ensure restoring the process filter, even if the user quits
  3219. ;; or there's some other error.
  3220. (unwind-protect
  3221. (with-current-buffer redirect-buffer
  3222. ;; Cleanup the redirect buffer
  3223. (erase-buffer)
  3224. ;; Mimic `comint-redirect-send-command', unfortunately it
  3225. ;; can't be used here because it expects a newline in the
  3226. ;; command and that's exactly what we are trying to avoid.
  3227. (let ((comint-redirect-echo-input nil)
  3228. (comint-redirect-completed nil)
  3229. (comint-redirect-perform-sanity-check nil)
  3230. (comint-redirect-insert-matching-regexp t)
  3231. (comint-redirect-finished-regexp
  3232. "1__dummy_completion__[[:space:]]*\n")
  3233. (comint-redirect-output-buffer redirect-buffer))
  3234. ;; Compatibility with Emacs 24.x. Comint changed and
  3235. ;; now `comint-redirect-filter' gets 3 args. This
  3236. ;; checks which version of `comint-redirect-filter' is
  3237. ;; in use based on its args and uses `apply-partially'
  3238. ;; to make it up for the 3 args case.
  3239. (if (= (length
  3240. (help-function-arglist 'comint-redirect-filter)) 3)
  3241. (set-process-filter
  3242. process (apply-partially
  3243. #'comint-redirect-filter original-filter-fn))
  3244. (set-process-filter process #'comint-redirect-filter))
  3245. (process-send-string process input-to-send)
  3246. ;; Grab output until our dummy completion used as
  3247. ;; output end marker is found.
  3248. (when (python-shell-accept-process-output
  3249. process python-shell-completion-native-output-timeout
  3250. comint-redirect-finished-regexp)
  3251. (re-search-backward "0__dummy_completion__" nil t)
  3252. (cl-remove-duplicates
  3253. (split-string
  3254. (buffer-substring-no-properties
  3255. (line-beginning-position) (point-min))
  3256. "[ \f\t\n\r\v()]+" t)
  3257. :test #'string=))))
  3258. (set-process-filter process original-filter-fn)))))
  3259. (defun python-shell-completion-get-completions (process import input)
  3260. "Do completion at point using PROCESS for IMPORT or INPUT.
  3261. When IMPORT is non-nil takes precedence over INPUT for
  3262. completion."
  3263. (setq input (or import input))
  3264. (with-current-buffer (process-buffer process)
  3265. (let ((completions
  3266. (python-util-strip-string
  3267. (python-shell-send-string-no-output
  3268. (format
  3269. (concat python-shell-completion-setup-code
  3270. "\nprint (" python-shell-completion-string-code ")")
  3271. input) process))))
  3272. (when (> (length completions) 2)
  3273. (split-string completions
  3274. "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
  3275. (defun python-shell-completion-at-point (&optional process)
  3276. "Function for `completion-at-point-functions' in `inferior-python-mode'.
  3277. Optional argument PROCESS forces completions to be retrieved
  3278. using that one instead of current buffer's process."
  3279. (setq process (or process (get-buffer-process (current-buffer))))
  3280. (let* ((line-start (if (derived-mode-p 'inferior-python-mode)
  3281. ;; Working on a shell buffer: use prompt end.
  3282. (cdr (python-util-comint-last-prompt))
  3283. (line-beginning-position)))
  3284. (import-statement
  3285. (when (string-match-p
  3286. (rx (* space) word-start (or "from" "import") word-end space)
  3287. (buffer-substring-no-properties line-start (point)))
  3288. (buffer-substring-no-properties line-start (point))))
  3289. (start
  3290. (save-excursion
  3291. (if (not (re-search-backward
  3292. (python-rx
  3293. (or whitespace open-paren close-paren string-delimiter))
  3294. line-start
  3295. t 1))
  3296. line-start
  3297. (forward-char (length (match-string-no-properties 0)))
  3298. (point))))
  3299. (end (point))
  3300. (prompt-boundaries
  3301. (with-current-buffer (process-buffer process)
  3302. (python-util-comint-last-prompt)))
  3303. (prompt
  3304. (with-current-buffer (process-buffer process)
  3305. (when prompt-boundaries
  3306. (buffer-substring-no-properties
  3307. (car prompt-boundaries) (cdr prompt-boundaries)))))
  3308. (completion-fn
  3309. (with-current-buffer (process-buffer process)
  3310. (cond ((or (null prompt)
  3311. (< (point) (cdr prompt-boundaries)))
  3312. #'ignore)
  3313. ((or (not python-shell-completion-native-enable)
  3314. ;; Even if native completion is enabled, for
  3315. ;; pdb interaction always use the fallback
  3316. ;; mechanism since the completer is changed.
  3317. ;; Also, since pdb interaction is single-line
  3318. ;; based, this is enough.
  3319. (string-match-p python-shell-prompt-pdb-regexp prompt))
  3320. #'python-shell-completion-get-completions)
  3321. (t #'python-shell-completion-native-get-completions)))))
  3322. (list start end
  3323. (completion-table-dynamic
  3324. (apply-partially
  3325. completion-fn
  3326. process import-statement)))))
  3327. (define-obsolete-function-alias
  3328. 'python-shell-completion-complete-at-point
  3329. 'python-shell-completion-at-point
  3330. "25.1")
  3331. (defun python-shell-completion-complete-or-indent ()
  3332. "Complete or indent depending on the context.
  3333. If content before pointer is all whitespace, indent.
  3334. If not try to complete."
  3335. (interactive)
  3336. (if (string-match "^[[:space:]]*$"
  3337. (buffer-substring (comint-line-beginning-position)
  3338. (point)))
  3339. (indent-for-tab-command)
  3340. (completion-at-point)))
  3341. ;;; PDB Track integration
  3342. (defcustom python-pdbtrack-activate t
  3343. "Non-nil makes Python shell enable pdbtracking."
  3344. :type 'boolean
  3345. :group 'python
  3346. :safe 'booleanp)
  3347. (defcustom python-pdbtrack-stacktrace-info-regexp
  3348. "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
  3349. "Regular expression matching stacktrace information.
  3350. Used to extract the current line and module being inspected."
  3351. :type 'string
  3352. :group 'python
  3353. :safe 'stringp)
  3354. (defvar python-pdbtrack-tracked-buffer nil
  3355. "Variable containing the value of the current tracked buffer.
  3356. Never set this variable directly, use
  3357. `python-pdbtrack-set-tracked-buffer' instead.")
  3358. (defvar python-pdbtrack-buffers-to-kill nil
  3359. "List of buffers to be deleted after tracking finishes.")
  3360. (defun python-pdbtrack-set-tracked-buffer (file-name)
  3361. "Set the buffer for FILE-NAME as the tracked buffer.
  3362. Internally it uses the `python-pdbtrack-tracked-buffer' variable.
  3363. Returns the tracked buffer."
  3364. (let* ((file-name-prospect (concat (file-remote-p default-directory)
  3365. file-name))
  3366. (file-buffer (get-file-buffer file-name-prospect)))
  3367. (if file-buffer
  3368. (setq python-pdbtrack-tracked-buffer file-buffer)
  3369. (cond
  3370. ((file-exists-p file-name-prospect)
  3371. (setq file-buffer (find-file-noselect file-name-prospect)))
  3372. ((and (not (equal file-name file-name-prospect))
  3373. (file-exists-p file-name))
  3374. ;; Fallback to a locally available copy of the file.
  3375. (setq file-buffer (find-file-noselect file-name-prospect))))
  3376. (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
  3377. (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
  3378. file-buffer))
  3379. (defun python-pdbtrack-comint-output-filter-function (output)
  3380. "Move overlay arrow to current pdb line in tracked buffer.
  3381. Argument OUTPUT is a string with the output from the comint process."
  3382. (when (and python-pdbtrack-activate (not (string= output "")))
  3383. (let* ((full-output (ansi-color-filter-apply
  3384. (buffer-substring comint-last-input-end (point-max))))
  3385. (line-number)
  3386. (file-name
  3387. (with-temp-buffer
  3388. (insert full-output)
  3389. ;; When the debugger encounters a pdb.set_trace()
  3390. ;; command, it prints a single stack frame. Sometimes
  3391. ;; it prints a bit of extra information about the
  3392. ;; arguments of the present function. When ipdb
  3393. ;; encounters an exception, it prints the _entire_ stack
  3394. ;; trace. To handle all of these cases, we want to find
  3395. ;; the _last_ stack frame printed in the most recent
  3396. ;; batch of output, then jump to the corresponding
  3397. ;; file/line number.
  3398. (goto-char (point-max))
  3399. (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
  3400. (setq line-number (string-to-number
  3401. (match-string-no-properties 2)))
  3402. (match-string-no-properties 1)))))
  3403. (if (and file-name line-number)
  3404. (let* ((tracked-buffer
  3405. (python-pdbtrack-set-tracked-buffer file-name))
  3406. (shell-buffer (current-buffer))
  3407. (tracked-buffer-window (get-buffer-window tracked-buffer))
  3408. (tracked-buffer-line-pos))
  3409. (with-current-buffer tracked-buffer
  3410. (set (make-local-variable 'overlay-arrow-string) "=>")
  3411. (set (make-local-variable 'overlay-arrow-position) (make-marker))
  3412. (setq tracked-buffer-line-pos (progn
  3413. (goto-char (point-min))
  3414. (forward-line (1- line-number))
  3415. (point-marker)))
  3416. (when tracked-buffer-window
  3417. (set-window-point
  3418. tracked-buffer-window tracked-buffer-line-pos))
  3419. (set-marker overlay-arrow-position tracked-buffer-line-pos))
  3420. (pop-to-buffer tracked-buffer)
  3421. (switch-to-buffer-other-window shell-buffer))
  3422. (when python-pdbtrack-tracked-buffer
  3423. (with-current-buffer python-pdbtrack-tracked-buffer
  3424. (set-marker overlay-arrow-position nil))
  3425. (mapc #'(lambda (buffer)
  3426. (ignore-errors (kill-buffer buffer)))
  3427. python-pdbtrack-buffers-to-kill)
  3428. (setq python-pdbtrack-tracked-buffer nil
  3429. python-pdbtrack-buffers-to-kill nil)))))
  3430. output)
  3431. ;;; Symbol completion
  3432. (defun python-completion-at-point ()
  3433. "Function for `completion-at-point-functions' in `python-mode'.
  3434. For this to work as best as possible you should call
  3435. `python-shell-send-buffer' from time to time so context in
  3436. inferior Python process is updated properly."
  3437. (let ((process (python-shell-get-process)))
  3438. (when process
  3439. (python-shell-completion-at-point process))))
  3440. (define-obsolete-function-alias
  3441. 'python-completion-complete-at-point
  3442. 'python-completion-at-point
  3443. "25.1")
  3444. ;;; Fill paragraph
  3445. (defcustom python-fill-comment-function 'python-fill-comment
  3446. "Function to fill comments.
  3447. This is the function used by `python-fill-paragraph' to
  3448. fill comments."
  3449. :type 'symbol
  3450. :group 'python)
  3451. (defcustom python-fill-string-function 'python-fill-string
  3452. "Function to fill strings.
  3453. This is the function used by `python-fill-paragraph' to
  3454. fill strings."
  3455. :type 'symbol
  3456. :group 'python)
  3457. (defcustom python-fill-decorator-function 'python-fill-decorator
  3458. "Function to fill decorators.
  3459. This is the function used by `python-fill-paragraph' to
  3460. fill decorators."
  3461. :type 'symbol
  3462. :group 'python)
  3463. (defcustom python-fill-paren-function 'python-fill-paren
  3464. "Function to fill parens.
  3465. This is the function used by `python-fill-paragraph' to
  3466. fill parens."
  3467. :type 'symbol
  3468. :group 'python)
  3469. (defcustom python-fill-docstring-style 'pep-257
  3470. "Style used to fill docstrings.
  3471. This affects `python-fill-string' behavior with regards to
  3472. triple quotes positioning.
  3473. Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
  3474. `symmetric', and nil. A value of nil won't care about quotes
  3475. position and will treat docstrings a normal string, any other
  3476. value may result in one of the following docstring styles:
  3477. `django':
  3478. \"\"\"
  3479. Process foo, return bar.
  3480. \"\"\"
  3481. \"\"\"
  3482. Process foo, return bar.
  3483. If processing fails throw ProcessingError.
  3484. \"\"\"
  3485. `onetwo':
  3486. \"\"\"Process foo, return bar.\"\"\"
  3487. \"\"\"
  3488. Process foo, return bar.
  3489. If processing fails throw ProcessingError.
  3490. \"\"\"
  3491. `pep-257':
  3492. \"\"\"Process foo, return bar.\"\"\"
  3493. \"\"\"Process foo, return bar.
  3494. If processing fails throw ProcessingError.
  3495. \"\"\"
  3496. `pep-257-nn':
  3497. \"\"\"Process foo, return bar.\"\"\"
  3498. \"\"\"Process foo, return bar.
  3499. If processing fails throw ProcessingError.
  3500. \"\"\"
  3501. `symmetric':
  3502. \"\"\"Process foo, return bar.\"\"\"
  3503. \"\"\"
  3504. Process foo, return bar.
  3505. If processing fails throw ProcessingError.
  3506. \"\"\""
  3507. :type '(choice
  3508. (const :tag "Don't format docstrings" nil)
  3509. (const :tag "Django's coding standards style." django)
  3510. (const :tag "One newline and start and Two at end style." onetwo)
  3511. (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
  3512. (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
  3513. (const :tag "Symmetric style." symmetric))
  3514. :group 'python
  3515. :safe (lambda (val)
  3516. (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
  3517. (defun python-fill-paragraph (&optional justify)
  3518. "`fill-paragraph-function' handling multi-line strings and possibly comments.
  3519. If any of the current line is in or at the end of a multi-line string,
  3520. fill the string or the paragraph of it that point is in, preserving
  3521. the string's indentation.
  3522. Optional argument JUSTIFY defines if the paragraph should be justified."
  3523. (interactive "P")
  3524. (save-excursion
  3525. (cond
  3526. ;; Comments
  3527. ((python-syntax-context 'comment)
  3528. (funcall python-fill-comment-function justify))
  3529. ;; Strings/Docstrings
  3530. ((save-excursion (or (python-syntax-context 'string)
  3531. (equal (string-to-syntax "|")
  3532. (syntax-after (point)))))
  3533. (funcall python-fill-string-function justify))
  3534. ;; Decorators
  3535. ((equal (char-after (save-excursion
  3536. (python-nav-beginning-of-statement))) ?@)
  3537. (funcall python-fill-decorator-function justify))
  3538. ;; Parens
  3539. ((or (python-syntax-context 'paren)
  3540. (looking-at (python-rx open-paren))
  3541. (save-excursion
  3542. (skip-syntax-forward "^(" (line-end-position))
  3543. (looking-at (python-rx open-paren))))
  3544. (funcall python-fill-paren-function justify))
  3545. (t t))))
  3546. (defun python-fill-comment (&optional justify)
  3547. "Comment fill function for `python-fill-paragraph'.
  3548. JUSTIFY should be used (if applicable) as in `fill-paragraph'."
  3549. (fill-comment-paragraph justify))
  3550. (defun python-fill-string (&optional justify)
  3551. "String fill function for `python-fill-paragraph'.
  3552. JUSTIFY should be used (if applicable) as in `fill-paragraph'."
  3553. (let* ((str-start-pos
  3554. (set-marker
  3555. (make-marker)
  3556. (or (python-syntax-context 'string)
  3557. (and (equal (string-to-syntax "|")
  3558. (syntax-after (point)))
  3559. (point)))))
  3560. (num-quotes (python-syntax-count-quotes
  3561. (char-after str-start-pos) str-start-pos))
  3562. (str-end-pos
  3563. (save-excursion
  3564. (goto-char (+ str-start-pos num-quotes))
  3565. (or (re-search-forward (rx (syntax string-delimiter)) nil t)
  3566. (goto-char (point-max)))
  3567. (point-marker)))
  3568. (multi-line-p
  3569. ;; Docstring styles may vary for oneliners and multi-liners.
  3570. (> (count-matches "\n" str-start-pos str-end-pos) 0))
  3571. (delimiters-style
  3572. (pcase python-fill-docstring-style
  3573. ;; delimiters-style is a cons cell with the form
  3574. ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
  3575. ;; is NIL means to not add any newlines for start or end
  3576. ;; of docstring. See `python-fill-docstring-style' for a
  3577. ;; graphic idea of each style.
  3578. (`django (cons 1 1))
  3579. (`onetwo (and multi-line-p (cons 1 2)))
  3580. (`pep-257 (and multi-line-p (cons nil 2)))
  3581. (`pep-257-nn (and multi-line-p (cons nil 1)))
  3582. (`symmetric (and multi-line-p (cons 1 1)))))
  3583. (fill-paragraph-function))
  3584. (save-restriction
  3585. (narrow-to-region str-start-pos str-end-pos)
  3586. (fill-paragraph justify))
  3587. (save-excursion
  3588. (when (and (python-info-docstring-p) python-fill-docstring-style)
  3589. ;; Add the number of newlines indicated by the selected style
  3590. ;; at the start of the docstring.
  3591. (goto-char (+ str-start-pos num-quotes))
  3592. (delete-region (point) (progn
  3593. (skip-syntax-forward "> ")
  3594. (point)))
  3595. (and (car delimiters-style)
  3596. (or (newline (car delimiters-style)) t)
  3597. ;; Indent only if a newline is added.
  3598. (indent-according-to-mode))
  3599. ;; Add the number of newlines indicated by the selected style
  3600. ;; at the end of the docstring.
  3601. (goto-char (if (not (= str-end-pos (point-max)))
  3602. (- str-end-pos num-quotes)
  3603. str-end-pos))
  3604. (delete-region (point) (progn
  3605. (skip-syntax-backward "> ")
  3606. (point)))
  3607. (and (cdr delimiters-style)
  3608. ;; Add newlines only if string ends.
  3609. (not (= str-end-pos (point-max)))
  3610. (or (newline (cdr delimiters-style)) t)
  3611. ;; Again indent only if a newline is added.
  3612. (indent-according-to-mode))))) t)
  3613. (defun python-fill-decorator (&optional _justify)
  3614. "Decorator fill function for `python-fill-paragraph'.
  3615. JUSTIFY should be used (if applicable) as in `fill-paragraph'."
  3616. t)
  3617. (defun python-fill-paren (&optional justify)
  3618. "Paren fill function for `python-fill-paragraph'.
  3619. JUSTIFY should be used (if applicable) as in `fill-paragraph'."
  3620. (save-restriction
  3621. (narrow-to-region (progn
  3622. (while (python-syntax-context 'paren)
  3623. (goto-char (1- (point))))
  3624. (line-beginning-position))
  3625. (progn
  3626. (when (not (python-syntax-context 'paren))
  3627. (end-of-line)
  3628. (when (not (python-syntax-context 'paren))
  3629. (skip-syntax-backward "^)")))
  3630. (while (and (python-syntax-context 'paren)
  3631. (not (eobp)))
  3632. (goto-char (1+ (point))))
  3633. (point)))
  3634. (let ((paragraph-start "\f\\|[ \t]*$")
  3635. (paragraph-separate ",")
  3636. (fill-paragraph-function))
  3637. (goto-char (point-min))
  3638. (fill-paragraph justify))
  3639. (while (not (eobp))
  3640. (forward-line 1)
  3641. (python-indent-line)
  3642. (goto-char (line-end-position))))
  3643. t)
  3644. ;;; Skeletons
  3645. (defcustom python-skeleton-autoinsert nil
  3646. "Non-nil means template skeletons will be automagically inserted.
  3647. This happens when pressing \"if<SPACE>\", for example, to prompt for
  3648. the if condition."
  3649. :type 'boolean
  3650. :group 'python
  3651. :safe 'booleanp)
  3652. (define-obsolete-variable-alias
  3653. 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
  3654. (defvar python-skeleton-available '()
  3655. "Internal list of available skeletons.")
  3656. (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
  3657. "Abbrev table for Python mode skeletons."
  3658. :case-fixed t
  3659. ;; Allow / inside abbrevs.
  3660. :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
  3661. ;; Only expand in code.
  3662. :enable-function (lambda ()
  3663. (and
  3664. (not (python-syntax-comment-or-string-p))
  3665. python-skeleton-autoinsert)))
  3666. (defmacro python-skeleton-define (name doc &rest skel)
  3667. "Define a `python-mode' skeleton using NAME DOC and SKEL.
  3668. The skeleton will be bound to python-skeleton-NAME and will
  3669. be added to `python-mode-skeleton-abbrev-table'."
  3670. (declare (indent 2))
  3671. (let* ((name (symbol-name name))
  3672. (function-name (intern (concat "python-skeleton-" name))))
  3673. `(progn
  3674. (define-abbrev python-mode-skeleton-abbrev-table
  3675. ,name "" ',function-name :system t)
  3676. (setq python-skeleton-available
  3677. (cons ',function-name python-skeleton-available))
  3678. (define-skeleton ,function-name
  3679. ,(or doc
  3680. (format "Insert %s statement." name))
  3681. ,@skel))))
  3682. (define-abbrev-table 'python-mode-abbrev-table ()
  3683. "Abbrev table for Python mode."
  3684. :parents (list python-mode-skeleton-abbrev-table))
  3685. (defmacro python-define-auxiliary-skeleton (name &optional doc &rest skel)
  3686. "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
  3687. The skeleton will be bound to python-skeleton-NAME."
  3688. (declare (indent 2))
  3689. (let* ((name (symbol-name name))
  3690. (function-name (intern (concat "python-skeleton--" name)))
  3691. (msg (funcall (if (fboundp 'format-message) #'format-message #'format)
  3692. "Add `%s' clause? " name)))
  3693. (when (not skel)
  3694. (setq skel
  3695. `(< ,(format "%s:" name) \n \n
  3696. > _ \n)))
  3697. `(define-skeleton ,function-name
  3698. ,(or doc
  3699. (format "Auxiliary skeleton for %s statement." name))
  3700. nil
  3701. (unless (y-or-n-p ,msg)
  3702. (signal 'quit t))
  3703. ,@skel)))
  3704. (python-define-auxiliary-skeleton else)
  3705. (python-define-auxiliary-skeleton except)
  3706. (python-define-auxiliary-skeleton finally)
  3707. (python-skeleton-define if nil
  3708. "Condition: "
  3709. "if " str ":" \n
  3710. _ \n
  3711. ("other condition, %s: "
  3712. <
  3713. "elif " str ":" \n
  3714. > _ \n nil)
  3715. '(python-skeleton--else) | ^)
  3716. (python-skeleton-define while nil
  3717. "Condition: "
  3718. "while " str ":" \n
  3719. > _ \n
  3720. '(python-skeleton--else) | ^)
  3721. (python-skeleton-define for nil
  3722. "Iteration spec: "
  3723. "for " str ":" \n
  3724. > _ \n
  3725. '(python-skeleton--else) | ^)
  3726. (python-skeleton-define import nil
  3727. "Import from module: "
  3728. "from " str & " " | -5
  3729. "import "
  3730. ("Identifier: " str ", ") -2 \n _)
  3731. (python-skeleton-define try nil
  3732. nil
  3733. "try:" \n
  3734. > _ \n
  3735. ("Exception, %s: "
  3736. <
  3737. "except " str ":" \n
  3738. > _ \n nil)
  3739. resume:
  3740. '(python-skeleton--except)
  3741. '(python-skeleton--else)
  3742. '(python-skeleton--finally) | ^)
  3743. (python-skeleton-define def nil
  3744. "Function name: "
  3745. "def " str "(" ("Parameter, %s: "
  3746. (unless (equal ?\( (char-before)) ", ")
  3747. str) "):" \n
  3748. "\"\"\"" - "\"\"\"" \n
  3749. > _ \n)
  3750. (python-skeleton-define class nil
  3751. "Class name: "
  3752. "class " str "(" ("Inheritance, %s: "
  3753. (unless (equal ?\( (char-before)) ", ")
  3754. str)
  3755. & ")" | -1
  3756. ":" \n
  3757. "\"\"\"" - "\"\"\"" \n
  3758. > _ \n)
  3759. (defun python-skeleton-add-menu-items ()
  3760. "Add menu items to Python->Skeletons menu."
  3761. (let ((skeletons (sort python-skeleton-available 'string<)))
  3762. (dolist (skeleton skeletons)
  3763. (easy-menu-add-item
  3764. nil '("Python" "Skeletons")
  3765. `[,(format
  3766. "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
  3767. ,skeleton t]))))
  3768. ;;; FFAP
  3769. (defcustom python-ffap-setup-code
  3770. "
  3771. def __FFAP_get_module_path(objstr):
  3772. try:
  3773. import inspect
  3774. import os.path
  3775. # NameError exceptions are delayed until this point.
  3776. obj = eval(objstr)
  3777. module = inspect.getmodule(obj)
  3778. filename = module.__file__
  3779. ext = os.path.splitext(filename)[1]
  3780. if ext in ('.pyc', '.pyo'):
  3781. # Point to the source file.
  3782. filename = filename[:-1]
  3783. if os.path.exists(filename):
  3784. return filename
  3785. return ''
  3786. except:
  3787. return ''"
  3788. "Python code to get a module path."
  3789. :type 'string
  3790. :group 'python)
  3791. (defcustom python-ffap-string-code
  3792. "__FFAP_get_module_path('''%s''')"
  3793. "Python code used to get a string with the path of a module."
  3794. :type 'string
  3795. :group 'python)
  3796. (defun python-ffap-module-path (module)
  3797. "Function for `ffap-alist' to return path for MODULE."
  3798. (let ((process (or
  3799. (and (derived-mode-p 'inferior-python-mode)
  3800. (get-buffer-process (current-buffer)))
  3801. (python-shell-get-process))))
  3802. (if (not process)
  3803. nil
  3804. (let ((module-file
  3805. (python-shell-send-string-no-output
  3806. (concat
  3807. python-ffap-setup-code
  3808. "\nprint (" (format python-ffap-string-code module) ")")
  3809. process)))
  3810. (unless (zerop (length module-file))
  3811. (python-util-strip-string module-file))))))
  3812. (defvar ffap-alist)
  3813. (eval-after-load "ffap"
  3814. '(progn
  3815. (push '(python-mode . python-ffap-module-path) ffap-alist)
  3816. (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
  3817. ;;; Code check
  3818. (defcustom python-check-command
  3819. (or (executable-find "pyflakes")
  3820. (executable-find "epylint")
  3821. "install pyflakes, pylint or something else")
  3822. "Command used to check a Python file."
  3823. :type 'string
  3824. :group 'python)
  3825. (defcustom python-check-buffer-name
  3826. "*Python check: %s*"
  3827. "Buffer name used for check commands."
  3828. :type 'string
  3829. :group 'python)
  3830. (defvar python-check-custom-command nil
  3831. "Internal use.")
  3832. ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
  3833. (make-variable-buffer-local 'python-check-custom-command)
  3834. (defun python-check (command)
  3835. "Check a Python file (default current buffer's file).
  3836. Runs COMMAND, a shell command, as if by `compile'.
  3837. See `python-check-command' for the default."
  3838. (interactive
  3839. (list (read-string "Check command: "
  3840. (or python-check-custom-command
  3841. (concat python-check-command " "
  3842. (shell-quote-argument
  3843. (or
  3844. (let ((name (buffer-file-name)))
  3845. (and name
  3846. (file-name-nondirectory name)))
  3847. "")))))))
  3848. (setq python-check-custom-command command)
  3849. (save-some-buffers (not compilation-ask-about-save) nil)
  3850. (python-shell-with-environment
  3851. (compilation-start command nil
  3852. (lambda (_modename)
  3853. (format python-check-buffer-name command)))))
  3854. ;;; Eldoc
  3855. (defcustom python-eldoc-setup-code
  3856. "def __PYDOC_get_help(obj):
  3857. try:
  3858. import inspect
  3859. try:
  3860. str_type = basestring
  3861. except NameError:
  3862. str_type = str
  3863. if isinstance(obj, str_type):
  3864. obj = eval(obj, globals())
  3865. doc = inspect.getdoc(obj)
  3866. if not doc and callable(obj):
  3867. target = None
  3868. if inspect.isclass(obj) and hasattr(obj, '__init__'):
  3869. target = obj.__init__
  3870. objtype = 'class'
  3871. else:
  3872. target = obj
  3873. objtype = 'def'
  3874. if target:
  3875. args = inspect.formatargspec(
  3876. *inspect.getargspec(target)
  3877. )
  3878. name = obj.__name__
  3879. doc = '{objtype} {name}{args}'.format(
  3880. objtype=objtype, name=name, args=args
  3881. )
  3882. else:
  3883. doc = doc.splitlines()[0]
  3884. except:
  3885. doc = ''
  3886. return doc"
  3887. "Python code to setup documentation retrieval."
  3888. :type 'string
  3889. :group 'python)
  3890. (defcustom python-eldoc-string-code
  3891. "__PYDOC_get_help('''%s''')"
  3892. "Python code used to get a string with the documentation of an object."
  3893. :type 'string
  3894. :group 'python)
  3895. (defun python-eldoc--get-symbol-at-point ()
  3896. "Get the current symbol for eldoc.
  3897. Returns the current symbol handling point within arguments."
  3898. (save-excursion
  3899. (let ((start (python-syntax-context 'paren)))
  3900. (when start
  3901. (goto-char start))
  3902. (when (or start
  3903. (eobp)
  3904. (memq (char-syntax (char-after)) '(?\ ?-)))
  3905. ;; Try to adjust to closest symbol if not in one.
  3906. (python-util-forward-comment -1)))
  3907. (python-info-current-symbol t)))
  3908. (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
  3909. "Internal implementation to get documentation at point.
  3910. If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
  3911. returns will be used. If not FORCE-PROCESS is passed what
  3912. `python-shell-get-process' returns is used."
  3913. (let ((process (or force-process (python-shell-get-process))))
  3914. (when process
  3915. (let* ((input (or force-input
  3916. (python-eldoc--get-symbol-at-point)))
  3917. (docstring
  3918. (when input
  3919. ;; Prevent resizing the echo area when iPython is
  3920. ;; enabled. Bug#18794.
  3921. (python-util-strip-string
  3922. (python-shell-send-string-no-output
  3923. (concat
  3924. python-eldoc-setup-code
  3925. "\nprint(" (format python-eldoc-string-code input) ")")
  3926. process)))))
  3927. (unless (zerop (length docstring))
  3928. docstring)))))
  3929. (defvar-local python-eldoc-get-doc t
  3930. "Non-nil means eldoc should fetch the documentation
  3931. automatically. Set to nil by `python-eldoc-function' if
  3932. `python-eldoc-function-timeout-permanent' is non-nil and
  3933. `python-eldoc-function' times out.")
  3934. (defcustom python-eldoc-function-timeout 1
  3935. "Timeout for `python-eldoc-function' in seconds."
  3936. :group 'python
  3937. :type 'integer
  3938. :version "25.1")
  3939. (defcustom python-eldoc-function-timeout-permanent t
  3940. "Non-nil means that when `python-eldoc-function' times out
  3941. `python-eldoc-get-doc' will be set to nil"
  3942. :group 'python
  3943. :type 'boolean
  3944. :version "25.1")
  3945. (defun python-eldoc-function ()
  3946. "`eldoc-documentation-function' for Python.
  3947. For this to work as best as possible you should call
  3948. `python-shell-send-buffer' from time to time so context in
  3949. inferior Python process is updated properly.
  3950. If `python-eldoc-function-timeout' seconds elapse before this
  3951. function returns then if
  3952. `python-eldoc-function-timeout-permanent' is non-nil
  3953. `python-eldoc-get-doc' will be set to nil and eldoc will no
  3954. longer return the documentation at the point automatically.
  3955. Set `python-eldoc-get-doc' to t to reenable eldoc documentation
  3956. fetching"
  3957. (when python-eldoc-get-doc
  3958. (with-timeout (python-eldoc-function-timeout
  3959. (if python-eldoc-function-timeout-permanent
  3960. (progn
  3961. (message "Eldoc echo-area display muted in this buffer, see `python-eldoc-function'")
  3962. (setq python-eldoc-get-doc nil))
  3963. (message "`python-eldoc-function' timed out, see `python-eldoc-function-timeout'")))
  3964. (python-eldoc--get-doc-at-point))))
  3965. (defun python-eldoc-at-point (symbol)
  3966. "Get help on SYMBOL using `help'.
  3967. Interactively, prompt for symbol."
  3968. (interactive
  3969. (let ((symbol (python-eldoc--get-symbol-at-point))
  3970. (enable-recursive-minibuffers t))
  3971. (list (read-string (if symbol
  3972. (format "Describe symbol (default %s): " symbol)
  3973. "Describe symbol: ")
  3974. nil nil symbol))))
  3975. (message (python-eldoc--get-doc-at-point symbol)))
  3976. (defun python-describe-at-point (symbol process)
  3977. (interactive (list (python-info-current-symbol)
  3978. (python-shell-get-process)))
  3979. (comint-send-string process (concat "help('" symbol "')\n")))
  3980. ;;; Hideshow
  3981. (defun python-hideshow-forward-sexp-function (arg)
  3982. "Python specific `forward-sexp' function for `hs-minor-mode'.
  3983. Argument ARG is ignored."
  3984. arg ; Shut up, byte compiler.
  3985. (python-nav-end-of-defun)
  3986. (unless (python-info-current-line-empty-p)
  3987. (backward-char)))
  3988. ;;; Imenu
  3989. (defvar python-imenu-format-item-label-function
  3990. 'python-imenu-format-item-label
  3991. "Imenu function used to format an item label.
  3992. It must be a function with two arguments: TYPE and NAME.")
  3993. (defvar python-imenu-format-parent-item-label-function
  3994. 'python-imenu-format-parent-item-label
  3995. "Imenu function used to format a parent item label.
  3996. It must be a function with two arguments: TYPE and NAME.")
  3997. (defvar python-imenu-format-parent-item-jump-label-function
  3998. 'python-imenu-format-parent-item-jump-label
  3999. "Imenu function used to format a parent jump item label.
  4000. It must be a function with two arguments: TYPE and NAME.")
  4001. (defun python-imenu-format-item-label (type name)
  4002. "Return Imenu label for single node using TYPE and NAME."
  4003. (format "%s (%s)" name type))
  4004. (defun python-imenu-format-parent-item-label (type name)
  4005. "Return Imenu label for parent node using TYPE and NAME."
  4006. (format "%s..." (python-imenu-format-item-label type name)))
  4007. (defun python-imenu-format-parent-item-jump-label (type _name)
  4008. "Return Imenu label for parent node jump using TYPE and NAME."
  4009. (if (string= type "class")
  4010. "*class definition*"
  4011. "*function definition*"))
  4012. (defun python-imenu--get-defun-type-name ()
  4013. "Return defun type and name at current position."
  4014. (when (looking-at python-nav-beginning-of-defun-regexp)
  4015. (let ((split (split-string (match-string-no-properties 0))))
  4016. (if (= (length split) 2)
  4017. split
  4018. (list (concat (car split) " " (cadr split))
  4019. (car (last split)))))))
  4020. (defun python-imenu--put-parent (type name pos tree)
  4021. "Add the parent with TYPE, NAME and POS to TREE."
  4022. (let ((label
  4023. (funcall python-imenu-format-item-label-function type name))
  4024. (jump-label
  4025. (funcall python-imenu-format-parent-item-jump-label-function type name)))
  4026. (if (not tree)
  4027. (cons label pos)
  4028. (cons label (cons (cons jump-label pos) tree)))))
  4029. (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
  4030. "Recursively build the tree of nested definitions of a node.
  4031. Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
  4032. not be passed explicitly unless you know what you are doing."
  4033. (setq min-indent (or min-indent 0)
  4034. prev-indent (or prev-indent python-indent-offset))
  4035. (let* ((pos (python-nav-backward-defun))
  4036. (defun-type-name (and pos (python-imenu--get-defun-type-name)))
  4037. (type (car defun-type-name))
  4038. (name (cadr defun-type-name))
  4039. (label (when name
  4040. (funcall python-imenu-format-item-label-function type name)))
  4041. (indent (current-indentation))
  4042. (children-indent-limit (+ python-indent-offset min-indent)))
  4043. (cond ((not pos)
  4044. ;; Nothing found, probably near to bobp.
  4045. nil)
  4046. ((<= indent min-indent)
  4047. ;; The current indentation points that this is a parent
  4048. ;; node, add it to the tree and stop recursing.
  4049. (python-imenu--put-parent type name pos tree))
  4050. (t
  4051. (python-imenu--build-tree
  4052. min-indent
  4053. indent
  4054. (if (<= indent children-indent-limit)
  4055. ;; This lies within the children indent offset range,
  4056. ;; so it's a normal child of its parent (i.e., not
  4057. ;; a child of a child).
  4058. (cons (cons label pos) tree)
  4059. ;; Oh no, a child of a child?! Fear not, we
  4060. ;; know how to roll. We recursively parse these by
  4061. ;; swapping prev-indent and min-indent plus adding this
  4062. ;; newly found item to a fresh subtree. This works, I
  4063. ;; promise.
  4064. (cons
  4065. (python-imenu--build-tree
  4066. prev-indent indent (list (cons label pos)))
  4067. tree)))))))
  4068. (defun python-imenu-create-index ()
  4069. "Return tree Imenu alist for the current Python buffer.
  4070. Change `python-imenu-format-item-label-function',
  4071. `python-imenu-format-parent-item-label-function',
  4072. `python-imenu-format-parent-item-jump-label-function' to
  4073. customize how labels are formatted."
  4074. (goto-char (point-max))
  4075. (let ((index)
  4076. (tree))
  4077. (while (setq tree (python-imenu--build-tree))
  4078. (setq index (cons tree index)))
  4079. index))
  4080. (defun python-imenu-create-flat-index (&optional alist prefix)
  4081. "Return flat outline of the current Python buffer for Imenu.
  4082. Optional argument ALIST is the tree to be flattened; when nil
  4083. `python-imenu-build-index' is used with
  4084. `python-imenu-format-parent-item-jump-label-function'
  4085. `python-imenu-format-parent-item-label-function'
  4086. `python-imenu-format-item-label-function' set to
  4087. (lambda (type name) name)
  4088. Optional argument PREFIX is used in recursive calls and should
  4089. not be passed explicitly.
  4090. Converts this:
  4091. ((\"Foo\" . 103)
  4092. (\"Bar\" . 138)
  4093. (\"decorator\"
  4094. (\"decorator\" . 173)
  4095. (\"wrap\"
  4096. (\"wrap\" . 353)
  4097. (\"wrapped_f\" . 393))))
  4098. To this:
  4099. ((\"Foo\" . 103)
  4100. (\"Bar\" . 138)
  4101. (\"decorator\" . 173)
  4102. (\"decorator.wrap\" . 353)
  4103. (\"decorator.wrapped_f\" . 393))"
  4104. ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
  4105. (apply
  4106. 'nconc
  4107. (mapcar
  4108. (lambda (item)
  4109. (let ((name (if prefix
  4110. (concat prefix "." (car item))
  4111. (car item)))
  4112. (pos (cdr item)))
  4113. (cond ((or (numberp pos) (markerp pos))
  4114. (list (cons name pos)))
  4115. ((listp pos)
  4116. (cons
  4117. (cons name (cdar pos))
  4118. (python-imenu-create-flat-index (cddr item) name))))))
  4119. (or alist
  4120. (let* ((fn (lambda (_type name) name))
  4121. (python-imenu-format-item-label-function fn)
  4122. (python-imenu-format-parent-item-label-function fn)
  4123. (python-imenu-format-parent-item-jump-label-function fn))
  4124. (python-imenu-create-index))))))
  4125. ;;; Misc helpers
  4126. (defun python-info-current-defun (&optional include-type)
  4127. "Return name of surrounding function with Python compatible dotty syntax.
  4128. Optional argument INCLUDE-TYPE indicates to include the type of the defun.
  4129. This function can be used as the value of `add-log-current-defun-function'
  4130. since it returns nil if point is not inside a defun."
  4131. (save-restriction
  4132. (prog-widen)
  4133. (save-excursion
  4134. (end-of-line 1)
  4135. (let ((names)
  4136. (starting-indentation (current-indentation))
  4137. (starting-pos (point))
  4138. (first-run t)
  4139. (last-indent)
  4140. (type))
  4141. (catch 'exit
  4142. (while (python-nav-beginning-of-defun 1)
  4143. (when (save-match-data
  4144. (and
  4145. (or (not last-indent)
  4146. (< (current-indentation) last-indent))
  4147. (or
  4148. (and first-run
  4149. (save-excursion
  4150. ;; If this is the first run, we may add
  4151. ;; the current defun at point.
  4152. (setq first-run nil)
  4153. (goto-char starting-pos)
  4154. (python-nav-beginning-of-statement)
  4155. (beginning-of-line 1)
  4156. (looking-at-p
  4157. python-nav-beginning-of-defun-regexp)))
  4158. (< starting-pos
  4159. (save-excursion
  4160. (let ((min-indent
  4161. (+ (current-indentation)
  4162. python-indent-offset)))
  4163. (if (< starting-indentation min-indent)
  4164. ;; If the starting indentation is not
  4165. ;; within the min defun indent make the
  4166. ;; check fail.
  4167. starting-pos
  4168. ;; Else go to the end of defun and add
  4169. ;; up the current indentation to the
  4170. ;; ending position.
  4171. (python-nav-end-of-defun)
  4172. (+ (point)
  4173. (if (>= (current-indentation) min-indent)
  4174. (1+ (current-indentation))
  4175. 0)))))))))
  4176. (save-match-data (setq last-indent (current-indentation)))
  4177. (if (or (not include-type) type)
  4178. (setq names (cons (match-string-no-properties 1) names))
  4179. (let ((match (split-string (match-string-no-properties 0))))
  4180. (setq type (car match))
  4181. (setq names (cons (cadr match) names)))))
  4182. ;; Stop searching ASAP.
  4183. (and (= (current-indentation) 0) (throw 'exit t))))
  4184. (and names
  4185. (concat (and type (format "%s " type))
  4186. (mapconcat 'identity names ".")))))))
  4187. (defun python-info-current-symbol (&optional replace-self)
  4188. "Return current symbol using dotty syntax.
  4189. With optional argument REPLACE-SELF convert \"self\" to current
  4190. parent defun name."
  4191. (let ((name
  4192. (and (not (python-syntax-comment-or-string-p))
  4193. (with-syntax-table python-dotty-syntax-table
  4194. (let ((sym (symbol-at-point)))
  4195. (and sym
  4196. (substring-no-properties (symbol-name sym))))))))
  4197. (when name
  4198. (if (not replace-self)
  4199. name
  4200. (let ((current-defun (python-info-current-defun)))
  4201. (if (not current-defun)
  4202. name
  4203. (replace-regexp-in-string
  4204. (python-rx line-start word-start "self" word-end ?.)
  4205. (concat
  4206. (mapconcat 'identity
  4207. (butlast (split-string current-defun "\\."))
  4208. ".") ".")
  4209. name)))))))
  4210. (defun python-info-statement-starts-block-p ()
  4211. "Return non-nil if current statement opens a block."
  4212. (save-excursion
  4213. (python-nav-beginning-of-statement)
  4214. (looking-at (python-rx block-start))))
  4215. (defun python-info-statement-ends-block-p ()
  4216. "Return non-nil if point is at end of block."
  4217. (let ((end-of-block-pos (save-excursion
  4218. (python-nav-end-of-block)))
  4219. (end-of-statement-pos (save-excursion
  4220. (python-nav-end-of-statement))))
  4221. (and end-of-block-pos end-of-statement-pos
  4222. (= end-of-block-pos end-of-statement-pos))))
  4223. (defun python-info-beginning-of-statement-p ()
  4224. "Return non-nil if point is at beginning of statement."
  4225. (= (point) (save-excursion
  4226. (python-nav-beginning-of-statement)
  4227. (point))))
  4228. (defun python-info-end-of-statement-p ()
  4229. "Return non-nil if point is at end of statement."
  4230. (= (point) (save-excursion
  4231. (python-nav-end-of-statement)
  4232. (point))))
  4233. (defun python-info-beginning-of-block-p ()
  4234. "Return non-nil if point is at beginning of block."
  4235. (and (python-info-beginning-of-statement-p)
  4236. (python-info-statement-starts-block-p)))
  4237. (defun python-info-end-of-block-p ()
  4238. "Return non-nil if point is at end of block."
  4239. (and (python-info-end-of-statement-p)
  4240. (python-info-statement-ends-block-p)))
  4241. (define-obsolete-function-alias
  4242. 'python-info-closing-block
  4243. 'python-info-dedenter-opening-block-position "24.4")
  4244. (defun python-info-dedenter-opening-block-position ()
  4245. "Return the point of the closest block the current line closes.
  4246. Returns nil if point is not on a dedenter statement or no opening
  4247. block can be detected. The latter case meaning current file is
  4248. likely an invalid python file."
  4249. (let ((positions (python-info-dedenter-opening-block-positions))
  4250. (indentation (current-indentation))
  4251. (position))
  4252. (while (and (not position)
  4253. positions)
  4254. (save-excursion
  4255. (goto-char (car positions))
  4256. (if (<= (current-indentation) indentation)
  4257. (setq position (car positions))
  4258. (setq positions (cdr positions)))))
  4259. position))
  4260. (defun python-info-dedenter-opening-block-positions ()
  4261. "Return points of blocks the current line may close sorted by closer.
  4262. Returns nil if point is not on a dedenter statement or no opening
  4263. block can be detected. The latter case meaning current file is
  4264. likely an invalid python file."
  4265. (save-excursion
  4266. (let ((dedenter-pos (python-info-dedenter-statement-p)))
  4267. (when dedenter-pos
  4268. (goto-char dedenter-pos)
  4269. (let* ((cur-line (line-beginning-position))
  4270. (pairs '(("elif" "elif" "if")
  4271. ("else" "if" "elif" "except" "for" "while")
  4272. ("except" "except" "try")
  4273. ("finally" "else" "except" "try")))
  4274. (dedenter (match-string-no-properties 0))
  4275. (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
  4276. (collected-indentations)
  4277. (opening-blocks))
  4278. (catch 'exit
  4279. (while (python-nav--syntactically
  4280. (lambda ()
  4281. (re-search-backward (python-rx block-start) nil t))
  4282. #'<)
  4283. (let ((indentation (current-indentation)))
  4284. (when (and (not (memq indentation collected-indentations))
  4285. (or (not collected-indentations)
  4286. (< indentation (apply #'min collected-indentations)))
  4287. ;; There must be no line with indentation
  4288. ;; smaller than `indentation' (except for
  4289. ;; blank lines) between the found opening
  4290. ;; block and the current line, otherwise it
  4291. ;; is not an opening block.
  4292. (save-excursion
  4293. (forward-line)
  4294. (let ((no-back-indent t))
  4295. (save-match-data
  4296. (while (and (< (point) cur-line)
  4297. (setq no-back-indent
  4298. (or (> (current-indentation) indentation)
  4299. (python-info-current-line-empty-p))))
  4300. (forward-line)))
  4301. no-back-indent)))
  4302. (setq collected-indentations
  4303. (cons indentation collected-indentations))
  4304. (when (member (match-string-no-properties 0)
  4305. possible-opening-blocks)
  4306. (setq opening-blocks (cons (point) opening-blocks))))
  4307. (when (zerop indentation)
  4308. (throw 'exit nil)))))
  4309. ;; sort by closer
  4310. (nreverse opening-blocks))))))
  4311. (define-obsolete-function-alias
  4312. 'python-info-closing-block-message
  4313. 'python-info-dedenter-opening-block-message "24.4")
  4314. (defun python-info-dedenter-opening-block-message ()
  4315. "Message the first line of the block the current statement closes."
  4316. (let ((point (python-info-dedenter-opening-block-position)))
  4317. (when point
  4318. (save-restriction
  4319. (prog-widen)
  4320. (message "Closes %s" (save-excursion
  4321. (goto-char point)
  4322. (buffer-substring
  4323. (point) (line-end-position))))))))
  4324. (defun python-info-dedenter-statement-p ()
  4325. "Return point if current statement is a dedenter.
  4326. Sets `match-data' to the keyword that starts the dedenter
  4327. statement."
  4328. (save-excursion
  4329. (python-nav-beginning-of-statement)
  4330. (when (and (not (python-syntax-context-type))
  4331. (looking-at (python-rx dedenter)))
  4332. (point))))
  4333. (defun python-info-line-ends-backslash-p (&optional line-number)
  4334. "Return non-nil if current line ends with backslash.
  4335. With optional argument LINE-NUMBER, check that line instead."
  4336. (save-excursion
  4337. (save-restriction
  4338. (prog-widen)
  4339. (when line-number
  4340. (python-util-goto-line line-number))
  4341. (while (and (not (eobp))
  4342. (goto-char (line-end-position))
  4343. (python-syntax-context 'paren)
  4344. (not (equal (char-before (point)) ?\\)))
  4345. (forward-line 1))
  4346. (when (equal (char-before) ?\\)
  4347. (point-marker)))))
  4348. (defun python-info-beginning-of-backslash (&optional line-number)
  4349. "Return the point where the backslashed line start.
  4350. Optional argument LINE-NUMBER forces the line number to check against."
  4351. (save-excursion
  4352. (save-restriction
  4353. (prog-widen)
  4354. (when line-number
  4355. (python-util-goto-line line-number))
  4356. (when (python-info-line-ends-backslash-p)
  4357. (while (save-excursion
  4358. (goto-char (line-beginning-position))
  4359. (python-syntax-context 'paren))
  4360. (forward-line -1))
  4361. (back-to-indentation)
  4362. (point-marker)))))
  4363. (defun python-info-continuation-line-p ()
  4364. "Check if current line is continuation of another.
  4365. When current line is continuation of another return the point
  4366. where the continued line ends."
  4367. (save-excursion
  4368. (save-restriction
  4369. (prog-widen)
  4370. (let* ((context-type (progn
  4371. (back-to-indentation)
  4372. (python-syntax-context-type)))
  4373. (line-start (line-number-at-pos))
  4374. (context-start (when context-type
  4375. (python-syntax-context context-type))))
  4376. (cond ((equal context-type 'paren)
  4377. ;; Lines inside a paren are always a continuation line
  4378. ;; (except the first one).
  4379. (python-util-forward-comment -1)
  4380. (point-marker))
  4381. ((member context-type '(string comment))
  4382. ;; move forward an roll again
  4383. (goto-char context-start)
  4384. (python-util-forward-comment)
  4385. (python-info-continuation-line-p))
  4386. (t
  4387. ;; Not within a paren, string or comment, the only way
  4388. ;; we are dealing with a continuation line is that
  4389. ;; previous line contains a backslash, and this can
  4390. ;; only be the previous line from current
  4391. (back-to-indentation)
  4392. (python-util-forward-comment -1)
  4393. (when (and (equal (1- line-start) (line-number-at-pos))
  4394. (python-info-line-ends-backslash-p))
  4395. (point-marker))))))))
  4396. (defun python-info-block-continuation-line-p ()
  4397. "Return non-nil if current line is a continuation of a block."
  4398. (save-excursion
  4399. (when (python-info-continuation-line-p)
  4400. (forward-line -1)
  4401. (back-to-indentation)
  4402. (when (looking-at (python-rx block-start))
  4403. (point-marker)))))
  4404. (defun python-info-assignment-statement-p (&optional current-line-only)
  4405. "Check if current line is an assignment.
  4406. With argument CURRENT-LINE-ONLY is non-nil, don't follow any
  4407. continuations, just check the if current line is an assignment."
  4408. (save-excursion
  4409. (let ((found nil))
  4410. (if current-line-only
  4411. (back-to-indentation)
  4412. (python-nav-beginning-of-statement))
  4413. (while (and
  4414. (re-search-forward (python-rx not-simple-operator
  4415. assignment-operator
  4416. (group not-simple-operator))
  4417. (line-end-position) t)
  4418. (not found))
  4419. (save-excursion
  4420. ;; The assignment operator should not be inside a string.
  4421. (backward-char (length (match-string-no-properties 1)))
  4422. (setq found (not (python-syntax-context-type)))))
  4423. (when found
  4424. (skip-syntax-forward " ")
  4425. (point-marker)))))
  4426. ;; TODO: rename to clarify this is only for the first continuation
  4427. ;; line or remove it and move its body to `python-indent-context'.
  4428. (defun python-info-assignment-continuation-line-p ()
  4429. "Check if current line is the first continuation of an assignment.
  4430. When current line is continuation of another with an assignment
  4431. return the point of the first non-blank character after the
  4432. operator."
  4433. (save-excursion
  4434. (when (python-info-continuation-line-p)
  4435. (forward-line -1)
  4436. (python-info-assignment-statement-p t))))
  4437. (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
  4438. "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
  4439. (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
  4440. (save-excursion
  4441. (beginning-of-line 1)
  4442. (looking-at python-nav-beginning-of-defun-regexp))))
  4443. (defun python-info-current-line-comment-p ()
  4444. "Return non-nil if current line is a comment line."
  4445. (char-equal
  4446. (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
  4447. ?#))
  4448. (defun python-info-current-line-empty-p ()
  4449. "Return non-nil if current line is empty, ignoring whitespace."
  4450. (save-excursion
  4451. (beginning-of-line 1)
  4452. (looking-at
  4453. (python-rx line-start (* whitespace)
  4454. (group (* not-newline))
  4455. (* whitespace) line-end))
  4456. (string-equal "" (match-string-no-properties 1))))
  4457. (defun python-info-docstring-p (&optional syntax-ppss)
  4458. "Return non-nil if point is in a docstring.
  4459. When optional argument SYNTAX-PPSS is given, use that instead of
  4460. point's current `syntax-ppss'."
  4461. ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
  4462. (save-excursion
  4463. (when (and syntax-ppss (python-syntax-context 'string syntax-ppss))
  4464. (goto-char (nth 8 syntax-ppss)))
  4465. (python-nav-beginning-of-statement)
  4466. (let ((counter 1)
  4467. (indentation (current-indentation))
  4468. (backward-sexp-point)
  4469. (re (concat "[uU]?[rR]?"
  4470. (python-rx string-delimiter))))
  4471. (when (and
  4472. (not (python-info-assignment-statement-p))
  4473. (looking-at-p re)
  4474. ;; Allow up to two consecutive docstrings only.
  4475. (>=
  4476. 2
  4477. (let (last-backward-sexp-point)
  4478. (while (save-excursion
  4479. (python-nav-backward-sexp)
  4480. (setq backward-sexp-point (point))
  4481. (and (= indentation (current-indentation))
  4482. ;; Make sure we're always moving point.
  4483. ;; If we get stuck in the same position
  4484. ;; on consecutive loop iterations,
  4485. ;; bail out.
  4486. (prog1 (not (eql last-backward-sexp-point
  4487. backward-sexp-point))
  4488. (setq last-backward-sexp-point
  4489. backward-sexp-point))
  4490. (looking-at-p
  4491. (concat "[uU]?[rR]?"
  4492. (python-rx string-delimiter)))))
  4493. ;; Previous sexp was a string, restore point.
  4494. (goto-char backward-sexp-point)
  4495. (cl-incf counter))
  4496. counter)))
  4497. (python-util-forward-comment -1)
  4498. (python-nav-beginning-of-statement)
  4499. (cond ((bobp))
  4500. ((python-info-assignment-statement-p) t)
  4501. ((python-info-looking-at-beginning-of-defun))
  4502. (t nil))))))
  4503. (defun python-info-encoding-from-cookie ()
  4504. "Detect current buffer's encoding from its coding cookie.
  4505. Returns the encoding as a symbol."
  4506. (let ((first-two-lines
  4507. (save-excursion
  4508. (save-restriction
  4509. (widen)
  4510. (goto-char (point-min))
  4511. (forward-line 2)
  4512. (buffer-substring-no-properties
  4513. (point)
  4514. (point-min))))))
  4515. (when (string-match (python-rx coding-cookie) first-two-lines)
  4516. (intern (match-string-no-properties 1 first-two-lines)))))
  4517. (defun python-info-encoding ()
  4518. "Return encoding for file.
  4519. Try `python-info-encoding-from-cookie', if none is found then
  4520. default to utf-8."
  4521. ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
  4522. ;; uses ASCII as default while Python 3 uses UTF-8. This means that
  4523. ;; in the worst case scenario python.el will make things work for
  4524. ;; Python 2 files with unicode data and no encoding defined.
  4525. (or (python-info-encoding-from-cookie)
  4526. 'utf-8))
  4527. ;;; Utility functions
  4528. (defun python-util-goto-line (line-number)
  4529. "Move point to LINE-NUMBER."
  4530. (goto-char (point-min))
  4531. (forward-line (1- line-number)))
  4532. ;; Stolen from org-mode
  4533. (defun python-util-clone-local-variables (from-buffer &optional regexp)
  4534. "Clone local variables from FROM-BUFFER.
  4535. Optional argument REGEXP selects variables to clone and defaults
  4536. to \"^python-\"."
  4537. (mapc
  4538. (lambda (pair)
  4539. (and (symbolp (car pair))
  4540. (string-match (or regexp "^python-")
  4541. (symbol-name (car pair)))
  4542. (set (make-local-variable (car pair))
  4543. (cdr pair))))
  4544. (buffer-local-variables from-buffer)))
  4545. (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
  4546. (defun python-util-comint-last-prompt ()
  4547. "Return comint last prompt overlay start and end.
  4548. This is for compatibility with Emacs < 24.4."
  4549. (cond ((bound-and-true-p comint-last-prompt-overlay)
  4550. (cons (overlay-start comint-last-prompt-overlay)
  4551. (overlay-end comint-last-prompt-overlay)))
  4552. ((bound-and-true-p comint-last-prompt)
  4553. comint-last-prompt)
  4554. (t nil)))
  4555. (defun python-util-forward-comment (&optional direction)
  4556. "Python mode specific version of `forward-comment'.
  4557. Optional argument DIRECTION defines the direction to move to."
  4558. (let ((comment-start (python-syntax-context 'comment))
  4559. (factor (if (< (or direction 0) 0)
  4560. -99999
  4561. 99999)))
  4562. (when comment-start
  4563. (goto-char comment-start))
  4564. (forward-comment factor)))
  4565. (defun python-util-list-directories (directory &optional predicate max-depth)
  4566. "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
  4567. Argument PREDICATE defaults to `identity' and must be a function
  4568. that takes one argument (a full path) and returns non-nil for
  4569. allowed files. When optional argument MAX-DEPTH is non-nil, stop
  4570. searching when depth is reached, else don't limit."
  4571. (let* ((dir (expand-file-name directory))
  4572. (dir-length (length dir))
  4573. (predicate (or predicate #'identity))
  4574. (to-scan (list dir))
  4575. (tally nil))
  4576. (while to-scan
  4577. (let ((current-dir (car to-scan)))
  4578. (when (funcall predicate current-dir)
  4579. (setq tally (cons current-dir tally)))
  4580. (setq to-scan (append (cdr to-scan)
  4581. (python-util-list-files
  4582. current-dir #'file-directory-p)
  4583. nil))
  4584. (when (and max-depth
  4585. (<= max-depth
  4586. (length (split-string
  4587. (substring current-dir dir-length)
  4588. "/\\|\\\\" t))))
  4589. (setq to-scan nil))))
  4590. (nreverse tally)))
  4591. (defun python-util-list-files (dir &optional predicate)
  4592. "List files in DIR, filtering with PREDICATE.
  4593. Argument PREDICATE defaults to `identity' and must be a function
  4594. that takes one argument (a full path) and returns non-nil for
  4595. allowed files."
  4596. (let ((dir-name (file-name-as-directory dir)))
  4597. (apply #'nconc
  4598. (mapcar (lambda (file-name)
  4599. (let ((full-file-name (expand-file-name file-name dir-name)))
  4600. (when (and
  4601. (not (member file-name '("." "..")))
  4602. (funcall (or predicate #'identity) full-file-name))
  4603. (list full-file-name))))
  4604. (directory-files dir-name)))))
  4605. (defun python-util-list-packages (dir &optional max-depth)
  4606. "List packages in DIR, limited by MAX-DEPTH.
  4607. When optional argument MAX-DEPTH is non-nil, stop searching when
  4608. depth is reached, else don't limit."
  4609. (let* ((dir (expand-file-name dir))
  4610. (parent-dir (file-name-directory
  4611. (directory-file-name
  4612. (file-name-directory
  4613. (file-name-as-directory dir)))))
  4614. (subpath-length (length parent-dir)))
  4615. (mapcar
  4616. (lambda (file-name)
  4617. (replace-regexp-in-string
  4618. (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
  4619. (python-util-list-directories
  4620. (directory-file-name dir)
  4621. (lambda (dir)
  4622. (file-exists-p (expand-file-name "__init__.py" dir)))
  4623. max-depth))))
  4624. (defun python-util-popn (lst n)
  4625. "Return LST first N elements.
  4626. N should be an integer, when negative its opposite is used.
  4627. When N is bigger than the length of LST, the list is
  4628. returned as is."
  4629. (let* ((n (min (abs n)))
  4630. (len (length lst))
  4631. (acc))
  4632. (if (> n len)
  4633. lst
  4634. (while (< 0 n)
  4635. (setq acc (cons (car lst) acc)
  4636. lst (cdr lst)
  4637. n (1- n)))
  4638. (reverse acc))))
  4639. (defun python-util-strip-string (string)
  4640. "Strip STRING whitespace and newlines from end and beginning."
  4641. (replace-regexp-in-string
  4642. (rx (or (: string-start (* (any whitespace ?\r ?\n)))
  4643. (: (* (any whitespace ?\r ?\n)) string-end)))
  4644. ""
  4645. string))
  4646. (defun python-util-valid-regexp-p (regexp)
  4647. "Return non-nil if REGEXP is valid."
  4648. (ignore-errors (string-match regexp "") t))
  4649. (defun python-electric-pair-string-delimiter ()
  4650. (when (and electric-pair-mode
  4651. (memq last-command-event '(?\" ?\'))
  4652. (let ((count 0))
  4653. (while (eq (char-before (- (point) count)) last-command-event)
  4654. (cl-incf count))
  4655. (= count 3))
  4656. (eq (char-after) last-command-event))
  4657. (save-excursion (insert (make-string 2 last-command-event)))))
  4658. (defvar electric-indent-inhibit)
  4659. ;;;###autoload
  4660. (define-derived-mode python-mode prog-mode "Python"
  4661. "Major mode for editing Python files.
  4662. \\{python-mode-map}"
  4663. (set (make-local-variable 'tab-width) 8)
  4664. (set (make-local-variable 'indent-tabs-mode) nil)
  4665. (set (make-local-variable 'comment-start) "# ")
  4666. (set (make-local-variable 'comment-start-skip) "#+\\s-*")
  4667. (set (make-local-variable 'parse-sexp-lookup-properties) t)
  4668. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  4669. (set (make-local-variable 'forward-sexp-function)
  4670. 'python-nav-forward-sexp)
  4671. (set (make-local-variable 'font-lock-defaults)
  4672. '(python-font-lock-keywords
  4673. nil nil nil nil
  4674. (font-lock-syntactic-face-function
  4675. . python-font-lock-syntactic-face-function)))
  4676. (set (make-local-variable 'syntax-propertize-function)
  4677. python-syntax-propertize-function)
  4678. (set (make-local-variable 'indent-line-function)
  4679. #'python-indent-line-function)
  4680. (set (make-local-variable 'indent-region-function) #'python-indent-region)
  4681. ;; Because indentation is not redundant, we cannot safely reindent code.
  4682. (set (make-local-variable 'electric-indent-inhibit) t)
  4683. (set (make-local-variable 'electric-indent-chars)
  4684. (cons ?: electric-indent-chars))
  4685. ;; Add """ ... """ pairing to electric-pair-mode.
  4686. (add-hook 'post-self-insert-hook
  4687. #'python-electric-pair-string-delimiter 'append t)
  4688. (set (make-local-variable 'paragraph-start) "\\s-*$")
  4689. (set (make-local-variable 'fill-paragraph-function)
  4690. #'python-fill-paragraph)
  4691. (set (make-local-variable 'beginning-of-defun-function)
  4692. #'python-nav-beginning-of-defun)
  4693. (set (make-local-variable 'end-of-defun-function)
  4694. #'python-nav-end-of-defun)
  4695. (add-hook 'completion-at-point-functions
  4696. #'python-completion-at-point nil 'local)
  4697. (add-hook 'post-self-insert-hook
  4698. #'python-indent-post-self-insert-function 'append 'local)
  4699. (set (make-local-variable 'imenu-create-index-function)
  4700. #'python-imenu-create-index)
  4701. (set (make-local-variable 'add-log-current-defun-function)
  4702. #'python-info-current-defun)
  4703. (add-hook 'which-func-functions #'python-info-current-defun nil t)
  4704. (set (make-local-variable 'skeleton-further-elements)
  4705. '((abbrev-mode nil)
  4706. (< '(backward-delete-char-untabify (min python-indent-offset
  4707. (current-column))))
  4708. (^ '(- (1+ (current-indentation))))))
  4709. (if (null eldoc-documentation-function)
  4710. ;; Emacs<25
  4711. (set (make-local-variable 'eldoc-documentation-function)
  4712. #'python-eldoc-function)
  4713. (add-function :before-until (local 'eldoc-documentation-function)
  4714. #'python-eldoc-function))
  4715. (add-to-list
  4716. 'hs-special-modes-alist
  4717. `(python-mode
  4718. "\\s-*\\_<\\(?:def\\|class\\)\\_>"
  4719. ;; Use the empty string as end regexp so it doesn't default to
  4720. ;; "\\s)". This way parens at end of defun are properly hidden.
  4721. ""
  4722. "#"
  4723. python-hideshow-forward-sexp-function
  4724. nil))
  4725. (set (make-local-variable 'outline-regexp)
  4726. (python-rx (* space) block-start))
  4727. (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
  4728. (set (make-local-variable 'outline-level)
  4729. #'(lambda ()
  4730. "`outline-level' function for Python mode."
  4731. (1+ (/ (current-indentation) python-indent-offset))))
  4732. (set (make-local-variable 'prettify-symbols-alist)
  4733. python--prettify-symbols-alist)
  4734. (python-skeleton-add-menu-items)
  4735. (make-local-variable 'python-shell-internal-buffer)
  4736. (when python-indent-guess-indent-offset
  4737. (python-indent-guess-indent-offset)))
  4738. (provide 'python)
  4739. ;; Local Variables:
  4740. ;; indent-tabs-mode: nil
  4741. ;; End:
  4742. ;;; python.el ends here