org-table.el 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982
  1. ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains the table editor and spreadsheet for Org mode.
  23. ;; Watch out: Here we are talking about two different kind of tables.
  24. ;; Most of the code is for the tables created with the Org mode table editor.
  25. ;; Sometimes, we talk about tables created and edited with the table.el
  26. ;; Emacs package. We call the former org-type tables, and the latter
  27. ;; table.el-type tables.
  28. ;;; Code:
  29. (require 'cl-lib)
  30. (require 'org)
  31. (declare-function org-element-at-point "org-element" ())
  32. (declare-function org-element-contents "org-element" (element))
  33. (declare-function org-element-extract-element "org-element" (element))
  34. (declare-function org-element-interpret-data "org-element" (data))
  35. (declare-function org-element-lineage "org-element"
  36. (blob &optional types with-self))
  37. (declare-function org-element-map "org-element"
  38. (data types fun
  39. &optional info first-match no-recursion with-affiliated))
  40. (declare-function org-element-parse-buffer "org-element"
  41. (&optional granularity visible-only))
  42. (declare-function org-element-property "org-element" (property element))
  43. (declare-function org-element-type "org-element" (element))
  44. (declare-function org-export-create-backend "ox" (&rest rest) t)
  45. (declare-function org-export-data-with-backend "ox" (data backend info))
  46. (declare-function org-export-filter-apply-functions "ox"
  47. (filters value info))
  48. (declare-function org-export-first-sibling-p "ox" (blob info))
  49. (declare-function org-export-get-backend "ox" (name))
  50. (declare-function org-export-get-environment "ox"
  51. (&optional backend subtreep ext-plist))
  52. (declare-function org-export-install-filters "ox" (info))
  53. (declare-function org-export-table-has-special-column-p "ox" (table))
  54. (declare-function org-export-table-row-is-special-p "ox" (table-row info))
  55. (declare-function calc-eval "calc" (str &optional separator &rest args))
  56. (defvar constants-unit-system)
  57. (defvar org-element-use-cache)
  58. (defvar org-export-filters-alist)
  59. (defvar org-table-follow-field-mode)
  60. (defvar orgtbl-mode) ; defined below
  61. (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
  62. (defvar sort-fold-case)
  63. (defvar orgtbl-after-send-table-hook nil
  64. "Hook for functions attaching to `C-c C-c', if the table is sent.
  65. This can be used to add additional functionality after the table is sent
  66. to the receiver position, otherwise, if table is not sent, the functions
  67. are not run.")
  68. (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
  69. (defcustom orgtbl-optimized t
  70. "Non-nil means use the optimized table editor version for `orgtbl-mode'.
  71. In the optimized version, the table editor takes over all simple keys that
  72. normally just insert a character. In tables, the characters are inserted
  73. in a way to minimize disturbing the table structure (i.e. in overwrite mode
  74. for empty fields). Outside tables, the correct binding of the keys is
  75. restored.
  76. Changing this variable requires a restart of Emacs to become
  77. effective."
  78. :group 'org-table
  79. :type 'boolean)
  80. (defcustom orgtbl-radio-table-templates
  81. '((latex-mode "% BEGIN RECEIVE ORGTBL %n
  82. % END RECEIVE ORGTBL %n
  83. \\begin{comment}
  84. #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
  85. | | |
  86. \\end{comment}\n")
  87. (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
  88. @c END RECEIVE ORGTBL %n
  89. @ignore
  90. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  91. | | |
  92. @end ignore\n")
  93. (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
  94. <!-- END RECEIVE ORGTBL %n -->
  95. <!--
  96. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  97. | | |
  98. -->\n")
  99. (org-mode "#+ BEGIN RECEIVE ORGTBL %n
  100. #+ END RECEIVE ORGTBL %n
  101. #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
  102. | | |
  103. "))
  104. "Templates for radio tables in different major modes.
  105. Each template must define lines that will be treated as a comment and that
  106. must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
  107. lines where \"%n\" will be replaced with the name of the table during
  108. insertion of the template. The transformed table will later be inserted
  109. between these lines.
  110. The template should also contain a minimal table in a multiline comment.
  111. If multiline comments are not possible in the buffer language,
  112. you can pack it into a string that will not be used when the code
  113. is compiled or executed. Above the table will you need a line with
  114. the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
  115. convert the table into a data structure useful in the
  116. language of the buffer. Check the manual for the section on
  117. \"Translator functions\", and more generally check out
  118. the Info node `(org)Tables in arbitrary syntax'.
  119. All occurrences of %n in a template will be replaced with the name of the
  120. table, obtained by prompting the user."
  121. :group 'org-table
  122. :type '(repeat
  123. (list (symbol :tag "Major mode")
  124. (string :tag "Format"))))
  125. (defgroup org-table-settings nil
  126. "Settings for tables in Org mode."
  127. :tag "Org Table Settings"
  128. :group 'org-table)
  129. (defcustom org-table-default-size "5x2"
  130. "The default size for newly created tables, Columns x Rows."
  131. :group 'org-table-settings
  132. :type 'string)
  133. (defcustom org-table-number-regexp
  134. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
  135. "Regular expression for recognizing numbers in table columns.
  136. If a table column contains mostly numbers, it will be aligned to the
  137. right. If not, it will be aligned to the left.
  138. The default value of this option is a regular expression which allows
  139. anything which looks remotely like a number as used in scientific
  140. context. For example, all of the following will be considered a
  141. number:
  142. 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
  143. Other options offered by the customize interface are more restrictive."
  144. :group 'org-table-settings
  145. :type '(choice
  146. (const :tag "Positive Integers"
  147. "^[0-9]+$")
  148. (const :tag "Integers"
  149. "^[-+]?[0-9]+$")
  150. (const :tag "Floating Point Numbers"
  151. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
  152. (const :tag "Floating Point Number or Integer"
  153. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
  154. (const :tag "Exponential, Floating point, Integer"
  155. "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
  156. (const :tag "Very General Number-Like, including hex and Calc radix"
  157. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  158. (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
  159. "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  160. (string :tag "Regexp:")))
  161. (defcustom org-table-number-fraction 0.5
  162. "Fraction of numbers in a column required to make the column align right.
  163. In a column all non-white fields are considered. If at least
  164. this fraction of fields is matched by `org-table-number-regexp',
  165. alignment to the right border applies."
  166. :group 'org-table-settings
  167. :type 'number)
  168. (defgroup org-table-editing nil
  169. "Behavior of tables during editing in Org mode."
  170. :tag "Org Table Editing"
  171. :group 'org-table)
  172. (defcustom org-table-automatic-realign t
  173. "Non-nil means automatically re-align table when pressing TAB or RETURN.
  174. When nil, aligning is only done with `\\[org-table-align]', or after column
  175. removal/insertion."
  176. :group 'org-table-editing
  177. :type 'boolean)
  178. (defcustom org-table-auto-blank-field t
  179. "Non-nil means automatically blank table field when starting to type into it.
  180. This only happens when typing immediately after a field motion
  181. command (TAB, S-TAB or RET)."
  182. :group 'org-table-editing
  183. :type 'boolean)
  184. (defcustom org-table-exit-follow-field-mode-when-leaving-table t
  185. "Non-nil means automatically exit the follow mode.
  186. When nil, the follow mode will stay on and be active in any table
  187. the cursor enters. Since the table follow filed mode messes with the
  188. window configuration, it is not recommended to set this variable to nil,
  189. except maybe locally in a special file that has mostly tables with long
  190. fields."
  191. :group 'org-table
  192. :version "24.1"
  193. :type 'boolean)
  194. (defcustom org-table-fix-formulas-confirm nil
  195. "Whether the user should confirm when Org fixes formulas."
  196. :group 'org-table-editing
  197. :version "24.1"
  198. :type '(choice
  199. (const :tag "with yes-or-no" yes-or-no-p)
  200. (const :tag "with y-or-n" y-or-n-p)
  201. (const :tag "no confirmation" nil)))
  202. (defcustom org-table-tab-jumps-over-hlines t
  203. "Non-nil means tab in the last column of a table with jump over a hline.
  204. If a horizontal separator line is following the current line,
  205. `org-table-next-field' can either create a new row before that line, or jump
  206. over the line. When this option is nil, a new line will be created before
  207. this line."
  208. :group 'org-table-editing
  209. :type 'boolean)
  210. (defgroup org-table-calculation nil
  211. "Options concerning tables in Org mode."
  212. :tag "Org Table Calculation"
  213. :group 'org-table)
  214. (defcustom org-table-use-standard-references 'from
  215. "Non-nil means using table references like B3 instead of @3$2.
  216. Possible values are:
  217. nil never use them
  218. from accept as input, do not present for editing
  219. t accept as input and present for editing"
  220. :group 'org-table-calculation
  221. :type '(choice
  222. (const :tag "Never, don't even check user input for them" nil)
  223. (const :tag "Always, both as user input, and when editing" t)
  224. (const :tag "Convert user input, don't offer during editing" from)))
  225. (defcustom org-table-copy-increment t
  226. "Non-nil means increment when copying current field with \
  227. `\\[org-table-copy-down]'."
  228. :group 'org-table-calculation
  229. :version "26.1"
  230. :package-version '(Org . "8.3")
  231. :type '(choice
  232. (const :tag "Use the difference between the current and the above fields" t)
  233. (integer :tag "Use a number" 1)
  234. (const :tag "Don't increment the value when copying a field" nil)))
  235. (defcustom org-calc-default-modes
  236. '(calc-internal-prec 12
  237. calc-float-format (float 8)
  238. calc-angle-mode deg
  239. calc-prefer-frac nil
  240. calc-symbolic-mode nil
  241. calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
  242. calc-display-working-message t
  243. )
  244. "List with Calc mode settings for use in `calc-eval' for table formulas.
  245. The list must contain alternating symbols (Calc modes variables and values).
  246. Don't remove any of the default settings, just change the values. Org mode
  247. relies on the variables to be present in the list."
  248. :group 'org-table-calculation
  249. :type 'plist)
  250. (defcustom org-table-duration-custom-format 'hours
  251. "Format for the output of calc computations like $1+$2;t.
  252. The default value is `hours', and will output the results as a
  253. number of hours. Other allowed values are `seconds', `minutes' and
  254. `days', and the output will be a fraction of seconds, minutes or
  255. days. `hh:mm' selects to use hours and minutes, ignoring seconds.
  256. The `U' flag in a table formula will select this specific format for
  257. a single formula."
  258. :group 'org-table-calculation
  259. :version "24.1"
  260. :type '(choice (symbol :tag "Seconds" 'seconds)
  261. (symbol :tag "Minutes" 'minutes)
  262. (symbol :tag "Hours " 'hours)
  263. (symbol :tag "Days " 'days)
  264. (symbol :tag "HH:MM " 'hh:mm)))
  265. (defcustom org-table-duration-hour-zero-padding t
  266. "Non-nil means hours in table duration computations should be zero-padded.
  267. So this is about 08:32:34 versus 8:33:34."
  268. :group 'org-table-calculation
  269. :version "26.1"
  270. :package-version '(Org . "9.1")
  271. :type 'boolean
  272. :safe #'booleanp)
  273. (defcustom org-table-formula-field-format "%s"
  274. "Format for fields which contain the result of a formula.
  275. For example, using \"~%s~\" will display the result within tilde
  276. characters. Beware that modifying the display can prevent the
  277. field from being used in another formula."
  278. :group 'org-table-settings
  279. :version "24.1"
  280. :type 'string)
  281. (defcustom org-table-formula-evaluate-inline t
  282. "Non-nil means TAB and RET evaluate a formula in current table field.
  283. If the current field starts with an equal sign, it is assumed to be a formula
  284. which should be evaluated as described in the manual and in the documentation
  285. string of the command `org-table-eval-formula'. This feature requires the
  286. Emacs calc package.
  287. When this variable is nil, formula calculation is only available through
  288. the command `\\[org-table-eval-formula]'."
  289. :group 'org-table-calculation
  290. :type 'boolean)
  291. (defcustom org-table-formula-use-constants t
  292. "Non-nil means interpret constants in formulas in tables.
  293. A constant looks like `$c' or `$Grav' and will be replaced before evaluation
  294. by the value given in `org-table-formula-constants', or by a value obtained
  295. from the `constants.el' package."
  296. :group 'org-table-calculation
  297. :type 'boolean)
  298. (defcustom org-table-formula-constants nil
  299. "Alist with constant names and values, for use in table formulas.
  300. The car of each element is a name of a constant, without the `$' before it.
  301. The cdr is the value as a string. For example, if you'd like to use the
  302. speed of light in a formula, you would configure
  303. (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
  304. and then use it in an equation like `$1*$c'.
  305. Constants can also be defined on a per-file basis using a line like
  306. #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
  307. :group 'org-table-calculation
  308. :type '(repeat
  309. (cons (string :tag "name")
  310. (string :tag "value"))))
  311. (defcustom org-table-allow-automatic-line-recalculation t
  312. "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
  313. \\<org-mode-map>\
  314. Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
  315. are pressed in the line."
  316. :group 'org-table-calculation
  317. :type 'boolean)
  318. (defcustom org-table-relative-ref-may-cross-hline t
  319. "Non-nil means relative formula references may cross hlines.
  320. Here are the allowed values:
  321. nil Relative references may not cross hlines. They will reference the
  322. field next to the hline instead. Coming from below, the reference
  323. will be to the field below the hline. Coming from above, it will be
  324. to the field above.
  325. t Relative references may cross hlines.
  326. error An attempt to cross a hline will throw an error.
  327. It is probably good to never set this variable to nil, for the sake of
  328. portability of tables."
  329. :group 'org-table-calculation
  330. :type '(choice
  331. (const :tag "Allow to cross" t)
  332. (const :tag "Stick to hline" nil)
  333. (const :tag "Error on attempt to cross" error)))
  334. (defcustom org-table-formula-create-columns nil
  335. "Non-nil means evaluation of formula can add new columns.
  336. When non-nil, evaluating an out-of-bounds field can insert as
  337. many columns as needed. When set to `warn', issue a warning when
  338. doing so. When set to `prompt', ask user before creating a new
  339. column. Otherwise, throw an error."
  340. :group 'org-table-calculation
  341. :version "26.1"
  342. :package-version '(Org . "8.3")
  343. :type '(choice
  344. (const :tag "Out-of-bounds field generates an error (default)" nil)
  345. (const :tag "Out-of-bounds field silently adds columns as needed" t)
  346. (const :tag "Out-of-bounds field adds columns, but issues a warning" warn)
  347. (const :tag "Prompt user when setting an out-of-bounds field" prompt)))
  348. (defgroup org-table-import-export nil
  349. "Options concerning table import and export in Org mode."
  350. :tag "Org Table Import Export"
  351. :group 'org-table)
  352. (defcustom org-table-export-default-format "orgtbl-to-tsv"
  353. "Default export parameters for `org-table-export'.
  354. These can be overridden for a specific table by setting the
  355. TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
  356. radio tables for the different export transformations and
  357. available parameters."
  358. :group 'org-table-import-export
  359. :type 'string)
  360. (defcustom org-table-convert-region-max-lines 999
  361. "Max lines that `org-table-convert-region' will attempt to process.
  362. The function can be slow on larger regions; this safety feature
  363. prevents it from hanging emacs."
  364. :group 'org-table-import-export
  365. :type 'integer
  366. :version "26.1"
  367. :package-version '(Org . "8.3"))
  368. (defcustom org-table-shrunk-column-indicator "…"
  369. "String to be displayed in a shrunk column."
  370. :group 'org-table-editing
  371. :type 'string
  372. :version "27.1"
  373. :package-version '(Org . "9.2")
  374. :safe (lambda (v) (and (stringp v) (not (equal v "")))))
  375. (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
  376. "Regexp matching a line marked for automatic recalculation.")
  377. (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
  378. "Regexp matching a line marked for recalculation.")
  379. (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
  380. "Regexp matching a line marked for calculation.")
  381. (defconst org-table-border-regexp "^[ \t]*[^| \t]"
  382. "Regexp matching any line outside an Org table.")
  383. (defvar org-table-last-highlighted-reference nil)
  384. (defvar org-table-formula-history nil)
  385. (defvar org-table-column-names nil
  386. "Alist with column names, derived from the `!' line.
  387. This variable is initialized with `org-table-analyze'.")
  388. (defvar org-table-column-name-regexp nil
  389. "Regular expression matching the current column names.
  390. This variable is initialized with `org-table-analyze'.")
  391. (defvar org-table-local-parameters nil
  392. "Alist with parameter names, derived from the `$' line.
  393. This variable is initialized with `org-table-analyze'.")
  394. (defvar org-table-named-field-locations nil
  395. "Alist with locations of named fields.
  396. Associations follow the pattern (NAME LINE COLUMN) where
  397. NAME is the name of the field as a string,
  398. LINE is the number of lines from the beginning of the table,
  399. COLUMN is the column of the field, as an integer.
  400. This variable is initialized with `org-table-analyze'.")
  401. (defvar org-table-current-line-types nil
  402. "Table row types in current table.
  403. This variable is initialized with `org-table-analyze'.")
  404. (defvar org-table-current-begin-pos nil
  405. "Current table begin position, as a marker.
  406. This variable is initialized with `org-table-analyze'.")
  407. (defvar org-table-current-ncol nil
  408. "Number of columns in current table.
  409. This variable is initialized with `org-table-analyze'.")
  410. (defvar org-table-dlines nil
  411. "Vector of data line line numbers in the current table.
  412. Line numbers are counted from the beginning of the table. This
  413. variable is initialized with `org-table-analyze'.")
  414. (defvar org-table-hlines nil
  415. "Vector of hline line numbers in the current table.
  416. Line numbers are counted from the beginning of the table. This
  417. variable is initialized with `org-table-analyze'.")
  418. (defconst org-table-range-regexp
  419. "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
  420. ;; 1 2 3 4 5
  421. "Regular expression for matching ranges in formulas.")
  422. (defconst org-table-range-regexp2
  423. (concat
  424. "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
  425. "\\.\\."
  426. "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
  427. "Match a range for reference display.")
  428. (defconst org-table-translate-regexp
  429. (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
  430. "Match a reference that needs translation, for reference display.")
  431. (defconst org-table-separator-space
  432. (propertize " " 'display '(space :width 1))
  433. "Space used around fields when aligning the table.
  434. This space serves as a segment separator for the purposes of the
  435. bidirectional reordering.")
  436. (defmacro org-table-save-field (&rest body)
  437. "Save current field; execute BODY; restore field.
  438. Field is restored even in case of abnormal exit."
  439. (declare (debug (body)))
  440. (org-with-gensyms (line column)
  441. `(let ((,line (copy-marker (line-beginning-position)))
  442. (,column (org-table-current-column)))
  443. (unwind-protect
  444. (progn ,@body)
  445. (goto-char ,line)
  446. (org-table-goto-column ,column)
  447. (set-marker ,line nil)))))
  448. ;;; See org-macs.el for the definition of org-table-with-shrunk-field,
  449. ;;; including the reason why it is defined there and not here.
  450. (defmacro org-table-with-shrunk-columns (&rest body)
  451. "Expand all columns before executing BODY, then shrink them again."
  452. (declare (debug (body)))
  453. (org-with-gensyms (shrunk-columns begin end)
  454. `(let ((,begin (copy-marker (org-table-begin)))
  455. (,end (copy-marker (org-table-end) t))
  456. (,shrunk-columns (org-table--list-shrunk-columns)))
  457. (org-with-point-at ,begin (org-table-expand ,begin ,end))
  458. (unwind-protect
  459. (progn ,@body)
  460. (org-table--shrink-columns ,shrunk-columns ,begin ,end)
  461. (set-marker ,begin nil)
  462. (set-marker ,end nil)))))
  463. ;;;###autoload
  464. (defun org-table-create-with-table.el ()
  465. "Use the table.el package to insert a new table.
  466. If there is already a table at point, convert between Org tables
  467. and table.el tables."
  468. (interactive)
  469. (require 'table)
  470. (cond
  471. ((and (org-at-table.el-p)
  472. (y-or-n-p "Convert table to Org table? "))
  473. (org-table-convert))
  474. ((and (org-at-table-p)
  475. (y-or-n-p "Convert table to table.el table? "))
  476. (org-table-align)
  477. (org-table-convert))
  478. (t (call-interactively 'table-insert))))
  479. ;;;###autoload
  480. (defun org-table-create-or-convert-from-region (arg)
  481. "Convert region to table, or create an empty table.
  482. If there is an active region, convert it to a table, using the function
  483. `org-table-convert-region'. See the documentation of that function
  484. to learn how the prefix argument is interpreted to determine the field
  485. separator.
  486. If there is no such region, create an empty table with `org-table-create'."
  487. (interactive "P")
  488. (if (org-region-active-p)
  489. (org-table-convert-region (region-beginning) (region-end) arg)
  490. (org-table-create arg)))
  491. ;;;###autoload
  492. (defun org-table-create (&optional size)
  493. "Query for a size and insert a table skeleton.
  494. SIZE is a string Columns x Rows like for example \"3x2\"."
  495. (interactive "P")
  496. (unless size
  497. (setq size (read-string
  498. (concat "Table size Columns x Rows [e.g. "
  499. org-table-default-size "]: ")
  500. "" nil org-table-default-size)))
  501. (let* ((pos (point))
  502. (indent (make-string (current-column) ?\ ))
  503. (split (org-split-string size " *x *"))
  504. (rows (string-to-number (nth 1 split)))
  505. (columns (string-to-number (car split)))
  506. (line (concat (apply 'concat indent "|" (make-list columns " |"))
  507. "\n")))
  508. (if (string-match "^[ \t]*$" (buffer-substring-no-properties
  509. (point-at-bol) (point)))
  510. (beginning-of-line 1)
  511. (newline))
  512. ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
  513. (dotimes (_ rows) (insert line))
  514. (goto-char pos)
  515. (when (> rows 1)
  516. ;; Insert a hline after the first row.
  517. (end-of-line 1)
  518. (insert "\n|-")
  519. (goto-char pos))
  520. (org-table-align)))
  521. ;;;###autoload
  522. (defun org-table-convert-region (beg0 end0 &optional separator)
  523. "Convert region to a table.
  524. The region goes from BEG0 to END0, but these borders will be moved
  525. slightly, to make sure a beginning of line in the first line is included.
  526. SEPARATOR specifies the field separator in the lines. It can have the
  527. following values:
  528. (4) Use the comma as a field separator
  529. (16) Use a TAB as field separator
  530. (64) Prompt for a regular expression as field separator
  531. integer When a number, use that many spaces, or a TAB, as field separator
  532. regexp When a regular expression, use it to match the separator
  533. nil When nil, the command tries to be smart and figure out the
  534. separator in the following way:
  535. - when each line contains a TAB, assume TAB-separated material
  536. - when each line contains a comma, assume CSV material
  537. - else, assume one or more SPACE characters as separator."
  538. (interactive "r\nP")
  539. (let* ((beg (min beg0 end0))
  540. (end (max beg0 end0))
  541. re)
  542. (if (> (count-lines beg end) org-table-convert-region-max-lines)
  543. (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
  544. org-table-convert-region-max-lines)
  545. (when (equal separator '(64))
  546. (setq separator (read-regexp "Regexp for field separator")))
  547. (goto-char beg)
  548. (beginning-of-line 1)
  549. (setq beg (point-marker))
  550. (goto-char end)
  551. (if (bolp) (backward-char 1) (end-of-line 1))
  552. (setq end (point-marker))
  553. ;; Get the right field separator
  554. (unless separator
  555. (goto-char beg)
  556. (setq separator
  557. (cond
  558. ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
  559. ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
  560. (t 1))))
  561. (goto-char beg)
  562. (if (equal separator '(4))
  563. (while (< (point) end)
  564. ;; parse the csv stuff
  565. (cond
  566. ((looking-at "^") (insert "| "))
  567. ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
  568. ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
  569. (replace-match "\\1")
  570. (if (looking-at "\"") (insert "\"")))
  571. ((looking-at "[^,\n]+") (goto-char (match-end 0)))
  572. ((looking-at "[ \t]*,") (replace-match " | "))
  573. (t (beginning-of-line 2))))
  574. (setq re (cond
  575. ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
  576. ((equal separator '(16)) "^\\|\t")
  577. ((integerp separator)
  578. (if (< separator 1)
  579. (user-error "Number of spaces in separator must be >= 1")
  580. (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
  581. ((stringp separator)
  582. (format "^ *\\|%s" separator))
  583. (t (error "This should not happen"))))
  584. (while (re-search-forward re end t)
  585. (replace-match "| " t t)))
  586. (goto-char beg)
  587. (org-table-align))))
  588. ;;;###autoload
  589. (defun org-table-import (file separator)
  590. "Import FILE as a table.
  591. The command tries to be smart and figure out the separator in the
  592. following way:
  593. - when each line contains a TAB, assume TAB-separated material
  594. - when each line contains a comma, assume CSV material
  595. - else, assume one or more SPACE characters as separator.
  596. When non-nil, SEPARATOR specifies the field separator in the
  597. lines. It can have the following values:
  598. (4) Use the comma as a field separator
  599. (16) Use a TAB as field separator
  600. (64) Prompt for a regular expression as field separator
  601. integer When a number, use that many spaces, or a TAB, as field separator
  602. regexp When a regular expression, use it to match the separator."
  603. (interactive "f\nP")
  604. (unless (bolp) (insert "\n"))
  605. (let ((beg (point))
  606. (pm (point-max)))
  607. (insert-file-contents file)
  608. (org-table-convert-region beg (+ (point) (- (point-max) pm)) separator)))
  609. ;;;###autoload
  610. (defun org-table-export (&optional file format)
  611. "Export table to a file, with configurable format.
  612. Such a file can be imported into usual spreadsheet programs.
  613. FILE can be the output file name. If not given, it will be taken
  614. from a TABLE_EXPORT_FILE property in the current entry or higher
  615. up in the hierarchy, or the user will be prompted for a file
  616. name. FORMAT can be an export format, of the same kind as it
  617. used when `orgtbl-mode' sends a table in a different format.
  618. The command suggests a format depending on TABLE_EXPORT_FORMAT,
  619. whether it is set locally or up in the hierarchy, then on the
  620. extension of the given file name, and finally on the variable
  621. `org-table-export-default-format'."
  622. (interactive)
  623. (unless (org-at-table-p) (user-error "No table at point"))
  624. (org-table-align) ; Make sure we have everything we need.
  625. (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
  626. (unless file
  627. (setq file (read-file-name "Export table to: "))
  628. (unless (or (not (file-exists-p file))
  629. (y-or-n-p (format "Overwrite file %s? " file)))
  630. (user-error "File not written")))
  631. (when (file-directory-p file)
  632. (user-error "This is a directory path, not a file"))
  633. (when (and (buffer-file-name (buffer-base-buffer))
  634. (file-equal-p
  635. (file-truename file)
  636. (file-truename (buffer-file-name (buffer-base-buffer)))))
  637. (user-error "Please specify a file name that is different from current"))
  638. (let ((fileext (concat (file-name-extension file) "$"))
  639. (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
  640. (unless format
  641. (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
  642. "orgtbl-to-html" "orgtbl-to-generic"
  643. "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
  644. "orgtbl-to-unicode"))
  645. (deffmt-readable
  646. (replace-regexp-in-string
  647. "\t" "\\t"
  648. (replace-regexp-in-string
  649. "\n" "\\n"
  650. (or (car (delq nil
  651. (mapcar
  652. (lambda (f)
  653. (and (string-match-p fileext f) f))
  654. formats)))
  655. org-table-export-default-format)
  656. t t) t t)))
  657. (setq format
  658. (org-completing-read
  659. "Format: " formats nil nil deffmt-readable))))
  660. (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
  661. (let ((transform (intern (match-string 1 format)))
  662. (params (and (match-end 2)
  663. (read (concat "(" (match-string 2 format) ")"))))
  664. (table (org-table-to-lisp
  665. (buffer-substring-no-properties
  666. (org-table-begin) (org-table-end)))))
  667. (unless (fboundp transform)
  668. (user-error "No such transformation function %s" transform))
  669. (let (buf)
  670. (with-current-buffer (find-file-noselect file)
  671. (setq buf (current-buffer))
  672. (erase-buffer)
  673. (fundamental-mode)
  674. (insert (funcall transform table params) "\n")
  675. (save-buffer))
  676. (kill-buffer buf))
  677. (message "Export done."))
  678. (user-error "TABLE_EXPORT_FORMAT invalid")))))
  679. (defvar org-table-aligned-begin-marker (make-marker)
  680. "Marker at the beginning of the table last aligned.
  681. Used to check if cursor still is in that table, to minimize realignment.")
  682. (defvar org-table-aligned-end-marker (make-marker)
  683. "Marker at the end of the table last aligned.
  684. Used to check if cursor still is in that table, to minimize realignment.")
  685. (defvar org-table-last-alignment nil
  686. "List of flags for flushright alignment, from the last re-alignment.
  687. This is being used to correctly align a single field after TAB or RET.")
  688. (defvar org-table-last-column-widths nil
  689. "List of max width of fields in each column.
  690. This is being used to correctly align a single field after TAB or RET.")
  691. (defvar-local org-table-formula-debug nil
  692. "Non-nil means debug table formulas.
  693. When nil, simply write \"#ERROR\" in corrupted fields.")
  694. (defvar-local org-table-overlay-coordinates nil
  695. "Overlay coordinates after each align of a table.")
  696. (defvar org-last-recalc-line nil)
  697. (defun org-table--align-field (field width align)
  698. "Format FIELD according to column WIDTH and alignement ALIGN.
  699. FIELD is a string. WIDTH is a number. ALIGN is either \"c\",
  700. \"l\" or\"r\"."
  701. (let* ((spaces (- width (org-string-width field)))
  702. (prefix (pcase align
  703. ("l" "")
  704. ("r" (make-string spaces ?\s))
  705. ("c" (make-string (/ spaces 2) ?\s))))
  706. (suffix (make-string (- spaces (length prefix)) ?\s)))
  707. (concat org-table-separator-space
  708. prefix
  709. field
  710. suffix
  711. org-table-separator-space)))
  712. ;;;###autoload
  713. (defun org-table-align ()
  714. "Align the table at point by aligning all vertical bars."
  715. (interactive)
  716. (let ((beg (org-table-begin))
  717. (end (copy-marker (org-table-end))))
  718. (org-table-save-field
  719. ;; Make sure invisible characters in the table are at the right
  720. ;; place since column widths take them into account.
  721. (org-font-lock-ensure beg end)
  722. (move-marker org-table-aligned-begin-marker beg)
  723. (move-marker org-table-aligned-end-marker end)
  724. (goto-char beg)
  725. (org-table-with-shrunk-columns
  726. (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
  727. ;; Table's rows as lists of fields. Rules are replaced
  728. ;; by nil. Trailing spaces are removed.
  729. (fields (mapcar
  730. (lambda (l)
  731. (and (not (string-match-p org-table-hline-regexp l))
  732. (org-split-string l "[ \t]*|[ \t]*")))
  733. (split-string (buffer-substring beg end) "\n" t)))
  734. ;; Compute number of columns. If the table contains no
  735. ;; field, create a default table and bail out.
  736. (columns-number
  737. (if fields (apply #'max (mapcar #'length fields))
  738. (kill-region beg end)
  739. (org-table-create org-table-default-size)
  740. (user-error "Empty table - created default table")))
  741. (widths nil)
  742. (alignments nil))
  743. ;; Compute alignment and width for each column.
  744. (dotimes (i columns-number)
  745. (let* ((max-width 1)
  746. (fixed-align? nil)
  747. (numbers 0)
  748. (non-empty 0))
  749. (dolist (row fields)
  750. (let ((cell (or (nth i row) "")))
  751. (setq max-width (max max-width (org-string-width cell)))
  752. (cond (fixed-align? nil)
  753. ((equal cell "") nil)
  754. ((string-match "\\`<\\([lrc]\\)[0-9]*>\\'" cell)
  755. (setq fixed-align? (match-string 1 cell)))
  756. (t
  757. (cl-incf non-empty)
  758. (when (string-match-p org-table-number-regexp cell)
  759. (cl-incf numbers))))))
  760. (push max-width widths)
  761. (push (cond
  762. (fixed-align?)
  763. ((>= numbers (* org-table-number-fraction non-empty)) "r")
  764. (t "l"))
  765. alignments)))
  766. (setq widths (nreverse widths))
  767. (setq alignments (nreverse alignments))
  768. ;; Store alignment of this table, for later editing of single
  769. ;; fields.
  770. (setq org-table-last-alignment alignments)
  771. (setq org-table-last-column-widths widths)
  772. ;; Build new table rows. Only replace rows that actually
  773. ;; changed.
  774. (dolist (row fields)
  775. (let ((previous (buffer-substring (point) (line-end-position)))
  776. (new
  777. (format "%s|%s|"
  778. indent
  779. (if (null row) ;horizontal rule
  780. (mapconcat (lambda (w) (make-string (+ 2 w) ?-))
  781. widths
  782. "+")
  783. (let ((cells ;add missing fields
  784. (append row
  785. (make-list (- columns-number
  786. (length row))
  787. ""))))
  788. (mapconcat #'identity
  789. (cl-mapcar #'org-table--align-field
  790. cells
  791. widths
  792. alignments)
  793. "|"))))))
  794. (if (equal new previous)
  795. (forward-line)
  796. (insert new "\n")
  797. (delete-region (point) (line-beginning-position 2)))))
  798. (set-marker end nil)
  799. (when org-table-overlay-coordinates (org-table-overlay-coordinates))
  800. (setq org-table-may-need-update nil))))))
  801. ;;;###autoload
  802. (defun org-table-begin (&optional table-type)
  803. "Find the beginning of the table and return its position.
  804. With a non-nil optional argument TABLE-TYPE, return the beginning
  805. of a table.el-type table. This function assumes point is on
  806. a table."
  807. (cond (table-type
  808. (org-element-property :post-affiliated (org-element-at-point)))
  809. ((save-excursion
  810. (and (re-search-backward org-table-border-regexp nil t)
  811. (line-beginning-position 2))))
  812. (t (point-min))))
  813. ;;;###autoload
  814. (defun org-table-end (&optional table-type)
  815. "Find the end of the table and return its position.
  816. With a non-nil optional argument TABLE-TYPE, return the end of
  817. a table.el-type table. This function assumes point is on
  818. a table."
  819. (save-excursion
  820. (cond (table-type
  821. (goto-char (org-element-property :end (org-element-at-point)))
  822. (skip-chars-backward " \t\n")
  823. (line-beginning-position 2))
  824. ((re-search-forward org-table-border-regexp nil t)
  825. (match-beginning 0))
  826. ;; When the line right after the table is the last line in
  827. ;; the buffer with trailing spaces but no final newline
  828. ;; character, be sure to catch the correct ending at its
  829. ;; beginning. In any other case, ending is expected to be
  830. ;; at point max.
  831. (t (goto-char (point-max))
  832. (skip-chars-backward " \t")
  833. (if (bolp) (point) (line-end-position))))))
  834. ;;;###autoload
  835. (defun org-table-justify-field-maybe (&optional new)
  836. "Justify the current field, text to left, number to right.
  837. Optional argument NEW may specify text to replace the current field content."
  838. (cond
  839. ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
  840. ((org-at-table-hline-p))
  841. ((and (not new)
  842. (or (not (eq (marker-buffer org-table-aligned-begin-marker)
  843. (current-buffer)))
  844. (< (point) org-table-aligned-begin-marker)
  845. (>= (point) org-table-aligned-end-marker)))
  846. ;; This is not the same table, force a full re-align.
  847. (setq org-table-may-need-update t))
  848. (t
  849. ;; Realign the current field, based on previous full realign.
  850. (let ((pos (point))
  851. (col (org-table-current-column)))
  852. (when (> col 0)
  853. (skip-chars-backward "^|")
  854. (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
  855. (setq org-table-may-need-update t)
  856. (let* ((align (nth (1- col) org-table-last-alignment))
  857. (width (nth (1- col) org-table-last-column-widths))
  858. (cell (match-string 0))
  859. (field (match-string 1))
  860. (properly-closed? (/= (match-beginning 2) (match-end 2)))
  861. (new-cell
  862. (save-match-data
  863. (cond (org-table-may-need-update
  864. (format " %s |" (or new field)))
  865. ((not properly-closed?)
  866. (setq org-table-may-need-update t)
  867. (format " %s |" (or new field)))
  868. ((not new)
  869. (concat (org-table--align-field field width align)
  870. "|"))
  871. ((<= (org-string-width new) width)
  872. (concat (org-table--align-field new width align)
  873. "|"))
  874. (t
  875. (setq org-table-may-need-update t)
  876. (format " %s |" new))))))
  877. (unless (equal new-cell cell)
  878. (let (org-table-may-need-update)
  879. (replace-match new-cell t t)))
  880. (goto-char pos))))))))
  881. ;;;###autoload
  882. (defun org-table-next-field ()
  883. "Go to the next field in the current table, creating new lines as needed.
  884. Before doing so, re-align the table if necessary."
  885. (interactive)
  886. (org-table-maybe-eval-formula)
  887. (org-table-maybe-recalculate-line)
  888. (when (and org-table-automatic-realign
  889. org-table-may-need-update)
  890. (org-table-align))
  891. (let ((end (org-table-end)))
  892. (if (org-at-table-hline-p)
  893. (end-of-line 1))
  894. (condition-case nil
  895. (progn
  896. (re-search-forward "|" end)
  897. (if (looking-at "[ \t]*$")
  898. (re-search-forward "|" end))
  899. (if (and (looking-at "-")
  900. org-table-tab-jumps-over-hlines
  901. (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
  902. (goto-char (match-beginning 1)))
  903. (if (looking-at "-")
  904. (progn
  905. (beginning-of-line 0)
  906. (org-table-insert-row 'below))
  907. (if (looking-at " ") (forward-char 1))))
  908. (error
  909. (org-table-insert-row 'below)))))
  910. ;;;###autoload
  911. (defun org-table-previous-field ()
  912. "Go to the previous field in the table.
  913. Before doing so, re-align the table if necessary."
  914. (interactive)
  915. (org-table-justify-field-maybe)
  916. (org-table-maybe-recalculate-line)
  917. (when (and org-table-automatic-realign
  918. org-table-may-need-update)
  919. (org-table-align))
  920. (when (org-at-table-hline-p)
  921. (end-of-line))
  922. (let ((start (org-table-begin))
  923. (origin (point)))
  924. (condition-case nil
  925. (progn
  926. (search-backward "|" start nil 2)
  927. (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
  928. (search-backward "|" start)))
  929. (error
  930. (goto-char origin)
  931. (user-error "Cannot move to previous table field"))))
  932. (when (looking-at "| ?")
  933. (goto-char (match-end 0))))
  934. (defun org-table-beginning-of-field (&optional n)
  935. "Move to the beginning of the current table field.
  936. If already at or before the beginning, move to the beginning of the
  937. previous field.
  938. With numeric argument N, move N-1 fields backward first."
  939. (interactive "p")
  940. (let ((pos (point)))
  941. (while (> n 1)
  942. (setq n (1- n))
  943. (org-table-previous-field))
  944. (if (not (re-search-backward "|" (point-at-bol 0) t))
  945. (user-error "No more table fields before the current")
  946. (goto-char (match-end 0))
  947. (and (looking-at " ") (forward-char 1)))
  948. (when (>= (point) pos) (org-table-beginning-of-field 2))))
  949. (defun org-table-end-of-field (&optional n)
  950. "Move to the end of the current table field.
  951. If already at or after the end, move to the end of the next table field.
  952. With numeric argument N, move N-1 fields forward first."
  953. (interactive "p")
  954. (let ((pos (point)))
  955. (while (> n 1)
  956. (setq n (1- n))
  957. (org-table-next-field))
  958. (when (re-search-forward "|" (point-at-eol 1) t)
  959. (backward-char 1)
  960. (skip-chars-backward " ")
  961. (when (and (equal (char-before (point)) ?|) (equal (char-after (point)) ?\s))
  962. (forward-char 1)))
  963. (when (<= (point) pos) (org-table-end-of-field 2))))
  964. ;;;###autoload
  965. (defun org-table-next-row ()
  966. "Go to the next row (same column) in the current table.
  967. Before doing so, re-align the table if necessary."
  968. (interactive)
  969. (org-table-maybe-eval-formula)
  970. (org-table-maybe-recalculate-line)
  971. (if (and org-table-automatic-realign
  972. org-table-may-need-update)
  973. (org-table-align))
  974. (let ((col (org-table-current-column)))
  975. (beginning-of-line 2)
  976. (when (or (not (org-at-table-p))
  977. (org-at-table-hline-p))
  978. (beginning-of-line 0)
  979. (org-table-insert-row 'below))
  980. (org-table-goto-column col)
  981. (skip-chars-backward "^|\n\r")
  982. (when (looking-at " ") (forward-char))))
  983. ;;;###autoload
  984. (defun org-table-copy-down (n)
  985. "Copy the value of the current field one row below.
  986. If the field at the cursor is empty, copy the content of the
  987. nearest non-empty field above. With argument N, use the Nth
  988. non-empty field.
  989. If the current field is not empty, it is copied down to the next
  990. row, and the cursor is moved with it. Therefore, repeating this
  991. command causes the column to be filled row-by-row.
  992. If the variable `org-table-copy-increment' is non-nil and the
  993. field is an integer or a timestamp, it will be incremented while
  994. copying. By default, increment by the difference between the
  995. value in the current field and the one in the field above. To
  996. increment using a fixed integer, set `org-table-copy-increment'
  997. to a number. In the case of a timestamp, increment by days."
  998. (interactive "p")
  999. (let* ((colpos (org-table-current-column))
  1000. (col (current-column))
  1001. (field (save-excursion (org-table-get-field)))
  1002. (field-up (or (save-excursion
  1003. (org-table-get (1- (org-table-current-line))
  1004. (org-table-current-column))) ""))
  1005. (non-empty (string-match "[^ \t]" field))
  1006. (non-empty-up (string-match "[^ \t]" field-up))
  1007. (beg (org-table-begin))
  1008. (orig-n n)
  1009. txt txt-up inc)
  1010. (org-table-check-inside-data-field)
  1011. (if (not non-empty)
  1012. (save-excursion
  1013. (setq txt
  1014. (catch 'exit
  1015. (while (progn (beginning-of-line 1)
  1016. (re-search-backward org-table-dataline-regexp
  1017. beg t))
  1018. (org-table-goto-column colpos t)
  1019. (if (and (looking-at
  1020. "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
  1021. (<= (setq n (1- n)) 0))
  1022. (throw 'exit (match-string 1))))))
  1023. (setq field-up
  1024. (catch 'exit
  1025. (while (progn (beginning-of-line 1)
  1026. (re-search-backward org-table-dataline-regexp
  1027. beg t))
  1028. (org-table-goto-column colpos t)
  1029. (if (and (looking-at
  1030. "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
  1031. (<= (setq n (1- n)) 0))
  1032. (throw 'exit (match-string 1))))))
  1033. (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
  1034. ;; Above field was not empty, go down to the next row. Skip
  1035. ;; alignment since we do it at the end of the process anyway.
  1036. (setq txt (org-trim field))
  1037. (let ((org-table-may-need-update nil)) (org-table-next-row))
  1038. (org-table-blank-field))
  1039. (if non-empty-up (setq txt-up (org-trim field-up)))
  1040. (setq inc (cond
  1041. ((numberp org-table-copy-increment) org-table-copy-increment)
  1042. (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
  1043. (string-match org-ts-regexp3 txt))
  1044. (- (org-time-string-to-absolute txt)
  1045. (org-time-string-to-absolute txt-up)))
  1046. ((string-match org-ts-regexp3 txt) 1)
  1047. ((string-match "\\([-+]\\)?\\(?:[0-9]+\\)?\\(?:\.[0-9]+\\)?" txt-up)
  1048. (- (string-to-number txt)
  1049. (string-to-number (match-string 0 txt-up))))
  1050. (t 1)))
  1051. (t 1)))
  1052. (if (not txt)
  1053. (user-error "No non-empty field found")
  1054. (if (and org-table-copy-increment
  1055. (not (equal orig-n 0))
  1056. (string-match-p "^[-+^/*0-9eE.]+$" txt)
  1057. (< (string-to-number txt) 100000000))
  1058. (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
  1059. (insert txt)
  1060. (org-move-to-column col)
  1061. (if (and org-table-copy-increment (org-at-timestamp-p 'lax))
  1062. (org-timestamp-up-day inc)
  1063. (org-table-maybe-recalculate-line))
  1064. (org-table-align)
  1065. (org-move-to-column col))))
  1066. (defun org-table-check-inside-data-field (&optional noerror assume-table)
  1067. "Non-nil when point is inside a table data field.
  1068. Raise an error otherwise, unless NOERROR is non-nil. In that
  1069. case, return nil if point is not inside a data field. When
  1070. optional argument ASSUME-TABLE is non-nil, assume point is within
  1071. a table."
  1072. (cond ((and (or assume-table (org-at-table-p))
  1073. (not (save-excursion (skip-chars-backward " \t") (bolp)))
  1074. (not (org-at-table-hline-p))
  1075. (not (looking-at-p "[ \t]*$"))))
  1076. (noerror nil)
  1077. (t (user-error "Not in table data field"))))
  1078. (defvar org-table-clip nil
  1079. "Clipboard for table regions.")
  1080. (defun org-table-get (line column)
  1081. "Get the field in table line LINE, column COLUMN.
  1082. If LINE is larger than the number of data lines in the table, the function
  1083. returns nil. However, if COLUMN is too large, we will simply return an
  1084. empty string.
  1085. If LINE is nil, use the current line.
  1086. If COLUMN is nil, use the current column."
  1087. (setq column (or column (org-table-current-column)))
  1088. (save-excursion
  1089. (and (or (not line) (org-table-goto-line line))
  1090. (org-trim (org-table-get-field column)))))
  1091. (defun org-table-put (line column value &optional align)
  1092. "Put VALUE into line LINE, column COLUMN.
  1093. When ALIGN is set, also realign the table."
  1094. (setq column (or column (org-table-current-column)))
  1095. (prog1 (save-excursion
  1096. (and (or (not line) (org-table-goto-line line))
  1097. (progn (org-table-goto-column column nil 'force) t)
  1098. (org-table-get-field column value)))
  1099. (and align (org-table-align))))
  1100. (defun org-table-current-line ()
  1101. "Return the index of the current data line."
  1102. (let ((pos (point)) (end (org-table-end)) (cnt 0))
  1103. (save-excursion
  1104. (goto-char (org-table-begin))
  1105. (while (and (re-search-forward org-table-dataline-regexp end t)
  1106. (setq cnt (1+ cnt))
  1107. (< (point-at-eol) pos))))
  1108. cnt))
  1109. (defun org-table-goto-line (N)
  1110. "Go to the Nth data line in the current table.
  1111. Return t when the line exists, nil if it does not exist."
  1112. (goto-char (org-table-begin))
  1113. (let ((end (org-table-end)) (cnt 0))
  1114. (while (and (re-search-forward org-table-dataline-regexp end t)
  1115. (< (setq cnt (1+ cnt)) N)))
  1116. (= cnt N)))
  1117. ;;;###autoload
  1118. (defun org-table-blank-field ()
  1119. "Blank the current table field or active region."
  1120. (interactive)
  1121. (org-table-check-inside-data-field)
  1122. (if (and (called-interactively-p 'any) (org-region-active-p))
  1123. (let (org-table-clip)
  1124. (org-table-cut-region (region-beginning) (region-end)))
  1125. (skip-chars-backward "^|")
  1126. (backward-char 1)
  1127. (if (looking-at "|[^|\n]+")
  1128. (let* ((pos (match-beginning 0))
  1129. (match (match-string 0))
  1130. (len (org-string-width match)))
  1131. (replace-match (concat "|" (make-string (1- len) ?\ )))
  1132. (goto-char (+ 2 pos))
  1133. (substring match 1)))))
  1134. (defun org-table-get-field (&optional n replace)
  1135. "Return the value of the field in column N of current row.
  1136. N defaults to current column. If REPLACE is a string, replace
  1137. field with this value. The return value is always the old
  1138. value."
  1139. (when n (org-table-goto-column n))
  1140. (skip-chars-backward "^|\n")
  1141. (if (or (bolp) (looking-at-p "[ \t]*$"))
  1142. ;; Before first column or after last one.
  1143. ""
  1144. (looking-at "[^|\r\n]*")
  1145. (let* ((pos (match-beginning 0))
  1146. (val (buffer-substring pos (match-end 0))))
  1147. (when replace
  1148. (org-table-with-shrunk-field
  1149. (replace-match (if (equal replace "") " " replace) t t)))
  1150. (goto-char (min (line-end-position) (1+ pos)))
  1151. val)))
  1152. ;;;###autoload
  1153. (defun org-table-field-info (_arg)
  1154. "Show info about the current field, and highlight any reference at point."
  1155. (interactive "P")
  1156. (unless (org-at-table-p) (user-error "Not at a table"))
  1157. (org-table-analyze)
  1158. (save-excursion
  1159. (let* ((pos (point))
  1160. (col (org-table-current-column))
  1161. (cname (car (rassoc (int-to-string col) org-table-column-names)))
  1162. (name (car (rassoc (list (count-lines org-table-current-begin-pos
  1163. (line-beginning-position))
  1164. col)
  1165. org-table-named-field-locations)))
  1166. (eql (org-table-expand-lhs-ranges
  1167. (mapcar
  1168. (lambda (e)
  1169. (cons (org-table-formula-handle-first/last-rc (car e))
  1170. (cdr e)))
  1171. (org-table-get-stored-formulas))))
  1172. (dline (org-table-current-dline))
  1173. (ref (format "@%d$%d" dline col))
  1174. (ref1 (org-table-convert-refs-to-an ref))
  1175. ;; Prioritize field formulas over column formulas.
  1176. (fequation (or (assoc name eql) (assoc ref eql)))
  1177. (cequation (assoc (format "$%d" col) eql))
  1178. (eqn (or fequation cequation)))
  1179. (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
  1180. (when p (setq eqn p)))
  1181. (goto-char pos)
  1182. (ignore-errors (org-table-show-reference 'local))
  1183. (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
  1184. dline col
  1185. (if cname (concat " or $" cname) "")
  1186. dline col ref1
  1187. (if name (concat " or $" name) "")
  1188. ;; FIXME: formula info not correct if special table line
  1189. (if eqn
  1190. (concat ", formula: "
  1191. (org-table-formula-to-user
  1192. (concat
  1193. (if (or (string-prefix-p "$" (car eqn))
  1194. (string-prefix-p "@" (car eqn)))
  1195. ""
  1196. "$")
  1197. (car eqn) "=" (cdr eqn))))
  1198. "")))))
  1199. (defun org-table-current-column ()
  1200. "Return current column number."
  1201. (interactive)
  1202. (save-excursion
  1203. (let ((pos (point)))
  1204. (beginning-of-line)
  1205. (if (not (search-forward "|" pos t)) 0
  1206. (let ((column 1)
  1207. (separator (if (org-at-table-hline-p) "[+|]" "|")))
  1208. (while (re-search-forward separator pos t) (cl-incf column))
  1209. column)))))
  1210. (defun org-table-current-dline ()
  1211. "Find out what table data line we are in.
  1212. Only data lines count for this."
  1213. (save-excursion
  1214. (let ((c 0)
  1215. (pos (line-beginning-position)))
  1216. (goto-char (org-table-begin))
  1217. (while (<= (point) pos)
  1218. (when (looking-at org-table-dataline-regexp) (cl-incf c))
  1219. (forward-line))
  1220. c)))
  1221. ;;;###autoload
  1222. (defun org-table-goto-column (n &optional on-delim force)
  1223. "Move the cursor to the Nth column in the current table line.
  1224. With optional argument ON-DELIM, stop with point before the left delimiter
  1225. of the field.
  1226. If there are less than N fields, just go to after the last delimiter.
  1227. However, when FORCE is non-nil, create new columns if necessary."
  1228. (interactive "p")
  1229. (beginning-of-line 1)
  1230. (when (> n 0)
  1231. (while (and (> (setq n (1- n)) -1)
  1232. (or (search-forward "|" (point-at-eol) t)
  1233. (and force
  1234. (progn (end-of-line 1)
  1235. (skip-chars-backward "^|")
  1236. (insert " | ")
  1237. t)))))
  1238. (when (and force (not (looking-at ".*|")))
  1239. (save-excursion (end-of-line 1) (insert " | ")))
  1240. (if on-delim
  1241. (backward-char 1)
  1242. (if (looking-at " ") (forward-char 1)))))
  1243. ;;;###autoload
  1244. (defun org-table-insert-column ()
  1245. "Insert a new column into the table."
  1246. (interactive)
  1247. (unless (org-at-table-p) (user-error "Not at a table"))
  1248. (org-table-find-dataline)
  1249. (let ((col (max 1 (org-table-current-column)))
  1250. (beg (org-table-begin))
  1251. (end (copy-marker (org-table-end)))
  1252. (shrunk-columns (org-table--list-shrunk-columns)))
  1253. (org-table-expand beg end)
  1254. (save-excursion
  1255. (goto-char beg)
  1256. (while (< (point) end)
  1257. (unless (org-at-table-hline-p)
  1258. (org-table-goto-column col t)
  1259. (unless (search-forward "|" (line-end-position) t 2)
  1260. ;; Add missing vertical bar at the end of the row.
  1261. (end-of-line)
  1262. (insert "|"))
  1263. (insert " |"))
  1264. (forward-line)))
  1265. (org-table-goto-column (1+ col))
  1266. (org-table-align)
  1267. ;; Shift appropriately stored shrunk column numbers, then hide the
  1268. ;; columns again.
  1269. (org-table--shrink-columns (mapcar (lambda (c) (if (<= c col) c (1+ c)))
  1270. shrunk-columns)
  1271. beg end)
  1272. (set-marker end nil)
  1273. ;; Fix TBLFM formulas, if desirable.
  1274. (when (or (not org-table-fix-formulas-confirm)
  1275. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1276. (org-table-fix-formulas "$" nil (1- col) 1)
  1277. (org-table-fix-formulas "$LR" nil (1- col) 1))))
  1278. (defun org-table-find-dataline ()
  1279. "Find a data line in the current table, which is needed for column commands.
  1280. This function assumes point is in a table. Raise an error when
  1281. there is no data row below."
  1282. (or (not (org-at-table-hline-p))
  1283. (let ((col (current-column))
  1284. (end (org-table-end)))
  1285. (forward-line)
  1286. (while (and (< (point) end) (org-at-table-hline-p))
  1287. (forward-line))
  1288. (when (>= (point) end)
  1289. (user-error "Cannot find data row for column operation"))
  1290. (org-move-to-column col)
  1291. t)))
  1292. (defun org-table-line-to-dline (line &optional above)
  1293. "Turn a buffer line number into a data line number.
  1294. If there is no data line in this line, return nil.
  1295. If there is no matching dline (most likely the reference was
  1296. a hline), the first dline below it is used. When ABOVE is
  1297. non-nil, the one above is used."
  1298. (let ((min 1)
  1299. (max (1- (length org-table-dlines))))
  1300. (cond ((or (> (aref org-table-dlines min) line)
  1301. (< (aref org-table-dlines max) line))
  1302. nil)
  1303. ((= line (aref org-table-dlines max)) max)
  1304. (t (catch 'exit
  1305. (while (> (- max min) 1)
  1306. (let* ((mean (/ (+ max min) 2))
  1307. (v (aref org-table-dlines mean)))
  1308. (cond ((= v line) (throw 'exit mean))
  1309. ((> v line) (setq max mean))
  1310. (t (setq min mean)))))
  1311. (cond ((= line (aref org-table-dlines max)) max)
  1312. ((= line (aref org-table-dlines min)) min)
  1313. (above min)
  1314. (t max)))))))
  1315. (defun org-table--swap-cells (row1 col1 row2 col2)
  1316. "Swap two cells indicated by the coordinates provided.
  1317. ROW1, COL1, ROW2, COL2 are integers indicating the row/column
  1318. position of the two cells that will be swapped in the table."
  1319. (let ((content1 (org-table-get row1 col1))
  1320. (content2 (org-table-get row2 col2)))
  1321. (org-table-put row1 col1 content2)
  1322. (org-table-put row2 col2 content1)))
  1323. (defun org-table--move-cell (direction)
  1324. "Move the current cell in a cardinal direction.
  1325. DIRECTION is a symbol among `up', `down', `left', and `right'.
  1326. The contents the current cell are swapped with cell in the
  1327. indicated direction. Raise an error if the move cannot be done."
  1328. (let ((row-shift (pcase direction (`up -1) (`down 1) (_ 0)))
  1329. (column-shift (pcase direction (`left -1) (`right 1) (_ 0))))
  1330. (when (and (= 0 row-shift) (= 0 column-shift))
  1331. (error "Invalid direction: %S" direction))
  1332. ;; Initialize `org-table-current-ncol' and `org-table-dlines'.
  1333. (org-table-analyze)
  1334. (let* ((row (org-table-current-line))
  1335. (column (org-table-current-column))
  1336. (target-row (+ row row-shift))
  1337. (target-column (+ column column-shift))
  1338. (org-table-current-nrow (1- (length org-table-dlines))))
  1339. (when (or (< target-column 1)
  1340. (< target-row 1)
  1341. (> target-column org-table-current-ncol)
  1342. (> target-row org-table-current-nrow))
  1343. (user-error "Cannot move cell further"))
  1344. (org-table--swap-cells row column target-row target-column)
  1345. (org-table-goto-line target-row)
  1346. (org-table-goto-column target-column))))
  1347. ;;;###autoload
  1348. (defun org-table-move-cell-up ()
  1349. "Move a single cell up in a table.
  1350. Swap with anything in target cell."
  1351. (interactive)
  1352. (unless (org-table-check-inside-data-field)
  1353. (error "No table at point"))
  1354. (org-table--move-cell 'up)
  1355. (org-table-align))
  1356. ;;;###autoload
  1357. (defun org-table-move-cell-down ()
  1358. "Move a single cell down in a table.
  1359. Swap with anything in target cell."
  1360. (interactive)
  1361. (unless (org-table-check-inside-data-field)
  1362. (error "No table at point"))
  1363. (org-table--move-cell 'down)
  1364. (org-table-align))
  1365. ;;;###autoload
  1366. (defun org-table-move-cell-left ()
  1367. "Move a single cell left in a table.
  1368. Swap with anything in target cell."
  1369. (interactive)
  1370. (unless (org-table-check-inside-data-field)
  1371. (error "No table at point"))
  1372. (org-table--move-cell 'left)
  1373. (org-table-align))
  1374. ;;;###autoload
  1375. (defun org-table-move-cell-right ()
  1376. "Move a single cell right in a table.
  1377. Swap with anything in target cell."
  1378. (interactive)
  1379. (unless (org-table-check-inside-data-field)
  1380. (error "No table at point"))
  1381. (org-table--move-cell 'right)
  1382. (org-table-align))
  1383. ;;;###autoload
  1384. (defun org-table-delete-column ()
  1385. "Delete a column from the table."
  1386. (interactive)
  1387. (unless (org-at-table-p) (user-error "Not at a table"))
  1388. (org-table-find-dataline)
  1389. (org-table-check-inside-data-field nil t)
  1390. (let* ((col (org-table-current-column))
  1391. (beg (org-table-begin))
  1392. (end (copy-marker (org-table-end)))
  1393. (shrunk-columns (remq col (org-table--list-shrunk-columns))))
  1394. (org-table-expand beg end)
  1395. (org-table-save-field
  1396. (goto-char beg)
  1397. (while (< (point) end)
  1398. (if (org-at-table-hline-p)
  1399. nil
  1400. (org-table-goto-column col t)
  1401. (and (looking-at "|[^|\n]+|")
  1402. (replace-match "|")))
  1403. (forward-line)))
  1404. (org-table-goto-column (max 1 (1- col)))
  1405. (org-table-align)
  1406. ;; Shift appropriately stored shrunk column numbers, then hide the
  1407. ;; columns again.
  1408. (org-table--shrink-columns (mapcar (lambda (c) (if (< c col) c (1- c)))
  1409. shrunk-columns)
  1410. beg end)
  1411. (set-marker end nil)
  1412. ;; Fix TBLFM formulas, if desirable.
  1413. (when (or (not org-table-fix-formulas-confirm)
  1414. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1415. (org-table-fix-formulas
  1416. "$" (list (cons (number-to-string col) "INVALID")) col -1 col)
  1417. (org-table-fix-formulas
  1418. "$LR" (list (cons (number-to-string col) "INVALID")) col -1 col))))
  1419. ;;;###autoload
  1420. (defun org-table-move-column-right ()
  1421. "Move column to the right."
  1422. (interactive)
  1423. (org-table-move-column nil))
  1424. ;;;###autoload
  1425. (defun org-table-move-column-left ()
  1426. "Move column to the left."
  1427. (interactive)
  1428. (org-table-move-column 'left))
  1429. ;;;###autoload
  1430. (defun org-table-move-column (&optional left)
  1431. "Move the current column to the right. With arg LEFT, move to the left."
  1432. (interactive "P")
  1433. (unless (org-at-table-p) (user-error "Not at a table"))
  1434. (org-table-find-dataline)
  1435. (org-table-check-inside-data-field nil t)
  1436. (let* ((col (org-table-current-column))
  1437. (col1 (if left (1- col) col))
  1438. (colpos (if left (1- col) (1+ col)))
  1439. (beg (org-table-begin))
  1440. (end (copy-marker (org-table-end))))
  1441. (when (and left (= col 1))
  1442. (user-error "Cannot move column further left"))
  1443. (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
  1444. (user-error "Cannot move column further right"))
  1445. (let ((shrunk-columns (org-table--list-shrunk-columns)))
  1446. (org-table-expand beg end)
  1447. (org-table-save-field
  1448. (goto-char beg)
  1449. (while (< (point) end)
  1450. (unless (org-at-table-hline-p)
  1451. (org-table-goto-column col1 t)
  1452. (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
  1453. (transpose-regions
  1454. (match-beginning 1) (match-end 1)
  1455. (match-beginning 2) (match-end 2))))
  1456. (forward-line)))
  1457. (org-table-goto-column colpos)
  1458. (org-table-align)
  1459. ;; Shift appropriately stored shrunk column numbers, then shrink
  1460. ;; the columns again.
  1461. (org-table--shrink-columns
  1462. (mapcar (lambda (c)
  1463. (cond ((and (= col c) left) (1- c))
  1464. ((= col c) (1+ c))
  1465. ((and (= col (1+ c)) left) (1+ c))
  1466. ((and (= col (1- c)) (not left) (1- c)))
  1467. (t c)))
  1468. shrunk-columns)
  1469. beg end)
  1470. (set-marker end nil)
  1471. ;; Fix TBLFM formulas, if desirable.
  1472. (when (or (not org-table-fix-formulas-confirm)
  1473. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1474. (org-table-fix-formulas
  1475. "$" (list (cons (number-to-string col) (number-to-string colpos))
  1476. (cons (number-to-string colpos) (number-to-string col))))
  1477. (org-table-fix-formulas
  1478. "$LR" (list
  1479. (cons (number-to-string col) (number-to-string colpos))
  1480. (cons (number-to-string colpos) (number-to-string col))))))))
  1481. ;;;###autoload
  1482. (defun org-table-move-row-down ()
  1483. "Move table row down."
  1484. (interactive)
  1485. (org-table-move-row nil))
  1486. ;;;###autoload
  1487. (defun org-table-move-row-up ()
  1488. "Move table row up."
  1489. (interactive)
  1490. (org-table-move-row 'up))
  1491. ;;;###autoload
  1492. (defun org-table-move-row (&optional up)
  1493. "Move the current table line down. With arg UP, move it up."
  1494. (interactive "P")
  1495. (let* ((col (current-column))
  1496. (pos (point))
  1497. (hline1p (save-excursion (beginning-of-line 1)
  1498. (looking-at org-table-hline-regexp)))
  1499. (dline1 (org-table-current-dline))
  1500. (dline2 (+ dline1 (if up -1 1)))
  1501. (tonew (if up 0 2))
  1502. hline2p)
  1503. (when (and up (= (point-min) (line-beginning-position)))
  1504. (user-error "Cannot move row further"))
  1505. (beginning-of-line tonew)
  1506. (when (or (and (not up) (eobp)) (not (org-at-table-p)))
  1507. (goto-char pos)
  1508. (user-error "Cannot move row further"))
  1509. (org-table-with-shrunk-columns
  1510. (setq hline2p (looking-at org-table-hline-regexp))
  1511. (goto-char pos)
  1512. (let ((row (delete-and-extract-region (line-beginning-position)
  1513. (line-beginning-position 2))))
  1514. (beginning-of-line tonew)
  1515. (unless (bolp) (insert "\n")) ;at eob without a newline
  1516. (insert row)
  1517. (unless (bolp) (insert "\n")) ;missing final newline in ROW
  1518. (beginning-of-line 0)
  1519. (org-move-to-column col)
  1520. (unless (or hline1p hline2p
  1521. (not (or (not org-table-fix-formulas-confirm)
  1522. (funcall org-table-fix-formulas-confirm
  1523. "Fix formulas? "))))
  1524. (org-table-fix-formulas
  1525. "@" (list
  1526. (cons (number-to-string dline1) (number-to-string dline2))
  1527. (cons (number-to-string dline2) (number-to-string dline1)))))))))
  1528. ;;;###autoload
  1529. (defun org-table-insert-row (&optional arg)
  1530. "Insert a new row above the current line into the table.
  1531. With prefix ARG, insert below the current line."
  1532. (interactive "P")
  1533. (unless (org-at-table-p) (user-error "Not at a table"))
  1534. (org-table-with-shrunk-columns
  1535. (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
  1536. (new (org-table-clean-line line)))
  1537. ;; Fix the first field if necessary
  1538. (when (string-match "^[ \t]*| *[#*$] *|" line)
  1539. (setq new (replace-match (match-string 0 line) t t new)))
  1540. (beginning-of-line (if arg 2 1))
  1541. ;; Buffer may not end of a newline character, so ensure
  1542. ;; (beginning-of-line 2) moves point to a new line.
  1543. (unless (bolp) (insert "\n"))
  1544. (let (org-table-may-need-update) (insert-before-markers new "\n"))
  1545. (beginning-of-line 0)
  1546. (re-search-forward "| ?" (line-end-position) t)
  1547. (when (or org-table-may-need-update org-table-overlay-coordinates)
  1548. (org-table-align))
  1549. (when (or (not org-table-fix-formulas-confirm)
  1550. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1551. (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))))
  1552. ;;;###autoload
  1553. (defun org-table-insert-hline (&optional above)
  1554. "Insert a horizontal-line below the current line into the table.
  1555. With prefix ABOVE, insert above the current line."
  1556. (interactive "P")
  1557. (unless (org-at-table-p) (user-error "Not at a table"))
  1558. (when (eobp) (save-excursion (insert "\n")))
  1559. (unless (string-match-p "|[ \t]*$" (org-current-line-string))
  1560. (org-table-align))
  1561. (org-table-with-shrunk-columns
  1562. (let ((line (org-table-clean-line
  1563. (buffer-substring (point-at-bol) (point-at-eol))))
  1564. (col (current-column)))
  1565. (while (string-match "|\\( +\\)|" line)
  1566. (setq line (replace-match
  1567. (concat "+" (make-string (- (match-end 1) (match-beginning 1))
  1568. ?-) "|") t t line)))
  1569. (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
  1570. (beginning-of-line (if above 1 2))
  1571. (insert line "\n")
  1572. (beginning-of-line (if above 1 -1))
  1573. (org-move-to-column col)
  1574. (when org-table-overlay-coordinates (org-table-align)))))
  1575. ;;;###autoload
  1576. (defun org-table-hline-and-move (&optional same-column)
  1577. "Insert a hline and move to the row below that line."
  1578. (interactive "P")
  1579. (let ((col (org-table-current-column)))
  1580. (org-table-maybe-eval-formula)
  1581. (org-table-maybe-recalculate-line)
  1582. (org-table-insert-hline)
  1583. (end-of-line 2)
  1584. (if (looking-at "\n[ \t]*|-")
  1585. (progn (insert "\n|") (org-table-align))
  1586. (org-table-next-field))
  1587. (if same-column (org-table-goto-column col))))
  1588. (defun org-table-clean-line (s)
  1589. "Convert a table line S into a string with only \"|\" and space.
  1590. In particular, this does handle wide and invisible characters."
  1591. (if (string-match "^[ \t]*|-" s)
  1592. ;; It's a hline, just map the characters
  1593. (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
  1594. (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
  1595. (setq s (replace-match
  1596. (concat "|" (make-string (org-string-width (match-string 1 s))
  1597. ?\ ) "|")
  1598. t t s)))
  1599. s))
  1600. ;;;###autoload
  1601. (defun org-table-kill-row ()
  1602. "Delete the current row or horizontal line from the table."
  1603. (interactive)
  1604. (unless (org-at-table-p) (user-error "Not at a table"))
  1605. (let ((col (current-column))
  1606. (dline (and (not (org-match-line org-table-hline-regexp))
  1607. (org-table-current-dline))))
  1608. (org-table-with-shrunk-columns
  1609. (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
  1610. (if (not (org-at-table-p)) (beginning-of-line 0))
  1611. (org-move-to-column col)
  1612. (when (and dline
  1613. (or (not org-table-fix-formulas-confirm)
  1614. (funcall org-table-fix-formulas-confirm "Fix formulas? ")))
  1615. (org-table-fix-formulas
  1616. "@" (list (cons (number-to-string dline) "INVALID")) dline -1 dline)))))
  1617. ;;;###autoload
  1618. (defun org-table-sort-lines
  1619. (&optional with-case sorting-type getkey-func compare-func interactive?)
  1620. "Sort table lines according to the column at point.
  1621. The position of point indicates the column to be used for
  1622. sorting, and the range of lines is the range between the nearest
  1623. horizontal separator lines, or the entire table of no such lines
  1624. exist. If point is before the first column, you will be prompted
  1625. for the sorting column. If there is an active region, the mark
  1626. specifies the first line and the sorting column, while point
  1627. should be in the last line to be included into the sorting.
  1628. The command then prompts for the sorting type which can be
  1629. alphabetically, numerically, or by time (as given in a time stamp
  1630. in the field, or as a HH:MM value). Sorting in reverse order is
  1631. also possible.
  1632. With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive
  1633. if the locale allows for it.
  1634. If SORTING-TYPE is specified when this function is called from a Lisp
  1635. program, no prompting will take place. SORTING-TYPE must be a character,
  1636. any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
  1637. sorting should be done in reverse order.
  1638. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
  1639. a function to be called to extract the key. It must return a value
  1640. that is compatible with COMPARE-FUNC, the function used to compare
  1641. entries.
  1642. A non-nil value for INTERACTIVE? is used to signal that this
  1643. function is being called interactively."
  1644. (interactive (list current-prefix-arg nil nil nil t))
  1645. (when (org-region-active-p) (goto-char (region-beginning)))
  1646. ;; Point must be either within a field or before a data line.
  1647. (save-excursion
  1648. (skip-chars-backward " \t")
  1649. (when (bolp) (search-forward "|" (line-end-position) t))
  1650. (org-table-check-inside-data-field))
  1651. ;; Set appropriate case sensitivity and column used for sorting.
  1652. (let ((column (let ((c (org-table-current-column)))
  1653. (cond ((> c 0) c)
  1654. (interactive?
  1655. (read-number "Use column N for sorting: "))
  1656. (t 1))))
  1657. (sorting-type
  1658. (or sorting-type
  1659. (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
  1660. \[t]ime, [f]unc. A/N/T/F means reversed: ")))
  1661. (start (org-table-begin))
  1662. (end (org-table-end)))
  1663. (save-restriction
  1664. ;; Narrow buffer to appropriate sorting area.
  1665. (if (org-region-active-p)
  1666. (progn (goto-char (region-beginning))
  1667. (narrow-to-region
  1668. (point)
  1669. (save-excursion (goto-char (region-end))
  1670. (line-beginning-position 2))))
  1671. (narrow-to-region
  1672. (save-excursion
  1673. (if (re-search-backward org-table-hline-regexp start t)
  1674. (line-beginning-position 2)
  1675. start))
  1676. (if (save-excursion (re-search-forward org-table-hline-regexp end t))
  1677. (match-beginning 0)
  1678. end)))
  1679. ;; Determine arguments for `sort-subr'. Also record original
  1680. ;; position. `org-table-save-field' cannot help here since
  1681. ;; sorting is too much destructive.
  1682. (let* ((coordinates
  1683. (cons (count-lines (point-min) (line-beginning-position))
  1684. (current-column)))
  1685. (extract-key-from-field
  1686. ;; Function to be called on the contents of the field
  1687. ;; used for sorting in the current row.
  1688. (cl-case sorting-type
  1689. ((?n ?N) #'string-to-number)
  1690. ((?a ?A) #'org-sort-remove-invisible)
  1691. ((?t ?T)
  1692. (lambda (f)
  1693. (cond ((string-match org-ts-regexp-both f)
  1694. (float-time
  1695. (org-time-string-to-time (match-string 0 f))))
  1696. ((org-duration-p f) (org-duration-to-minutes f))
  1697. ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f)
  1698. (org-duration-to-minutes (match-string 0 f)))
  1699. (t 0))))
  1700. ((?f ?F)
  1701. (or getkey-func
  1702. (and interactive?
  1703. (org-read-function "Function for extracting keys: "))
  1704. (error "Missing key extractor to sort rows")))
  1705. (t (user-error "Invalid sorting type `%c'" sorting-type))))
  1706. (predicate
  1707. (cl-case sorting-type
  1708. ((?n ?N ?t ?T) #'<)
  1709. ((?a ?A) (if with-case #'org-string-collate-lessp
  1710. (lambda (s1 s2) (org-string-collate-lessp s1 s2 nil t))))
  1711. ((?f ?F)
  1712. (or compare-func
  1713. (and interactive?
  1714. (org-read-function
  1715. "Function for comparing keys (empty for default \
  1716. `sort-subr' predicate): "
  1717. 'allow-empty))))))
  1718. (shrunk-columns (remq column (org-table--list-shrunk-columns))))
  1719. (goto-char (point-min))
  1720. (sort-subr (memq sorting-type '(?A ?N ?T ?F))
  1721. (lambda ()
  1722. (forward-line)
  1723. (while (and (not (eobp))
  1724. (not (looking-at org-table-dataline-regexp)))
  1725. (forward-line)))
  1726. #'end-of-line
  1727. (lambda ()
  1728. (funcall extract-key-from-field
  1729. (org-trim (org-table-get-field column))))
  1730. nil
  1731. predicate)
  1732. ;; Hide all columns but the one being sorted.
  1733. (org-table--shrink-columns shrunk-columns start end)
  1734. ;; Move back to initial field.
  1735. (forward-line (car coordinates))
  1736. (move-to-column (cdr coordinates))))))
  1737. ;;;###autoload
  1738. (defun org-table-cut-region (beg end)
  1739. "Copy region in table to the clipboard and blank all relevant fields.
  1740. If there is no active region, use just the field at point."
  1741. (interactive (list
  1742. (if (org-region-active-p) (region-beginning) (point))
  1743. (if (org-region-active-p) (region-end) (point))))
  1744. (org-table-copy-region beg end 'cut))
  1745. ;;;###autoload
  1746. (defun org-table-copy-region (beg end &optional cut)
  1747. "Copy rectangular region in table to clipboard.
  1748. A special clipboard is used which can only be accessed with
  1749. `org-table-paste-rectangle'. Return the region copied, as a list
  1750. of lists of fields."
  1751. (interactive (list
  1752. (if (org-region-active-p) (region-beginning) (point))
  1753. (if (org-region-active-p) (region-end) (point))
  1754. current-prefix-arg))
  1755. (goto-char (min beg end))
  1756. (org-table-check-inside-data-field)
  1757. (let ((beg (line-beginning-position))
  1758. (c01 (org-table-current-column))
  1759. region)
  1760. (goto-char (max beg end))
  1761. (org-table-check-inside-data-field nil t)
  1762. (let* ((end (copy-marker (line-end-position)))
  1763. (c02 (org-table-current-column))
  1764. (column-start (min c01 c02))
  1765. (column-end (max c01 c02))
  1766. (column-number (1+ (- column-end column-start)))
  1767. (rpl (and cut " ")))
  1768. (goto-char beg)
  1769. (while (< (point) end)
  1770. (unless (org-at-table-hline-p)
  1771. ;; Collect every cell between COLUMN-START and COLUMN-END.
  1772. (let (cols)
  1773. (dotimes (c column-number)
  1774. (push (org-table-get-field (+ c column-start) rpl) cols))
  1775. (push (nreverse cols) region)))
  1776. (forward-line))
  1777. (set-marker end nil))
  1778. (when cut (org-table-align))
  1779. (message (substitute-command-keys "Cells in the region copied, use \
  1780. \\[org-table-paste-rectangle] to paste them in a table."))
  1781. (setq org-table-clip (nreverse region))))
  1782. ;;;###autoload
  1783. (defun org-table-paste-rectangle ()
  1784. "Paste a rectangular region into a table.
  1785. The upper right corner ends up in the current field. All involved fields
  1786. will be overwritten. If the rectangle does not fit into the present table,
  1787. the table is enlarged as needed. The process ignores horizontal separator
  1788. lines."
  1789. (interactive)
  1790. (unless (consp org-table-clip)
  1791. (user-error "First cut/copy a region to paste!"))
  1792. (org-table-check-inside-data-field)
  1793. (let* ((column (org-table-current-column))
  1794. (org-table-automatic-realign nil))
  1795. (org-table-save-field
  1796. (dolist (row org-table-clip)
  1797. (while (org-at-table-hline-p) (forward-line))
  1798. ;; If we left the table, create a new row.
  1799. (when (and (bolp) (not (looking-at "[ \t]*|")))
  1800. (end-of-line 0)
  1801. (org-table-next-field))
  1802. (let ((c column))
  1803. (dolist (field row)
  1804. (org-table-goto-column c nil 'force)
  1805. (org-table-get-field nil field)
  1806. (cl-incf c)))
  1807. (forward-line)))
  1808. (org-table-align)))
  1809. ;;;###autoload
  1810. (defun org-table-convert ()
  1811. "Convert from `org-mode' table to table.el and back.
  1812. Obviously, this only works within limits. When an Org table is converted
  1813. to table.el, all horizontal separator lines get lost, because table.el uses
  1814. these as cell boundaries and has no notion of horizontal lines. A table.el
  1815. table can be converted to an Org table only if it does not do row or column
  1816. spanning. Multiline cells will become multiple cells. Beware, Org mode
  1817. does not test if the table can be successfully converted - it blindly
  1818. applies a recipe that works for simple tables."
  1819. (interactive)
  1820. (require 'table)
  1821. (if (org-at-table.el-p)
  1822. ;; convert to Org table
  1823. (let ((beg (copy-marker (org-table-begin t)))
  1824. (end (copy-marker (org-table-end t))))
  1825. (table-unrecognize-region beg end)
  1826. (goto-char beg)
  1827. (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
  1828. (replace-match ""))
  1829. (goto-char beg))
  1830. (if (org-at-table-p)
  1831. ;; convert to table.el table
  1832. (let ((beg (copy-marker (org-table-begin)))
  1833. (end (copy-marker (org-table-end))))
  1834. ;; first, get rid of all horizontal lines
  1835. (goto-char beg)
  1836. (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
  1837. (replace-match ""))
  1838. ;; insert a hline before first
  1839. (goto-char beg)
  1840. (org-table-insert-hline 'above)
  1841. (beginning-of-line -1)
  1842. ;; insert a hline after each line
  1843. (while (progn (beginning-of-line 3) (< (point) end))
  1844. (org-table-insert-hline))
  1845. (goto-char beg)
  1846. (setq end (move-marker end (org-table-end)))
  1847. ;; replace "+" at beginning and ending of hlines
  1848. (while (re-search-forward "^\\([ \t]*\\)|-" end t)
  1849. (replace-match "\\1+-"))
  1850. (goto-char beg)
  1851. (while (re-search-forward "-|[ \t]*$" end t)
  1852. (replace-match "-+"))
  1853. (goto-char beg)))))
  1854. (defun org-table-transpose-table-at-point ()
  1855. "Transpose Org table at point and eliminate hlines.
  1856. So a table like
  1857. | 1 | 2 | 4 | 5 |
  1858. |---+---+---+---|
  1859. | a | b | c | d |
  1860. | e | f | g | h |
  1861. will be transposed as
  1862. | 1 | a | e |
  1863. | 2 | b | f |
  1864. | 4 | c | g |
  1865. | 5 | d | h |
  1866. Note that horizontal lines disappear."
  1867. (interactive)
  1868. (let* ((table (delete 'hline (org-table-to-lisp)))
  1869. (dline_old (org-table-current-line))
  1870. (col_old (org-table-current-column))
  1871. (contents (mapcar (lambda (_)
  1872. (let ((tp table))
  1873. (mapcar
  1874. (lambda (_)
  1875. (prog1
  1876. (pop (car tp))
  1877. (setq tp (cdr tp))))
  1878. table)))
  1879. (car table))))
  1880. (goto-char (org-table-begin))
  1881. (re-search-forward "|")
  1882. (backward-char)
  1883. (delete-region (point) (org-table-end))
  1884. (insert (mapconcat
  1885. (lambda(x)
  1886. (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
  1887. contents ""))
  1888. (org-table-goto-line col_old)
  1889. (org-table-goto-column dline_old))
  1890. (org-table-align))
  1891. ;;;###autoload
  1892. (defun org-table-wrap-region (arg)
  1893. "Wrap several fields in a column like a paragraph.
  1894. This is useful if you'd like to spread the contents of a field over several
  1895. lines, in order to keep the table compact.
  1896. If there is an active region, and both point and mark are in the same column,
  1897. the text in the column is wrapped to minimum width for the given number of
  1898. lines. Generally, this makes the table more compact. A prefix ARG may be
  1899. used to change the number of desired lines. For example, \
  1900. `C-2 \\[org-table-wrap-region]'
  1901. formats the selected text to two lines. If the region was longer than two
  1902. lines, the remaining lines remain empty. A negative prefix argument reduces
  1903. the current number of lines by that amount. The wrapped text is pasted back
  1904. into the table. If you formatted it to more lines than it was before, fields
  1905. further down in the table get overwritten - so you might need to make space in
  1906. the table first.
  1907. If there is no region, the current field is split at the cursor position and
  1908. the text fragment to the right of the cursor is prepended to the field one
  1909. line down.
  1910. If there is no region, but you specify a prefix ARG, the current field gets
  1911. blank, and the content is appended to the field above."
  1912. (interactive "P")
  1913. (org-table-check-inside-data-field)
  1914. (if (org-region-active-p)
  1915. ;; There is a region: fill as a paragraph.
  1916. (let ((start (region-beginning)))
  1917. (org-table-cut-region (region-beginning) (region-end))
  1918. (when (> (length (car org-table-clip)) 1)
  1919. (user-error "Region must be limited to single column"))
  1920. (let ((nlines (cond ((not arg) (length org-table-clip))
  1921. ((< arg 1) (+ (length org-table-clip) arg))
  1922. (t arg))))
  1923. (setq org-table-clip
  1924. (mapcar #'list
  1925. (org-wrap (mapconcat #'car org-table-clip " ")
  1926. nil
  1927. nlines))))
  1928. (goto-char start)
  1929. (org-table-paste-rectangle))
  1930. ;; No region, split the current field at point.
  1931. (unless (org-get-alist-option org-M-RET-may-split-line 'table)
  1932. (skip-chars-forward "^\r\n|"))
  1933. (cond
  1934. (arg ; Combine with field above.
  1935. (let ((s (org-table-blank-field))
  1936. (col (org-table-current-column)))
  1937. (forward-line -1)
  1938. (while (org-at-table-hline-p) (forward-line -1))
  1939. (org-table-goto-column col)
  1940. (skip-chars-forward "^|")
  1941. (skip-chars-backward " ")
  1942. (insert " " (org-trim s))
  1943. (org-table-align)))
  1944. ((looking-at "\\([^|]+\\)+|") ; Split field.
  1945. (let ((s (match-string 1)))
  1946. (replace-match " |")
  1947. (goto-char (match-beginning 0))
  1948. (org-table-next-row)
  1949. (insert (org-trim s) " ")
  1950. (org-table-align)))
  1951. (t (org-table-next-row)))))
  1952. (defvar org-field-marker nil)
  1953. ;;;###autoload
  1954. (defun org-table-edit-field (arg)
  1955. "Edit table field in a different window.
  1956. This is mainly useful for fields that contain hidden parts.
  1957. When called with a `\\[universal-argument]' prefix, just make the full field
  1958. visible so that it can be edited in place.
  1959. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  1960. toggle `org-table-follow-field-mode'."
  1961. (interactive "P")
  1962. (unless (org-at-table-p) (user-error "Not at a table"))
  1963. (cond
  1964. ((equal arg '(16))
  1965. (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
  1966. (arg
  1967. (let ((b (save-excursion (skip-chars-backward "^|") (point)))
  1968. (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
  1969. (remove-text-properties b e '(invisible t intangible t))
  1970. (if (and (boundp 'font-lock-mode) font-lock-mode)
  1971. (font-lock-fontify-block))))
  1972. (t
  1973. (let ((pos (point-marker))
  1974. (coord
  1975. (if (eq org-table-use-standard-references t)
  1976. (concat (org-number-to-letters (org-table-current-column))
  1977. (int-to-string (org-table-current-dline)))
  1978. (concat "@" (int-to-string (org-table-current-dline))
  1979. "$" (int-to-string (org-table-current-column)))))
  1980. (field (org-table-get-field))
  1981. (cw (current-window-configuration))
  1982. p)
  1983. (goto-char pos)
  1984. (org-switch-to-buffer-other-window "*Org Table Edit Field*")
  1985. (when (and (local-variable-p 'org-field-marker)
  1986. (markerp org-field-marker))
  1987. (move-marker org-field-marker nil))
  1988. (erase-buffer)
  1989. (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
  1990. (let ((org-inhibit-startup t)) (org-mode))
  1991. (auto-fill-mode -1)
  1992. (setq truncate-lines nil)
  1993. (setq word-wrap t)
  1994. (goto-char (setq p (point-max)))
  1995. (insert (org-trim field))
  1996. (remove-text-properties p (point-max) '(invisible t intangible t))
  1997. (goto-char p)
  1998. (setq-local org-finish-function 'org-table-finish-edit-field)
  1999. (setq-local org-window-configuration cw)
  2000. (setq-local org-field-marker pos)
  2001. (message "Edit and finish with C-c C-c")))))
  2002. (defun org-table-finish-edit-field ()
  2003. "Finish editing a table data field.
  2004. Remove all newline characters, insert the result into the table, realign
  2005. the table and kill the editing buffer."
  2006. (let ((pos org-field-marker)
  2007. (cw org-window-configuration)
  2008. (cb (current-buffer))
  2009. text)
  2010. (goto-char (point-min))
  2011. (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
  2012. (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
  2013. (replace-match " "))
  2014. (setq text (org-trim (buffer-string)))
  2015. (set-window-configuration cw)
  2016. (kill-buffer cb)
  2017. (select-window (get-buffer-window (marker-buffer pos)))
  2018. (goto-char pos)
  2019. (move-marker pos nil)
  2020. (org-table-check-inside-data-field)
  2021. (org-table-get-field nil text)
  2022. (org-table-align)
  2023. (message "New field value inserted")))
  2024. (define-minor-mode org-table-follow-field-mode
  2025. "Minor mode to make the table field editor window follow the cursor.
  2026. When this mode is active, the field editor window will always show the
  2027. current field. The mode exits automatically when the cursor leaves the
  2028. table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
  2029. nil " TblFollow" nil
  2030. (if org-table-follow-field-mode
  2031. (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
  2032. 'append 'local)
  2033. (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
  2034. (let* ((buf (get-buffer "*Org Table Edit Field*"))
  2035. (win (and buf (get-buffer-window buf))))
  2036. (when win (delete-window win))
  2037. (when buf
  2038. (with-current-buffer buf
  2039. (move-marker org-field-marker nil))
  2040. (kill-buffer buf)))))
  2041. (defun org-table-follow-fields-with-editor ()
  2042. (if (and org-table-exit-follow-field-mode-when-leaving-table
  2043. (not (org-at-table-p)))
  2044. ;; We have left the table, exit the follow mode
  2045. (org-table-follow-field-mode -1)
  2046. (when (org-table-check-inside-data-field 'noerror)
  2047. (let ((win (selected-window)))
  2048. (org-table-edit-field nil)
  2049. (org-fit-window-to-buffer)
  2050. (select-window win)))))
  2051. (defvar org-timecnt) ; dynamically scoped parameter
  2052. ;;;###autoload
  2053. (defun org-table-sum (&optional beg end nlast)
  2054. "Sum numbers in region of current table column.
  2055. The result will be displayed in the echo area, and will be available
  2056. as kill to be inserted with \\[yank].
  2057. If there is an active region, it is interpreted as a rectangle and all
  2058. numbers in that rectangle will be summed. If there is no active
  2059. region and point is located in a table column, sum all numbers in that
  2060. column.
  2061. If at least one number looks like a time HH:MM or HH:MM:SS, all other
  2062. numbers are assumed to be times as well (in decimal hours) and the
  2063. numbers are added as such.
  2064. If NLAST is a number, only the NLAST fields will actually be summed."
  2065. (interactive)
  2066. (save-excursion
  2067. (let (col (org-timecnt 0) diff h m s org-table-clip)
  2068. (cond
  2069. ((and beg end)) ; beg and end given explicitly
  2070. ((org-region-active-p)
  2071. (setq beg (region-beginning) end (region-end)))
  2072. (t
  2073. (setq col (org-table-current-column))
  2074. (goto-char (org-table-begin))
  2075. (unless (re-search-forward "^[ \t]*|[^-]" nil t)
  2076. (user-error "No table data"))
  2077. (org-table-goto-column col)
  2078. (setq beg (point))
  2079. (goto-char (org-table-end))
  2080. (unless (re-search-backward "^[ \t]*|[^-]" nil t)
  2081. (user-error "No table data"))
  2082. (org-table-goto-column col)
  2083. (setq end (point))))
  2084. (let* ((items (apply 'append (org-table-copy-region beg end)))
  2085. (items1 (cond ((not nlast) items)
  2086. ((>= nlast (length items)) items)
  2087. (t (setq items (reverse items))
  2088. (setcdr (nthcdr (1- nlast) items) nil)
  2089. (nreverse items))))
  2090. (numbers (delq nil (mapcar 'org-table-get-number-for-summing
  2091. items1)))
  2092. (res (apply '+ numbers))
  2093. (sres (if (= org-timecnt 0)
  2094. (number-to-string res)
  2095. (setq diff (* 3600 res)
  2096. h (floor (/ diff 3600)) diff (mod diff 3600)
  2097. m (floor (/ diff 60)) diff (mod diff 60)
  2098. s diff)
  2099. (format "%.0f:%02.0f:%02.0f" h m s))))
  2100. (kill-new sres)
  2101. (when (called-interactively-p 'interactive)
  2102. (message "%s" (substitute-command-keys
  2103. (format "Sum of %d items: %-20s \
  2104. \(\\[yank] will insert result into buffer)" (length numbers) sres))))
  2105. sres))))
  2106. (defun org-table-get-number-for-summing (s)
  2107. (let (n)
  2108. (if (string-match "^ *|? *" s)
  2109. (setq s (replace-match "" nil nil s)))
  2110. (if (string-match " *|? *$" s)
  2111. (setq s (replace-match "" nil nil s)))
  2112. (setq n (string-to-number s))
  2113. (cond
  2114. ((and (string-match "0" s)
  2115. (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
  2116. ((string-match "\\`[ \t]+\\'" s) nil)
  2117. ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
  2118. (let ((h (string-to-number (or (match-string 1 s) "0")))
  2119. (m (string-to-number (or (match-string 2 s) "0")))
  2120. (s (string-to-number (or (match-string 4 s) "0"))))
  2121. (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
  2122. (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
  2123. ((equal n 0) nil)
  2124. (t n))))
  2125. (defun org-table-current-field-formula (&optional key noerror)
  2126. "Return the formula active for the current field.
  2127. Assumes that table is already analyzed. If KEY is given, return
  2128. the key to this formula. Otherwise return the formula preceded
  2129. with \"=\" or \":=\"."
  2130. (let* ((line (count-lines org-table-current-begin-pos
  2131. (line-beginning-position)))
  2132. (row (org-table-line-to-dline line)))
  2133. (cond
  2134. (row
  2135. (let* ((col (org-table-current-column))
  2136. (name (car (rassoc (list line col)
  2137. org-table-named-field-locations)))
  2138. (scol (format "$%d" col))
  2139. (ref (format "@%d$%d" (org-table-current-dline) col))
  2140. (stored-list (org-table-get-stored-formulas noerror))
  2141. (ass (or (assoc name stored-list)
  2142. (assoc ref stored-list)
  2143. (assoc scol stored-list))))
  2144. (cond (key (car ass))
  2145. (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
  2146. (cdr ass))))))
  2147. (noerror nil)
  2148. (t (error "No formula active for the current field")))))
  2149. (defun org-table-get-formula (&optional equation named)
  2150. "Read a formula from the minibuffer, offer stored formula as default.
  2151. When NAMED is non-nil, look for a named equation."
  2152. (let* ((stored-list (org-table-get-stored-formulas))
  2153. (name (car (rassoc (list (count-lines org-table-current-begin-pos
  2154. (line-beginning-position))
  2155. (org-table-current-column))
  2156. org-table-named-field-locations)))
  2157. (ref (format "@%d$%d"
  2158. (org-table-current-dline)
  2159. (org-table-current-column)))
  2160. (scol (cond
  2161. ((not named) (format "$%d" (org-table-current-column)))
  2162. ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name)
  2163. (t ref)))
  2164. (name (or name ref))
  2165. (org-table-may-need-update nil)
  2166. (stored (cdr (assoc scol stored-list)))
  2167. (eq (cond
  2168. ((and stored equation (string-match-p "^ *=? *$" equation))
  2169. stored)
  2170. ((stringp equation) equation)
  2171. (t
  2172. (org-table-formula-from-user
  2173. (read-string
  2174. (org-table-formula-to-user
  2175. (format "%s formula %s=" (if named "Field" "Column") scol))
  2176. (if stored (org-table-formula-to-user stored) "")
  2177. 'org-table-formula-history)))))
  2178. mustsave)
  2179. (unless (org-string-nw-p eq)
  2180. ;; Remove formula.
  2181. (setq stored-list (delq (assoc scol stored-list) stored-list))
  2182. (org-table-store-formulas stored-list)
  2183. (user-error "Formula removed"))
  2184. (when (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  2185. (when (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  2186. (when (and name (not named))
  2187. ;; We set the column equation, delete the named one.
  2188. (setq stored-list (delq (assoc name stored-list) stored-list)
  2189. mustsave t))
  2190. (if stored
  2191. (setcdr (assoc scol stored-list) eq)
  2192. (setq stored-list (cons (cons scol eq) stored-list)))
  2193. (when (or mustsave (not (equal stored eq)))
  2194. (org-table-store-formulas stored-list))
  2195. eq))
  2196. (defun org-table-store-formulas (alist &optional location)
  2197. "Store the list of formulas below the current table.
  2198. If optional argument LOCATION is a buffer position, insert it at
  2199. LOCATION instead."
  2200. (save-excursion
  2201. (if location
  2202. (progn (goto-char location) (beginning-of-line))
  2203. (goto-char (org-table-end)))
  2204. (let ((case-fold-search t))
  2205. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
  2206. (progn
  2207. ;; Don't overwrite TBLFM, we might use text properties to
  2208. ;; store stuff.
  2209. (goto-char (match-beginning 3))
  2210. (delete-region (match-beginning 3) (match-end 0)))
  2211. (org-indent-line)
  2212. (insert (or (match-string 2) "#+TBLFM:")))
  2213. (insert " "
  2214. (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
  2215. (sort alist #'org-table-formula-less-p)
  2216. "::")
  2217. "\n"))))
  2218. (defsubst org-table-formula-make-cmp-string (a)
  2219. (when (string-match "\\`$[<>]" a)
  2220. (let ((arrow (string-to-char (substring a 1))))
  2221. ;; Fake a high number to make sure this is sorted at the end.
  2222. (setq a (org-table-formula-handle-first/last-rc a))
  2223. (setq a (format "$%d" (+ 10000
  2224. (if (= arrow ?<) -1000 0)
  2225. (string-to-number (substring a 1)))))))
  2226. (when (string-match
  2227. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  2228. a)
  2229. (concat
  2230. (if (match-end 2)
  2231. (format "@%05d" (string-to-number (match-string 2 a))) "")
  2232. (if (match-end 4)
  2233. (format "$%05d" (string-to-number (match-string 4 a))) "")
  2234. (if (match-end 5)
  2235. (concat "@@" (match-string 5 a))))))
  2236. (defun org-table-formula-less-p (a b)
  2237. "Compare two formulas for sorting."
  2238. (let ((as (org-table-formula-make-cmp-string (car a)))
  2239. (bs (org-table-formula-make-cmp-string (car b))))
  2240. (and as bs (string< as bs))))
  2241. ;;;###autoload
  2242. (defun org-table-get-stored-formulas (&optional noerror location)
  2243. "Return an alist with the stored formulas directly after current table.
  2244. By default, only return active formulas, i.e., formulas located
  2245. on the first line after the table. However, if optional argument
  2246. LOCATION is a buffer position, consider the formulas there."
  2247. (save-excursion
  2248. (if location
  2249. (progn (goto-char location) (beginning-of-line))
  2250. (goto-char (org-table-end)))
  2251. (let ((case-fold-search t))
  2252. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
  2253. (let ((strings (org-split-string (match-string-no-properties 2)
  2254. " *:: *"))
  2255. eq-alist seen)
  2256. (dolist (string strings (nreverse eq-alist))
  2257. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
  2258. \[<>]+\\)\\) *= *\\(.*[^ \t]\\)"
  2259. string)
  2260. (let ((lhs
  2261. (let ((m (match-string 1 string)))
  2262. (cond
  2263. ((not (match-end 2)) m)
  2264. ;; Is it a column reference?
  2265. ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m)
  2266. ;; Since named columns are not possible in
  2267. ;; LHS, assume this is a named field.
  2268. (t (match-string 2 string)))))
  2269. (rhs (match-string 3 string)))
  2270. (push (cons lhs rhs) eq-alist)
  2271. (cond
  2272. ((not (member lhs seen)) (push lhs seen))
  2273. (noerror
  2274. (message
  2275. "Double definition `%s=' in TBLFM line, please fix by hand"
  2276. lhs)
  2277. (ding)
  2278. (sit-for 2))
  2279. (t
  2280. (user-error
  2281. "Double definition `%s=' in TBLFM line, please fix by hand"
  2282. lhs)))))))))))
  2283. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2284. "Modify the equations after the table structure has been edited.
  2285. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2286. For all numbers larger than LIMIT, shift them by DELTA."
  2287. (save-excursion
  2288. (goto-char (org-table-end))
  2289. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2290. (let ((msg "The formulas in #+TBLFM have been updated")
  2291. (re (concat key "\\([0-9]+\\)"))
  2292. (re2
  2293. (when remove
  2294. (if (or (equal key "$") (equal key "$LR"))
  2295. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2296. (regexp-quote key) remove)
  2297. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2298. s n a)
  2299. (when remove
  2300. (while (re-search-forward re2 (point-at-eol) t)
  2301. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2302. (if (equal (char-before (match-beginning 0)) ?.)
  2303. (user-error
  2304. "Change makes TBLFM term %s invalid, use undo to recover"
  2305. (match-string 0))
  2306. (replace-match "")))))
  2307. (while (re-search-forward re (point-at-eol) t)
  2308. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2309. (setq s (match-string 1) n (string-to-number s))
  2310. (cond
  2311. ((setq a (assoc s replace))
  2312. (replace-match (concat key (cdr a)) t t)
  2313. (message msg))
  2314. ((and limit (> n limit))
  2315. (replace-match (concat key (int-to-string (+ n delta))) t t)
  2316. (message msg))))))
  2317. (forward-line))))
  2318. ;;;###autoload
  2319. (defun org-table-maybe-eval-formula ()
  2320. "Check if the current field starts with \"=\" or \":=\".
  2321. If yes, store the formula and apply it."
  2322. ;; We already know we are in a table. Get field will only return a formula
  2323. ;; when appropriate. It might return a separator line, but no problem.
  2324. (when org-table-formula-evaluate-inline
  2325. (let* ((field (org-trim (or (org-table-get-field) "")))
  2326. named eq)
  2327. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2328. (setq named (equal (string-to-char field) ?:)
  2329. eq (match-string 1 field))
  2330. (org-table-eval-formula (and named '(4))
  2331. (org-table-formula-from-user eq))))))
  2332. (defvar org-recalc-commands nil
  2333. "List of commands triggering the recalculation of a line.
  2334. Will be filled automatically during use.")
  2335. (defvar org-recalc-marks
  2336. '((" " . "Unmarked: no special line, no automatic recalculation")
  2337. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  2338. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  2339. ("!" . "Column name definition line. Reference in formula as $name.")
  2340. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  2341. ("_" . "Names for values in row below this one.")
  2342. ("^" . "Names for values in row above this one.")))
  2343. ;;;###autoload
  2344. (defun org-table-rotate-recalc-marks (&optional newchar)
  2345. "Rotate the recalculation mark in the first column.
  2346. If in any row, the first field is not consistent with a mark,
  2347. insert a new column for the markers.
  2348. When there is an active region, change all the lines in the region,
  2349. after prompting for the marking character.
  2350. After each change, a message will be displayed indicating the meaning
  2351. of the new mark."
  2352. (interactive)
  2353. (unless (org-at-table-p) (user-error "Not at a table"))
  2354. (let* ((region (org-region-active-p))
  2355. (l1 (and region
  2356. (save-excursion (goto-char (region-beginning))
  2357. (copy-marker (line-beginning-position)))))
  2358. (l2 (and region
  2359. (save-excursion (goto-char (region-end))
  2360. (copy-marker (line-beginning-position)))))
  2361. (l (copy-marker (line-beginning-position)))
  2362. (col (org-table-current-column))
  2363. (newchar (if region
  2364. (char-to-string
  2365. (read-char-exclusive
  2366. "Change region to what mark? Type # * ! $ or SPC: "))
  2367. newchar))
  2368. (no-special-column
  2369. (save-excursion
  2370. (goto-char (org-table-begin))
  2371. (re-search-forward
  2372. "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
  2373. (when (and newchar (not (assoc newchar org-recalc-marks)))
  2374. (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
  2375. newchar))
  2376. (when l1 (goto-char l1))
  2377. (save-excursion
  2378. (beginning-of-line)
  2379. (unless (looking-at org-table-dataline-regexp)
  2380. (user-error "Not at a table data line")))
  2381. (when no-special-column
  2382. (org-table-goto-column 1)
  2383. (org-table-insert-column))
  2384. (let ((previous-line-end (line-end-position))
  2385. (newchar
  2386. (save-excursion
  2387. (beginning-of-line)
  2388. (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
  2389. (newchar)
  2390. (t (cadr (member (match-string 1)
  2391. (append (mapcar #'car org-recalc-marks)
  2392. '(" ")))))))))
  2393. ;; Rotate mark in first row.
  2394. (org-table-get-field 1 (format " %s " newchar))
  2395. ;; Rotate marks in additional rows if a region is active.
  2396. (when region
  2397. (save-excursion
  2398. (forward-line)
  2399. (while (<= (point) l2)
  2400. (when (looking-at org-table-dataline-regexp)
  2401. (org-table-get-field 1 (format " %s " newchar)))
  2402. (forward-line))))
  2403. ;; Only align if rotation actually changed lines' length.
  2404. (when (/= previous-line-end (line-end-position)) (org-table-align)))
  2405. (goto-char l)
  2406. (org-table-goto-column (if no-special-column (1+ col) col))
  2407. (when l1 (set-marker l1 nil))
  2408. (when l2 (set-marker l2 nil))
  2409. (set-marker l nil)
  2410. (when (called-interactively-p 'interactive)
  2411. (message "%s" (cdr (assoc newchar org-recalc-marks))))))
  2412. ;;;###autoload
  2413. (defun org-table-analyze ()
  2414. "Analyze table at point and store results.
  2415. This function sets up the following dynamically scoped variables:
  2416. `org-table-column-name-regexp',
  2417. `org-table-column-names',
  2418. `org-table-current-begin-pos',
  2419. `org-table-current-line-types',
  2420. `org-table-current-ncol',
  2421. `org-table-dlines',
  2422. `org-table-hlines',
  2423. `org-table-local-parameters',
  2424. `org-table-named-field-locations'."
  2425. (let ((beg (org-table-begin))
  2426. (end (org-table-end)))
  2427. (save-excursion
  2428. (goto-char beg)
  2429. ;; Extract column names.
  2430. (setq org-table-column-names nil)
  2431. (when (save-excursion
  2432. (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
  2433. (let ((c 1))
  2434. (dolist (name (org-split-string (match-string 1) " *| *"))
  2435. (cl-incf c)
  2436. (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
  2437. (push (cons name (int-to-string c)) org-table-column-names)))))
  2438. (setq org-table-column-names (nreverse org-table-column-names))
  2439. (setq org-table-column-name-regexp
  2440. (format "\\$\\(%s\\)\\>"
  2441. (regexp-opt (mapcar #'car org-table-column-names) t)))
  2442. ;; Extract local parameters.
  2443. (setq org-table-local-parameters nil)
  2444. (save-excursion
  2445. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  2446. (dolist (field (org-split-string (match-string 1) " *| *"))
  2447. (when (string-match
  2448. "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  2449. (push (cons (match-string 1 field) (match-string 2 field))
  2450. org-table-local-parameters)))))
  2451. ;; Update named fields locations. We minimize `count-lines'
  2452. ;; processing by storing last known number of lines in LAST.
  2453. (setq org-table-named-field-locations nil)
  2454. (save-excursion
  2455. (let ((last (cons (point) 0)))
  2456. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  2457. (let ((c (match-string 1))
  2458. (fields (org-split-string (match-string 2) " *| *")))
  2459. (save-excursion
  2460. (forward-line (if (equal c "_") 1 -1))
  2461. (let ((fields1
  2462. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  2463. (org-split-string (match-string 1) " *| *")))
  2464. (line (cl-incf (cdr last) (count-lines (car last) (point))))
  2465. (col 1))
  2466. (setcar last (point)) ; Update last known position.
  2467. (while (and fields fields1)
  2468. (let ((field (pop fields))
  2469. (v (pop fields1)))
  2470. (cl-incf col)
  2471. (when (and (stringp field)
  2472. (stringp v)
  2473. (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
  2474. field))
  2475. (push (cons field v) org-table-local-parameters)
  2476. (push (list field line col)
  2477. org-table-named-field-locations))))))))))
  2478. ;; Re-use existing markers when possible.
  2479. (if (markerp org-table-current-begin-pos)
  2480. (move-marker org-table-current-begin-pos (point))
  2481. (setq org-table-current-begin-pos (point-marker)))
  2482. ;; Analyze the line types.
  2483. (let ((l 0) hlines dlines types)
  2484. (while (looking-at "[ \t]*|\\(-\\)?")
  2485. (push (if (match-end 1) 'hline 'dline) types)
  2486. (if (match-end 1) (push l hlines) (push l dlines))
  2487. (forward-line)
  2488. (cl-incf l))
  2489. (push 'hline types) ; Add an imaginary extra hline to the end.
  2490. (setq org-table-current-line-types (apply #'vector (nreverse types)))
  2491. (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
  2492. (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
  2493. ;; Get the number of columns from the first data line in table.
  2494. (goto-char beg)
  2495. (forward-line (aref org-table-dlines 1))
  2496. (let* ((fields
  2497. (org-split-string
  2498. (buffer-substring (line-beginning-position) (line-end-position))
  2499. "[ \t]*|[ \t]*"))
  2500. (nfields (length fields))
  2501. al al2)
  2502. (setq org-table-current-ncol nfields)
  2503. (let ((last-dline
  2504. (aref org-table-dlines (1- (length org-table-dlines)))))
  2505. (dotimes (i nfields)
  2506. (let ((column (1+ i)))
  2507. (push (list (format "LR%d" column) last-dline column) al)
  2508. (push (cons (format "LR%d" column) (nth i fields)) al2))))
  2509. (setq org-table-named-field-locations
  2510. (append org-table-named-field-locations al))
  2511. (setq org-table-local-parameters
  2512. (append org-table-local-parameters al2))))))
  2513. (defun org-table-goto-field (ref &optional create-column-p)
  2514. "Move point to a specific field in the current table.
  2515. REF is either the name of a field its absolute reference, as
  2516. a string. No column is created unless CREATE-COLUMN-P is
  2517. non-nil. If it is a function, it is called with the column
  2518. number as its argument as is used as a predicate to know if the
  2519. column can be created.
  2520. This function assumes the table is already analyzed (i.e., using
  2521. `org-table-analyze')."
  2522. (let* ((coordinates
  2523. (cond
  2524. ((cdr (assoc ref org-table-named-field-locations)))
  2525. ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
  2526. (list (condition-case nil
  2527. (aref org-table-dlines
  2528. (string-to-number (match-string 1 ref)))
  2529. (error (user-error "Invalid row number in %s" ref)))
  2530. (string-to-number (match-string 2 ref))))
  2531. (t (user-error "Unknown field: %s" ref))))
  2532. (line (car coordinates))
  2533. (column (nth 1 coordinates))
  2534. (create-new-column (if (functionp create-column-p)
  2535. (funcall create-column-p column)
  2536. create-column-p)))
  2537. (when coordinates
  2538. (goto-char org-table-current-begin-pos)
  2539. (forward-line line)
  2540. (org-table-goto-column column nil create-new-column))))
  2541. ;;;###autoload
  2542. (defun org-table-maybe-recalculate-line ()
  2543. "Recompute the current line if marked for it, and if we haven't just done it."
  2544. (interactive)
  2545. (and org-table-allow-automatic-line-recalculation
  2546. (not (and (memq last-command org-recalc-commands)
  2547. (eq org-last-recalc-line (line-beginning-position))))
  2548. (save-excursion (beginning-of-line 1)
  2549. (looking-at org-table-auto-recalculate-regexp))
  2550. (org-table-recalculate) t))
  2551. (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
  2552. (defsubst org-set-calc-mode (var &optional value)
  2553. (if (stringp var)
  2554. (setq var (assoc var '(("D" calc-angle-mode deg)
  2555. ("R" calc-angle-mode rad)
  2556. ("F" calc-prefer-frac t)
  2557. ("S" calc-symbolic-mode t)))
  2558. value (nth 2 var) var (nth 1 var)))
  2559. (if (memq var org-tbl-calc-modes)
  2560. (setcar (cdr (memq var org-tbl-calc-modes)) value)
  2561. (cons var (cons value org-tbl-calc-modes)))
  2562. org-tbl-calc-modes)
  2563. ;;;###autoload
  2564. (defun org-table-eval-formula (&optional arg equation
  2565. suppress-align suppress-const
  2566. suppress-store suppress-analysis)
  2567. "Replace the table field value at the cursor by the result of a calculation.
  2568. In a table, this command replaces the value in the current field with the
  2569. result of a formula. It also installs the formula as the \"current\" column
  2570. formula, by storing it in a special line below the table. When called
  2571. with a `\\[universal-argument]' prefix the formula is installed as a \
  2572. field formula.
  2573. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  2574. insert the active equation for the field
  2575. back into the current field, so that it can be edited there. This is \
  2576. useful
  2577. in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
  2578. check the referenced fields.
  2579. When called, the command first prompts for a formula, which is read in
  2580. the minibuffer. Previously entered formulas are available through the
  2581. history list, and the last used formula is offered as a default.
  2582. These stored formulas are adapted correctly when moving, inserting, or
  2583. deleting columns with the corresponding commands.
  2584. The formula can be any algebraic expression understood by the Calc package.
  2585. For details, see the Org mode manual.
  2586. This function can also be called from Lisp programs and offers
  2587. additional arguments: EQUATION can be the formula to apply. If this
  2588. argument is given, the user will not be prompted.
  2589. SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
  2590. unnecessary aligns.
  2591. SUPPRESS-CONST suppresses the interpretation of constants in the
  2592. formula, assuming that this has been done already outside the
  2593. function.
  2594. SUPPRESS-STORE means the formula should not be stored, either
  2595. because it is already stored, or because it is a modified
  2596. equation that should not overwrite the stored one.
  2597. SUPPRESS-ANALYSIS prevents analyzing the table and checking
  2598. location of point."
  2599. (interactive "P")
  2600. (unless suppress-analysis
  2601. (org-table-check-inside-data-field nil t)
  2602. (org-table-analyze))
  2603. (if (equal arg '(16))
  2604. (let ((eq (org-table-current-field-formula)))
  2605. (org-table-get-field nil eq)
  2606. (org-table-align)
  2607. (setq org-table-may-need-update t))
  2608. (let* (fields
  2609. (ndown (if (integerp arg) arg 1))
  2610. (org-table-automatic-realign nil)
  2611. (case-fold-search nil)
  2612. (down (> ndown 1))
  2613. (formula (if (and equation suppress-store)
  2614. equation
  2615. (org-table-get-formula equation (equal arg '(4)))))
  2616. (n0 (org-table-current-column))
  2617. (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
  2618. (numbers nil) ; was a variable, now fixed default
  2619. (keep-empty nil)
  2620. n form form0 formrpl formrg bw fmt x ev orig c lispp literal
  2621. duration duration-output-format)
  2622. ;; Parse the format string. Since we have a lot of modes, this is
  2623. ;; a lot of work. However, I think calc still uses most of the time.
  2624. (if (string-match ";" formula)
  2625. (let ((tmp (org-split-string formula ";")))
  2626. (setq formula (car tmp)
  2627. fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2628. (nth 1 tmp)))
  2629. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2630. (setq c (string-to-char (match-string 1 fmt))
  2631. n (string-to-number (match-string 2 fmt)))
  2632. (if (= c ?p)
  2633. (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
  2634. (setq org-tbl-calc-modes
  2635. (org-set-calc-mode
  2636. 'calc-float-format
  2637. (list (cdr (assoc c '((?n . float) (?f . fix)
  2638. (?s . sci) (?e . eng))))
  2639. n))))
  2640. (setq fmt (replace-match "" t t fmt)))
  2641. (if (string-match "[tTU]" fmt)
  2642. (let ((ff (match-string 0 fmt)))
  2643. (setq duration t numbers t
  2644. duration-output-format
  2645. (cond ((equal ff "T") nil)
  2646. ((equal ff "t") org-table-duration-custom-format)
  2647. ((equal ff "U") 'hh:mm))
  2648. fmt (replace-match "" t t fmt))))
  2649. (if (string-match "N" fmt)
  2650. (setq numbers t
  2651. fmt (replace-match "" t t fmt)))
  2652. (if (string-match "L" fmt)
  2653. (setq literal t
  2654. fmt (replace-match "" t t fmt)))
  2655. (if (string-match "E" fmt)
  2656. (setq keep-empty t
  2657. fmt (replace-match "" t t fmt)))
  2658. (while (string-match "[DRFS]" fmt)
  2659. (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
  2660. (setq fmt (replace-match "" t t fmt)))
  2661. (unless (string-match "\\S-" fmt)
  2662. (setq fmt nil))))
  2663. (when (and (not suppress-const) org-table-formula-use-constants)
  2664. (setq formula (org-table-formula-substitute-names formula)))
  2665. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2666. (setq formula (org-table-formula-handle-first/last-rc formula))
  2667. (while (> ndown 0)
  2668. (setq fields (org-split-string
  2669. (org-trim
  2670. (buffer-substring-no-properties
  2671. (line-beginning-position) (line-end-position)))
  2672. " *| *"))
  2673. ;; replace fields with duration values if relevant
  2674. (if duration
  2675. (setq fields
  2676. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2677. fields)))
  2678. (if (eq numbers t)
  2679. (setq fields (mapcar
  2680. (lambda (x)
  2681. (if (string-match "\\S-" x)
  2682. (number-to-string (string-to-number x))
  2683. x))
  2684. fields)))
  2685. (setq ndown (1- ndown))
  2686. (setq form (copy-sequence formula)
  2687. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2688. (if (and lispp literal) (setq lispp 'literal))
  2689. ;; Insert row and column number of formula result field
  2690. (while (string-match "[@$]#" form)
  2691. (setq form
  2692. (replace-match
  2693. (format "%d"
  2694. (save-match-data
  2695. (if (equal (substring form (match-beginning 0)
  2696. (1+ (match-beginning 0)))
  2697. "@")
  2698. (org-table-current-dline)
  2699. (org-table-current-column))))
  2700. t t form)))
  2701. ;; Check for old vertical references
  2702. (org-table--error-on-old-row-references form)
  2703. ;; Insert remote references
  2704. (setq form (org-table-remote-reference-indirection form))
  2705. (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2706. (setq form
  2707. (replace-match
  2708. (save-match-data
  2709. (org-table-make-reference
  2710. (let ((rmtrng (org-table-get-remote-range
  2711. (match-string 1 form) (match-string 2 form))))
  2712. (if duration
  2713. (if (listp rmtrng)
  2714. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2715. (org-table-time-string-to-seconds rmtrng))
  2716. rmtrng))
  2717. keep-empty numbers lispp))
  2718. t t form)))
  2719. ;; Insert complex ranges
  2720. (while (and (string-match org-table-range-regexp form)
  2721. (> (length (match-string 0 form)) 1))
  2722. (setq formrg
  2723. (save-match-data
  2724. (org-table-get-range
  2725. (match-string 0 form) org-table-current-begin-pos n0)))
  2726. (setq formrpl
  2727. (save-match-data
  2728. (org-table-make-reference
  2729. ;; possibly handle durations
  2730. (if duration
  2731. (if (listp formrg)
  2732. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2733. (org-table-time-string-to-seconds formrg))
  2734. formrg)
  2735. keep-empty numbers lispp)))
  2736. (if (not (save-match-data
  2737. (string-match (regexp-quote form) formrpl)))
  2738. (setq form (replace-match formrpl t t form))
  2739. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2740. ;; Insert simple ranges, i.e. included in the current row.
  2741. (while (string-match
  2742. "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
  2743. form)
  2744. (setq form
  2745. (replace-match
  2746. (save-match-data
  2747. (org-table-make-reference
  2748. (cl-subseq fields
  2749. (+ (if (match-end 2) n0 0)
  2750. (string-to-number (match-string 1 form))
  2751. -1)
  2752. (+ (if (match-end 4) n0 0)
  2753. (string-to-number (match-string 3 form))))
  2754. keep-empty numbers lispp))
  2755. t t form)))
  2756. (setq form0 form)
  2757. ;; Insert the references to fields in same row
  2758. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2759. (setq n (+ (string-to-number (match-string 1 form))
  2760. (if (match-end 2) n0 0))
  2761. x (nth (1- (if (= n 0) n0 (max n 1))) fields)
  2762. formrpl (save-match-data
  2763. (org-table-make-reference
  2764. x keep-empty numbers lispp)))
  2765. (when (or (not x)
  2766. (save-match-data
  2767. (string-match (regexp-quote formula) formrpl)))
  2768. (user-error "Invalid field specifier \"%s\""
  2769. (match-string 0 form)))
  2770. (setq form (replace-match formrpl t t form)))
  2771. (if lispp
  2772. (setq ev (condition-case nil
  2773. (eval (eval (read form)))
  2774. (error "#ERROR"))
  2775. ev (if (numberp ev) (number-to-string ev) ev)
  2776. ev (if duration (org-table-time-seconds-to-string
  2777. (string-to-number ev)
  2778. duration-output-format) ev))
  2779. ;; Use <...> time-stamps so that Calc can handle them.
  2780. (setq form
  2781. (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
  2782. ;; Internationalize local time-stamps by setting locale to
  2783. ;; "C".
  2784. (setq form
  2785. (replace-regexp-in-string
  2786. org-ts-regexp
  2787. (lambda (ts)
  2788. (let ((system-time-locale "C"))
  2789. (format-time-string
  2790. (org-time-stamp-format
  2791. (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2792. (apply #'encode-time
  2793. (save-match-data (org-parse-time-string ts))))))
  2794. form t t))
  2795. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2796. form
  2797. (calc-eval (cons form org-tbl-calc-modes)
  2798. (when (and (not keep-empty) numbers) 'num)))
  2799. ev (if duration (org-table-time-seconds-to-string
  2800. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2801. (string-to-number (org-table-time-string-to-seconds ev))
  2802. (string-to-number ev))
  2803. duration-output-format)
  2804. ev)))
  2805. (when org-table-formula-debug
  2806. (with-output-to-temp-buffer "*Substitution History*"
  2807. (princ (format "Substitution history of formula
  2808. Orig: %s
  2809. $xyz-> %s
  2810. @r$c-> %s
  2811. $1-> %s\n" orig formula form0 form))
  2812. (if (consp ev)
  2813. (princ (format " %s^\nError: %s"
  2814. (make-string (car ev) ?\-) (nth 1 ev)))
  2815. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2816. ev (or fmt "NONE")
  2817. (if fmt (format fmt (string-to-number ev)) ev)))))
  2818. (setq bw (get-buffer-window "*Substitution History*"))
  2819. (org-fit-window-to-buffer bw)
  2820. (unless (and (called-interactively-p 'any) (not ndown))
  2821. (unless (let (inhibit-redisplay)
  2822. (y-or-n-p "Debugging Formula. Continue to next? "))
  2823. (org-table-align)
  2824. (user-error "Abort"))
  2825. (delete-window bw)
  2826. (message "")))
  2827. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2828. (org-table-justify-field-maybe
  2829. (format org-table-formula-field-format
  2830. (cond
  2831. ((not (stringp ev)) ev)
  2832. (fmt (format fmt (string-to-number ev)))
  2833. ;; Replace any active time stamp in the result with
  2834. ;; an inactive one. Dates in tables are likely
  2835. ;; piece of regular data, not meant to appear in the
  2836. ;; agenda.
  2837. (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev)))))
  2838. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2839. (call-interactively 'org-return)
  2840. (setq ndown 0)))
  2841. (and down (org-table-maybe-recalculate-line))
  2842. (or suppress-align (and org-table-may-need-update
  2843. (org-table-align))))))
  2844. (defun org-table-put-field-property (prop value)
  2845. (save-excursion
  2846. (put-text-property (progn (skip-chars-backward "^|") (point))
  2847. (progn (skip-chars-forward "^|") (point))
  2848. prop value)))
  2849. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2850. "Get a calc vector from a column, according to descriptor DESC.
  2851. Optional arguments TBEG and COL can give the beginning of the table and
  2852. the current column, to avoid unnecessary parsing.
  2853. HIGHLIGHT means just highlight the range.
  2854. When CORNERS-ONLY is set, only return the corners of the range as
  2855. a list (line1 column1 line2 column2) where line1 and line2 are
  2856. line numbers relative to beginning of table, or TBEG, and column1
  2857. and column2 are table column numbers."
  2858. (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
  2859. (replace-regexp-in-string "\\$" "@0$" desc)
  2860. desc))
  2861. (col (or col (org-table-current-column)))
  2862. (tbeg (or tbeg (org-table-begin)))
  2863. (thisline (count-lines tbeg (line-beginning-position))))
  2864. (unless (string-match org-table-range-regexp desc)
  2865. (user-error "Invalid table range specifier `%s'" desc))
  2866. (let ((rangep (match-end 3))
  2867. (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
  2868. (or (save-match-data
  2869. (and (org-string-nw-p r)
  2870. (org-table--descriptor-line r thisline)))
  2871. thisline)))
  2872. (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
  2873. (or (save-match-data
  2874. (and (org-string-nw-p r)
  2875. (org-table--descriptor-line r thisline)))
  2876. thisline)))
  2877. (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
  2878. (if (or (not c) (= (string-to-number c) 0)) col
  2879. (+ (string-to-number c)
  2880. (if (memq (string-to-char c) '(?- ?+)) col 0)))))
  2881. (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
  2882. (if (or (not c) (= (string-to-number c) 0)) col
  2883. (+ (string-to-number c)
  2884. (if (memq (string-to-char c) '(?- ?+)) col 0))))))
  2885. (save-excursion
  2886. (if (and (not corners-only)
  2887. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2888. ;; Just one field.
  2889. (progn
  2890. (forward-line (- r1 thisline))
  2891. (while (not (looking-at org-table-dataline-regexp))
  2892. (forward-line))
  2893. (prog1 (org-trim (org-table-get-field c1))
  2894. (when highlight (org-table-highlight-rectangle))))
  2895. ;; A range, return a vector. First sort the numbers to get
  2896. ;; a regular rectangle.
  2897. (let ((first-row (min r1 r2))
  2898. (last-row (max r1 r2))
  2899. (first-column (min c1 c2))
  2900. (last-column (max c1 c2)))
  2901. (if corners-only (list first-row first-column last-row last-column)
  2902. ;; Copy the range values into a list.
  2903. (forward-line (- first-row thisline))
  2904. (while (not (looking-at org-table-dataline-regexp))
  2905. (forward-line)
  2906. (cl-incf first-row))
  2907. (org-table-goto-column first-column)
  2908. (let ((beg (point)))
  2909. (forward-line (- last-row first-row))
  2910. (while (not (looking-at org-table-dataline-regexp))
  2911. (forward-line -1))
  2912. (org-table-goto-column last-column)
  2913. (let ((end (point)))
  2914. (when highlight
  2915. (org-table-highlight-rectangle
  2916. beg (progn (skip-chars-forward "^|\n") (point))))
  2917. ;; Return string representation of calc vector.
  2918. (mapcar #'org-trim
  2919. (apply #'append
  2920. (org-table-copy-region beg end))))))))))))
  2921. (defun org-table--descriptor-line (desc cline)
  2922. "Return relative line number corresponding to descriptor DESC.
  2923. The cursor is currently in relative line number CLINE."
  2924. (if (string-match "\\`[0-9]+\\'" desc)
  2925. (aref org-table-dlines (string-to-number desc))
  2926. (when (or (not (string-match
  2927. "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
  2928. ;; 1 2 3 4 5 6
  2929. desc))
  2930. (and (not (match-end 3)) (not (match-end 6)))
  2931. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2932. (user-error "Invalid row descriptor `%s'" desc))
  2933. (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
  2934. (hdir (match-string 2 desc))
  2935. (odir (match-string 5 desc))
  2936. (on (and (match-end 6) (string-to-number (match-string 6 desc))))
  2937. (rel (and (match-end 6)
  2938. (or (and (match-end 1) (not (match-end 3)))
  2939. (match-end 5)))))
  2940. (when (and hn (not hdir))
  2941. (setq cline 0)
  2942. (setq hdir "+")
  2943. (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
  2944. (when (and (not hn) on (not odir)) (user-error "Should never happen"))
  2945. (when hn
  2946. (setq cline
  2947. (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
  2948. (when on
  2949. (setq cline
  2950. (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
  2951. cline)))
  2952. (defun org-table--row-type (type n i backwards relative desc)
  2953. "Return relative line of Nth row with type TYPE.
  2954. Search starts from relative line I. When BACKWARDS in non-nil,
  2955. look before I. When RELATIVE is non-nil, the reference is
  2956. relative. DESC is the original descriptor that started the
  2957. search, as a string."
  2958. (let ((l (length org-table-current-line-types)))
  2959. (catch :exit
  2960. (dotimes (_ n)
  2961. (while (and (cl-incf i (if backwards -1 1))
  2962. (>= i 0)
  2963. (< i l)
  2964. (not (eq (aref org-table-current-line-types i) type))
  2965. ;; We are going to cross a hline. Check if this is
  2966. ;; an authorized move.
  2967. (cond
  2968. ((not relative))
  2969. ((not (eq (aref org-table-current-line-types i) 'hline)))
  2970. ((eq org-table-relative-ref-may-cross-hline t))
  2971. ((eq org-table-relative-ref-may-cross-hline 'error)
  2972. (user-error "Row descriptor %s crosses hline" desc))
  2973. (t (cl-decf i (if backwards -1 1)) ; Step back.
  2974. (throw :exit nil)))))))
  2975. (cond ((or (< i 0) (>= i l))
  2976. (user-error "Row descriptor %s leads outside table" desc))
  2977. ;; The last hline doesn't exist. Instead, point to last row
  2978. ;; in table.
  2979. ((= i (1- l)) (1- i))
  2980. (t i))))
  2981. (defun org-table--error-on-old-row-references (s)
  2982. (when (string-match "&[-+0-9I]" s)
  2983. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2984. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2985. "Convert list ELEMENTS to something appropriate to insert into formula.
  2986. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2987. NUMBERS indicates that everything should be converted to numbers.
  2988. LISPP non-nil means to return something appropriate for a Lisp
  2989. list, `literal' is for the format specifier L."
  2990. ;; Calc nan (not a number) is used for the conversion of the empty
  2991. ;; field to a reference for several reasons: (i) It is accepted in a
  2992. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2993. ;; (ii) In a single field (not in range) it can be distinguished
  2994. ;; from "(nan)" which is the reference made from a single field
  2995. ;; containing "nan".
  2996. (if (stringp elements)
  2997. ;; field reference
  2998. (if lispp
  2999. (if (eq lispp 'literal)
  3000. elements
  3001. (if (and (eq elements "") (not keep-empty))
  3002. ""
  3003. (prin1-to-string
  3004. (if numbers (string-to-number elements) elements))))
  3005. (if (string-match "\\S-" elements)
  3006. (progn
  3007. (when numbers (setq elements (number-to-string
  3008. (string-to-number elements))))
  3009. (concat "(" elements ")"))
  3010. (if (or (not keep-empty) numbers) "(0)" "nan")))
  3011. ;; range reference
  3012. (unless keep-empty
  3013. (setq elements
  3014. (delq nil
  3015. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  3016. elements))))
  3017. (setq elements (or elements '())) ; if delq returns nil then we need '()
  3018. (if lispp
  3019. (mapconcat
  3020. (lambda (x)
  3021. (if (eq lispp 'literal)
  3022. x
  3023. (prin1-to-string (if numbers (string-to-number x) x))))
  3024. elements " ")
  3025. (concat "[" (mapconcat
  3026. (lambda (x)
  3027. (if (string-match "\\S-" x)
  3028. (if numbers
  3029. (number-to-string (string-to-number x))
  3030. x)
  3031. (if (or (not keep-empty) numbers) "0" "nan")))
  3032. elements
  3033. ",") "]"))))
  3034. (defun org-table-message-once-per-second (t1 &rest args)
  3035. "If there has been more than one second since T1, display message.
  3036. ARGS are passed as arguments to the `message' function. Returns
  3037. current time if a message is printed, otherwise returns T1. If
  3038. T1 is nil, always messages."
  3039. (let ((curtime (current-time)))
  3040. (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
  3041. (progn (apply 'message args)
  3042. curtime)
  3043. t1)))
  3044. ;;;###autoload
  3045. (defun org-table-recalculate (&optional all noalign)
  3046. "Recalculate the current table line by applying all stored formulas.
  3047. With prefix arg ALL, do this for all lines in the table.
  3048. When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
  3049. if ALL is the symbol `iterate',
  3050. recompute the table until it no longer changes.
  3051. If NOALIGN is not nil, do not re-align the table after the computations
  3052. are done. This is typically used internally to save time, if it is
  3053. known that the table will be realigned a little later anyway."
  3054. (interactive "P")
  3055. (unless (memq this-command org-recalc-commands)
  3056. (push this-command org-recalc-commands))
  3057. (unless (org-at-table-p) (user-error "Not at a table"))
  3058. (if (or (eq all 'iterate) (equal all '(16)))
  3059. (org-table-iterate)
  3060. (org-table-analyze)
  3061. (let* ((eqlist (sort (org-table-get-stored-formulas)
  3062. (lambda (a b) (string< (car a) (car b)))))
  3063. (inhibit-redisplay (not debug-on-error))
  3064. (line-re org-table-dataline-regexp)
  3065. (log-first-time (current-time))
  3066. (log-last-time log-first-time)
  3067. (cnt 0)
  3068. beg end eqlcol eqlfield)
  3069. ;; Insert constants in all formulas.
  3070. (when eqlist
  3071. (org-table-save-field
  3072. ;; Expand equations, then split the equation list between
  3073. ;; column formulas and field formulas.
  3074. (dolist (eq eqlist)
  3075. (let* ((rhs (org-table-formula-substitute-names
  3076. (org-table-formula-handle-first/last-rc (cdr eq))))
  3077. (old-lhs (car eq))
  3078. (lhs
  3079. (org-table-formula-handle-first/last-rc
  3080. (cond
  3081. ((string-match "\\`@-?I+" old-lhs)
  3082. (user-error "Can't assign to hline relative reference"))
  3083. ((string-match "\\`$[<>]" old-lhs)
  3084. (let ((new (org-table-formula-handle-first/last-rc
  3085. old-lhs)))
  3086. (when (assoc new eqlist)
  3087. (user-error "\"%s=\" formula tries to overwrite \
  3088. existing formula for column %s"
  3089. old-lhs
  3090. new))
  3091. new))
  3092. (t old-lhs)))))
  3093. (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
  3094. (push (cons lhs rhs) eqlcol)
  3095. (push (cons lhs rhs) eqlfield))))
  3096. (setq eqlcol (nreverse eqlcol))
  3097. ;; Expand ranges in lhs of formulas
  3098. (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
  3099. ;; Get the correct line range to process.
  3100. (if all
  3101. (progn
  3102. (setq end (copy-marker (org-table-end)))
  3103. (goto-char (setq beg org-table-current-begin-pos))
  3104. (cond
  3105. ((re-search-forward org-table-calculate-mark-regexp end t)
  3106. ;; This is a table with marked lines, compute selected
  3107. ;; lines.
  3108. (setq line-re org-table-recalculate-regexp))
  3109. ;; Move forward to the first non-header line.
  3110. ((and (re-search-forward org-table-dataline-regexp end t)
  3111. (re-search-forward org-table-hline-regexp end t)
  3112. (re-search-forward org-table-dataline-regexp end t))
  3113. (setq beg (match-beginning 0)))
  3114. ;; Just leave BEG at the start of the table.
  3115. (t nil)))
  3116. (setq beg (line-beginning-position)
  3117. end (copy-marker (line-beginning-position 2))))
  3118. (goto-char beg)
  3119. ;; Mark named fields untouchable. Also check if several
  3120. ;; field/range formulas try to set the same field.
  3121. (remove-text-properties beg end '(:org-untouchable t))
  3122. (let ((current-line (count-lines org-table-current-begin-pos
  3123. (line-beginning-position)))
  3124. seen-fields)
  3125. (dolist (eq eqlfield)
  3126. (let* ((name (car eq))
  3127. (location (assoc name org-table-named-field-locations))
  3128. (eq-line (or (nth 1 location)
  3129. (and (string-match "\\`@\\([0-9]+\\)" name)
  3130. (aref org-table-dlines
  3131. (string-to-number
  3132. (match-string 1 name))))))
  3133. (reference
  3134. (if location
  3135. ;; Turn field coordinates associated to NAME
  3136. ;; into an absolute reference.
  3137. (format "@%d$%d"
  3138. (org-table-line-to-dline eq-line)
  3139. (nth 2 location))
  3140. name)))
  3141. (when (member reference seen-fields)
  3142. (user-error "Several field/range formulas try to set %s"
  3143. reference))
  3144. (push reference seen-fields)
  3145. (when (or all (eq eq-line current-line))
  3146. (org-table-goto-field name)
  3147. (org-table-put-field-property :org-untouchable t)))))
  3148. ;; Evaluate the column formulas, but skip fields covered by
  3149. ;; field formulas.
  3150. (goto-char beg)
  3151. (while (re-search-forward line-re end t)
  3152. (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
  3153. ;; Unprotected line, recalculate.
  3154. (cl-incf cnt)
  3155. (when all
  3156. (setq log-last-time
  3157. (org-table-message-once-per-second
  3158. log-last-time
  3159. "Re-applying formulas to full table...(line %d)" cnt)))
  3160. (if (markerp org-last-recalc-line)
  3161. (move-marker org-last-recalc-line (line-beginning-position))
  3162. (setq org-last-recalc-line
  3163. (copy-marker (line-beginning-position))))
  3164. (dolist (entry eqlcol)
  3165. (goto-char org-last-recalc-line)
  3166. (org-table-goto-column
  3167. (string-to-number (substring (car entry) 1)) nil 'force)
  3168. (unless (get-text-property (point) :org-untouchable)
  3169. (org-table-eval-formula
  3170. nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
  3171. ;; Evaluate the field formulas.
  3172. (dolist (eq eqlfield)
  3173. (let ((reference (car eq))
  3174. (formula (cdr eq)))
  3175. (setq log-last-time
  3176. (org-table-message-once-per-second
  3177. (and all log-last-time)
  3178. "Re-applying formula to field: %s" (car eq)))
  3179. (org-table-goto-field
  3180. reference
  3181. ;; Possibly create a new column, as long as
  3182. ;; `org-table-formula-create-columns' allows it.
  3183. (let ((column-count (progn (end-of-line)
  3184. (1- (org-table-current-column)))))
  3185. (lambda (column)
  3186. (when (> column 1000)
  3187. (user-error "Formula column target too large"))
  3188. (and (> column column-count)
  3189. (or (eq org-table-formula-create-columns t)
  3190. (and (eq org-table-formula-create-columns 'warn)
  3191. (progn
  3192. (org-display-warning
  3193. "Out-of-bounds formula added columns")
  3194. t))
  3195. (and (eq org-table-formula-create-columns 'prompt)
  3196. (yes-or-no-p
  3197. "Out-of-bounds formula. Add columns? "))
  3198. (user-error
  3199. "Missing columns in the table. Aborting"))))))
  3200. (org-table-eval-formula nil formula t t t t))))
  3201. ;; Clean up markers and internal text property.
  3202. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  3203. (set-marker end nil)
  3204. (unless noalign
  3205. (when org-table-may-need-update (org-table-align))
  3206. (when all
  3207. (org-table-message-once-per-second
  3208. log-first-time "Re-applying formulas to %d lines... done" cnt)))
  3209. (org-table-message-once-per-second
  3210. (and all log-first-time) "Re-applying formulas... done")))))
  3211. ;;;###autoload
  3212. (defun org-table-iterate (&optional arg)
  3213. "Recalculate the table until it does not change anymore.
  3214. The maximum number of iterations is 10, but you can choose a different value
  3215. with the prefix ARG."
  3216. (interactive "P")
  3217. (let ((imax (if arg (prefix-numeric-value arg) 10))
  3218. (i 0)
  3219. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  3220. thistbl)
  3221. (catch 'exit
  3222. (while (< i imax)
  3223. (setq i (1+ i))
  3224. (org-table-recalculate 'all)
  3225. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  3226. (if (not (string= lasttbl thistbl))
  3227. (setq lasttbl thistbl)
  3228. (if (> i 1)
  3229. (message "Convergence after %d iterations" i)
  3230. (message "Table was already stable"))
  3231. (throw 'exit t)))
  3232. (user-error "No convergence after %d iterations" i))))
  3233. ;;;###autoload
  3234. (defun org-table-recalculate-buffer-tables ()
  3235. "Recalculate all tables in the current buffer."
  3236. (interactive)
  3237. (org-with-wide-buffer
  3238. (org-table-map-tables
  3239. (lambda ()
  3240. ;; Reason for separate `org-table-align': When repeating
  3241. ;; (org-table-recalculate t) `org-table-may-need-update' gets in
  3242. ;; the way.
  3243. (org-table-recalculate t t)
  3244. (org-table-align))
  3245. t)))
  3246. ;;;###autoload
  3247. (defun org-table-iterate-buffer-tables ()
  3248. "Iterate all tables in the buffer, to converge inter-table dependencies."
  3249. (interactive)
  3250. (let* ((imax 10)
  3251. (i imax)
  3252. (checksum (md5 (buffer-string)))
  3253. c1)
  3254. (org-with-wide-buffer
  3255. (catch 'exit
  3256. (while (> i 0)
  3257. (setq i (1- i))
  3258. (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
  3259. (if (equal checksum (setq c1 (md5 (buffer-string))))
  3260. (progn
  3261. (org-table-map-tables #'org-table-align t)
  3262. (message "Convergence after %d iterations" (- imax i))
  3263. (throw 'exit t))
  3264. (setq checksum c1)))
  3265. (org-table-map-tables #'org-table-align t)
  3266. (user-error "No convergence after %d iterations" imax)))))
  3267. (defun org-table-calc-current-TBLFM (&optional arg)
  3268. "Apply the #+TBLFM in the line at point to the table."
  3269. (interactive "P")
  3270. (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
  3271. (let ((formula (buffer-substring
  3272. (line-beginning-position)
  3273. (line-end-position))))
  3274. (save-excursion
  3275. ;; Insert a temporary formula at right after the table
  3276. (goto-char (org-table-TBLFM-begin))
  3277. (let ((s (point-marker)))
  3278. (insert formula "\n")
  3279. (let ((e (point-marker)))
  3280. ;; Recalculate the table.
  3281. (beginning-of-line 0) ; move to the inserted line
  3282. (skip-chars-backward " \r\n\t")
  3283. (unwind-protect
  3284. (org-call-with-arg #'org-table-recalculate (or arg t))
  3285. ;; Delete the formula inserted temporarily.
  3286. (delete-region s e)
  3287. (set-marker s nil)
  3288. (set-marker e nil)))))))
  3289. (defun org-table-TBLFM-begin ()
  3290. "Find the beginning of the TBLFM lines and return its position.
  3291. Return nil when the beginning of TBLFM line was not found."
  3292. (save-excursion
  3293. (when (progn (forward-line 1)
  3294. (re-search-backward org-table-TBLFM-begin-regexp nil t))
  3295. (line-beginning-position 2))))
  3296. (defun org-table-expand-lhs-ranges (equations)
  3297. "Expand list of formulas.
  3298. If some of the RHS in the formulas are ranges or a row reference,
  3299. expand them to individual field equations for each field. This
  3300. function assumes the table is already analyzed (i.e., using
  3301. `org-table-analyze')."
  3302. (let (res)
  3303. (dolist (e equations (nreverse res))
  3304. (let ((lhs (car e))
  3305. (rhs (cdr e)))
  3306. (cond
  3307. ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
  3308. ;; This just refers to one fixed field.
  3309. (push e res))
  3310. ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
  3311. ;; This just refers to one fixed named field.
  3312. (push e res))
  3313. ((string-match-p "\\`\\$[0-9]+\\'" lhs)
  3314. ;; Column formulas are treated specially and are not
  3315. ;; expanded.
  3316. (push e res))
  3317. ((string-match "\\`@[0-9]+\\'" lhs)
  3318. (dotimes (ic org-table-current-ncol)
  3319. (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
  3320. rhs)
  3321. res)))
  3322. (t
  3323. (let* ((range (org-table-get-range
  3324. lhs org-table-current-begin-pos 1 nil 'corners))
  3325. (r1 (org-table-line-to-dline (nth 0 range)))
  3326. (c1 (nth 1 range))
  3327. (r2 (org-table-line-to-dline (nth 2 range) 'above))
  3328. (c2 (nth 3 range)))
  3329. (cl-loop for ir from r1 to r2 do
  3330. (cl-loop for ic from c1 to c2 do
  3331. (push (cons (propertize
  3332. (format "@%d$%d" ir ic) :orig-eqn e)
  3333. rhs)
  3334. res))))))))))
  3335. (defun org-table-formula-handle-first/last-rc (s)
  3336. "Replace @<, @>, $<, $> with first/last row/column of the table.
  3337. So @< and $< will always be replaced with @1 and $1, respectively.
  3338. The advantage of these special markers are that structure editing of
  3339. the table will not change them, while @1 and $1 will be modified
  3340. when a line/row is swapped out of that privileged position. So for
  3341. formulas that use a range of rows or columns, it may often be better
  3342. to anchor the formula with \"I\" row markers, or to offset from the
  3343. borders of the table using the @< @> $< $> makers."
  3344. (let (n nmax len char (start 0))
  3345. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
  3346. s start)
  3347. (if (match-end 3)
  3348. (setq start (match-end 3))
  3349. (setq nmax (if (equal (match-string 1 s) "@")
  3350. (1- (length org-table-dlines))
  3351. org-table-current-ncol)
  3352. len (- (match-end 2) (match-beginning 2))
  3353. char (string-to-char (match-string 2 s))
  3354. n (if (= char ?<)
  3355. len
  3356. (- nmax len -1)))
  3357. (if (or (< n 1) (> n nmax))
  3358. (user-error "Reference \"%s\" in expression \"%s\" points outside table"
  3359. (match-string 0 s) s))
  3360. (setq start (match-beginning 0))
  3361. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
  3362. s)
  3363. (defun org-table-formula-substitute-names (f)
  3364. "Replace $const with values in string F."
  3365. (let ((start 0)
  3366. (pp (/= (string-to-char f) ?'))
  3367. (duration (string-match-p ";.*[Tt].*\\'" f))
  3368. (new (replace-regexp-in-string ; Check for column names.
  3369. org-table-column-name-regexp
  3370. (lambda (m)
  3371. (concat "$" (cdr (assoc (match-string 1 m)
  3372. org-table-column-names))))
  3373. f t t)))
  3374. ;; Parameters and constants.
  3375. (while (setq start
  3376. (string-match
  3377. "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
  3378. new start))
  3379. (if (match-end 2) (setq start (match-end 2))
  3380. (cl-incf start)
  3381. ;; When a duration is expected, convert value on the fly.
  3382. (let ((value
  3383. (save-match-data
  3384. (let ((v (org-table-get-constant (match-string 1 new))))
  3385. (if (and (org-string-nw-p v) duration)
  3386. (org-table-time-string-to-seconds v)
  3387. v)))))
  3388. (when value
  3389. (setq new (replace-match
  3390. (concat (and pp "(") value (and pp ")")) t t new))))))
  3391. (if org-table-formula-debug (propertize new :orig-formula f) new)))
  3392. (defun org-table-get-constant (const)
  3393. "Find the value for a parameter or constant in a formula.
  3394. Parameters get priority."
  3395. (or (cdr (assoc const org-table-local-parameters))
  3396. (cdr (assoc const org-table-formula-constants-local))
  3397. (cdr (assoc const org-table-formula-constants))
  3398. (and (fboundp 'constants-get) (constants-get const))
  3399. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  3400. (org-entry-get nil (substring const 5) 'inherit))
  3401. "#UNDEFINED_NAME"))
  3402. (defvar org-table-fedit-map
  3403. (let ((map (make-sparse-keymap)))
  3404. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  3405. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  3406. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  3407. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  3408. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  3409. (org-defkey map "\C-c?" 'org-table-show-reference)
  3410. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  3411. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  3412. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  3413. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  3414. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  3415. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  3416. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  3417. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  3418. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  3419. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  3420. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  3421. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  3422. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  3423. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  3424. map))
  3425. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
  3426. '("Edit-Formulas"
  3427. ["Finish and Install" org-table-fedit-finish t]
  3428. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  3429. ["Abort" org-table-fedit-abort t]
  3430. "--"
  3431. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  3432. ["Complete Lisp Symbol" lisp-complete-symbol t]
  3433. "--"
  3434. "Shift Reference at Point"
  3435. ["Up" org-table-fedit-ref-up t]
  3436. ["Down" org-table-fedit-ref-down t]
  3437. ["Left" org-table-fedit-ref-left t]
  3438. ["Right" org-table-fedit-ref-right t]
  3439. "-"
  3440. "Change Test Row for Column Formulas"
  3441. ["Up" org-table-fedit-line-up t]
  3442. ["Down" org-table-fedit-line-down t]
  3443. "--"
  3444. ["Scroll Table Window" org-table-fedit-scroll t]
  3445. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  3446. ["Show Table Grid" org-table-fedit-toggle-coordinates
  3447. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  3448. org-table-overlay-coordinates)]
  3449. "--"
  3450. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  3451. :style toggle :selected org-table-buffer-is-an]))
  3452. (defvar org-pos)
  3453. (defvar org-table--fedit-source nil
  3454. "Position of the TBLFM line being edited.")
  3455. ;;;###autoload
  3456. (defun org-table-edit-formulas ()
  3457. "Edit the formulas of the current table in a separate buffer."
  3458. (interactive)
  3459. (let ((at-tblfm (org-at-TBLFM-p)))
  3460. (unless (or at-tblfm (org-at-table-p))
  3461. (user-error "Not at a table"))
  3462. (save-excursion
  3463. ;; Move point within the table before analyzing it.
  3464. (when at-tblfm (re-search-backward "^[ \t]*|"))
  3465. (org-table-analyze))
  3466. (let ((key (org-table-current-field-formula 'key 'noerror))
  3467. (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
  3468. #'org-table-formula-less-p))
  3469. (pos (point-marker))
  3470. (source (copy-marker (line-beginning-position)))
  3471. (startline 1)
  3472. (wc (current-window-configuration))
  3473. (sel-win (selected-window))
  3474. (titles '((column . "# Column Formulas\n")
  3475. (field . "# Field and Range Formulas\n")
  3476. (named . "# Named Field Formulas\n"))))
  3477. (org-switch-to-buffer-other-window "*Edit Formulas*")
  3478. (erase-buffer)
  3479. ;; Keep global-font-lock-mode from turning on font-lock-mode
  3480. (let ((font-lock-global-modes '(not fundamental-mode)))
  3481. (fundamental-mode))
  3482. (setq-local font-lock-global-modes (list 'not major-mode))
  3483. (setq-local org-pos pos)
  3484. (setq-local org-table--fedit-source source)
  3485. (setq-local org-window-configuration wc)
  3486. (setq-local org-selected-window sel-win)
  3487. (use-local-map org-table-fedit-map)
  3488. (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
  3489. (easy-menu-add org-table-fedit-menu)
  3490. (setq startline (org-current-line))
  3491. (dolist (entry eql)
  3492. (let* ((type (cond
  3493. ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry))
  3494. 'column)
  3495. ((equal (string-to-char (car entry)) ?@) 'field)
  3496. (t 'named)))
  3497. (title (assq type titles)))
  3498. (when title
  3499. (unless (bobp) (insert "\n"))
  3500. (insert
  3501. (org-add-props (cdr title) nil 'face font-lock-comment-face))
  3502. (setq titles (remove title titles)))
  3503. (when (equal key (car entry)) (setq startline (org-current-line)))
  3504. (let ((s (concat
  3505. (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
  3506. (car entry) " = " (cdr entry) "\n")))
  3507. (remove-text-properties 0 (length s) '(face nil) s)
  3508. (insert s))))
  3509. (when (eq org-table-use-standard-references t)
  3510. (org-table-fedit-toggle-ref-type))
  3511. (org-goto-line startline)
  3512. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  3513. Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
  3514. See menu for more commands.")))))
  3515. (defun org-table-fedit-post-command ()
  3516. (when (not (memq this-command '(lisp-complete-symbol)))
  3517. (let ((win (selected-window)))
  3518. (save-excursion
  3519. (ignore-errors (org-table-show-reference))
  3520. (select-window win)))))
  3521. (defun org-table-formula-to-user (s)
  3522. "Convert a formula from internal to user representation."
  3523. (if (eq org-table-use-standard-references t)
  3524. (org-table-convert-refs-to-an s)
  3525. s))
  3526. (defun org-table-formula-from-user (s)
  3527. "Convert a formula from user to internal representation."
  3528. (if org-table-use-standard-references
  3529. (org-table-convert-refs-to-rc s)
  3530. s))
  3531. (defun org-table-convert-refs-to-rc (s)
  3532. "Convert spreadsheet references from A7 to @7$28.
  3533. Works for single references, but also for entire formulas and even the
  3534. full TBLFM line."
  3535. (let ((start 0))
  3536. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
  3537. (cond
  3538. ((match-end 3)
  3539. ;; format match, just advance
  3540. (setq start (match-end 0)))
  3541. ((and (> (match-beginning 0) 0)
  3542. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  3543. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  3544. ;; 3.e5 or something like this.
  3545. (setq start (match-end 0)))
  3546. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  3547. ;; (member (match-string 1 s)
  3548. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  3549. )
  3550. ;; function name, just advance
  3551. (setq start (match-end 0)))
  3552. (t
  3553. (setq start (match-beginning 0)
  3554. s (replace-match
  3555. (if (equal (match-string 2 s) "&")
  3556. (format "$%d" (org-letters-to-number (match-string 1 s)))
  3557. (format "@%d$%d"
  3558. (string-to-number (match-string 2 s))
  3559. (org-letters-to-number (match-string 1 s))))
  3560. t t s)))))
  3561. s))
  3562. (defun org-table-convert-refs-to-an (s)
  3563. "Convert spreadsheet references from to @7$28 to AB7.
  3564. Works for single references, but also for entire formulas and even the
  3565. full TBLFM line."
  3566. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  3567. (setq s (replace-match
  3568. (format "%s%d"
  3569. (org-number-to-letters
  3570. (string-to-number (match-string 2 s)))
  3571. (string-to-number (match-string 1 s)))
  3572. t t s)))
  3573. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  3574. (setq s (replace-match (concat "\\1"
  3575. (org-number-to-letters
  3576. (string-to-number (match-string 2 s))) "&")
  3577. t nil s)))
  3578. s)
  3579. (defun org-letters-to-number (s)
  3580. "Convert a base 26 number represented by letters into an integer.
  3581. For example: AB -> 28."
  3582. (let ((n 0))
  3583. (setq s (upcase s))
  3584. (while (> (length s) 0)
  3585. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3586. s (substring s 1)))
  3587. n))
  3588. (defun org-number-to-letters (n)
  3589. "Convert an integer into a base 26 number represented by letters.
  3590. For example: 28 -> AB."
  3591. (let ((s ""))
  3592. (while (> n 0)
  3593. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3594. n (/ (1- n) 26)))
  3595. s))
  3596. (defun org-table-time-string-to-seconds (s)
  3597. "Convert a time string into numerical duration in seconds.
  3598. S can be a string matching either -?HH:MM:SS or -?HH:MM.
  3599. If S is a string representing a number, keep this number."
  3600. (if (equal s "")
  3601. s
  3602. (let (hour minus min sec res)
  3603. (cond
  3604. ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3605. (setq minus (< 0 (length (match-string 1 s)))
  3606. hour (string-to-number (match-string 2 s))
  3607. min (string-to-number (match-string 3 s))
  3608. sec (string-to-number (match-string 4 s)))
  3609. (if minus
  3610. (setq res (- (+ (* hour 3600) (* min 60) sec)))
  3611. (setq res (+ (* hour 3600) (* min 60) sec))))
  3612. ((and (not (string-match org-ts-regexp-both s))
  3613. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3614. (setq minus (< 0 (length (match-string 1 s)))
  3615. hour (string-to-number (match-string 2 s))
  3616. min (string-to-number (match-string 3 s)))
  3617. (if minus
  3618. (setq res (- (+ (* hour 3600) (* min 60))))
  3619. (setq res (+ (* hour 3600) (* min 60)))))
  3620. (t (setq res (string-to-number s))))
  3621. (number-to-string res))))
  3622. (defun org-table-time-seconds-to-string (secs &optional output-format)
  3623. "Convert a number of seconds to a time string.
  3624. If OUTPUT-FORMAT is non-nil, return a number of days, hours,
  3625. minutes or seconds."
  3626. (let* ((secs0 (abs secs))
  3627. (res
  3628. (cond ((eq output-format 'days)
  3629. (format "%.3f" (/ (float secs0) 86400)))
  3630. ((eq output-format 'hours)
  3631. (format "%.2f" (/ (float secs0) 3600)))
  3632. ((eq output-format 'minutes)
  3633. (format "%.1f" (/ (float secs0) 60)))
  3634. ((eq output-format 'seconds)
  3635. (format "%d" secs0))
  3636. ((eq output-format 'hh:mm)
  3637. ;; Ignore seconds
  3638. (substring (format-seconds
  3639. (if org-table-duration-hour-zero-padding
  3640. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3641. secs0)
  3642. 0 -3))
  3643. (t (format-seconds
  3644. (if org-table-duration-hour-zero-padding
  3645. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3646. secs0)))))
  3647. (if (< secs 0) (concat "-" res) res)))
  3648. ;;; Columns shrinking
  3649. (defun org-table--shrunk-field ()
  3650. "Non-nil if current field is narrowed.
  3651. When non-nil, return the overlay narrowing the field."
  3652. (cl-some (lambda (o)
  3653. (and (eq 'table-column-hide (overlay-get o 'org-overlay-type))
  3654. o))
  3655. (overlays-at (save-excursion
  3656. (skip-chars-forward (if (org-at-table-hline-p) "^+|"
  3657. "^|")
  3658. (line-end-position))
  3659. (1- (point))))))
  3660. (defun org-table--list-shrunk-columns ()
  3661. "List currently shrunk columns in table at point."
  3662. (save-excursion
  3663. ;; We really check shrunk columns in current row only. It could
  3664. ;; be wrong if all rows do not contain the same number of columns
  3665. ;; (i.e. the table is not properly aligned). As a consequence,
  3666. ;; some columns may not be shrunk again upon aligning the table.
  3667. ;;
  3668. ;; For example, in the following table, cursor is on first row and
  3669. ;; "<>" indicates a shrunk column.
  3670. ;;
  3671. ;; | |
  3672. ;; | | <> |
  3673. ;;
  3674. ;; Aligning table from the first row will not shrink again the
  3675. ;; second row, which was not visible initially.
  3676. ;;
  3677. ;; However, fixing it requires to check every row, which may be
  3678. ;; slow on large tables. Moreover, the hindrance of this
  3679. ;; pathological case is very limited.
  3680. (beginning-of-line)
  3681. (search-forward "|")
  3682. (let ((separator (if (org-at-table-hline-p) "+" "|"))
  3683. (column 1)
  3684. (shrunk (and (org-table--shrunk-field) (list 1)))
  3685. (end (line-end-position)))
  3686. (while (search-forward separator end t)
  3687. (cl-incf column)
  3688. (when (org-table--shrunk-field) (push column shrunk)))
  3689. (nreverse shrunk))))
  3690. (defun org-table--make-shrinking-overlay (start end display field &optional pre)
  3691. "Create an overlay to shrink text between START and END.
  3692. Use string DISPLAY instead of the real text between the two
  3693. buffer positions. FIELD is the real contents of the field, as
  3694. a string, or nil. It is meant to be displayed upon moving the
  3695. mouse onto the overlay.
  3696. Return the overlay."
  3697. (let ((show-before-edit
  3698. (lambda (o &rest _)
  3699. ;; Removing one overlay removes all other overlays in the
  3700. ;; same column.
  3701. (mapc #'delete-overlay
  3702. (cdr (overlay-get o 'org-table-column-overlays)))))
  3703. (o (make-overlay start end)))
  3704. (overlay-put o 'insert-behind-hooks (and (not pre) (list show-before-edit)))
  3705. (overlay-put o 'insert-in-front-hooks (list show-before-edit))
  3706. (overlay-put o 'modification-hooks (list show-before-edit))
  3707. (overlay-put o 'org-overlay-type 'table-column-hide)
  3708. (when (stringp field) (overlay-put o 'help-echo field))
  3709. ;; Make sure overlays stays on top of table coordinates overlays.
  3710. ;; See `org-table-overlay-coordinates'.
  3711. (overlay-put o 'priority 1)
  3712. (org-overlay-display o display 'org-table t)
  3713. o))
  3714. (defun org-table--shrink-field (width start end contents)
  3715. "Shrink a table field to a specified width.
  3716. WIDTH is an integer representing the number of characters to
  3717. display, in addition to `org-table-shrunk-column-indicator'. START
  3718. and END are, respectively, the beginning and ending positions of
  3719. the field. CONTENTS is its trimmed contents, as a string, or
  3720. `hline' for table rules.
  3721. Real field is hidden under one or two overlays. They have the
  3722. following properties:
  3723. `org-overlay-type'
  3724. Set to `table-column-hide'. Used to identify overlays
  3725. responsible for shrinking columns in a table.
  3726. `org-table-column-overlays'
  3727. It is a list with the pattern (siblings . COLUMN-OVERLAYS)
  3728. where COLUMN-OVERLAYS is the list of all overlays hiding the
  3729. same column.
  3730. Whenever the text behind or next to the overlay is modified, all
  3731. the overlays in the column are deleted, effectively displaying
  3732. the column again.
  3733. Return a list of overlays hiding the field, or nil if field is
  3734. already hidden."
  3735. (cond
  3736. ((org-table--shrunk-field) nil) ;already shrunk: bail out
  3737. ((or (= 0 width) ;shrink to one character
  3738. (>= 1 (org-string-width (buffer-substring start end))))
  3739. (list (org-table--make-shrinking-overlay
  3740. start end org-table-shrunk-column-indicator
  3741. (if (eq 'hline contents) "" contents))))
  3742. ((eq contents 'hline) ;no contents to hide
  3743. (list (org-table--make-shrinking-overlay
  3744. start end
  3745. (concat (make-string (max 0 (1+ width)) ?-)
  3746. org-table-shrunk-column-indicator)
  3747. "")))
  3748. (t
  3749. ;; If the field is not empty, consider using two overlays: one for
  3750. ;; the blanks at the beginning of the field, and another one at
  3751. ;; the end of the field. The former ensures a shrunk field is
  3752. ;; always displayed with a single white space character in front
  3753. ;; of it -- e.g., so that even right-aligned fields appear to the
  3754. ;; left -- and the latter cuts the field at WIDTH visible
  3755. ;; characters.
  3756. (let* ((pre-overlay
  3757. (and (not (equal contents ""))
  3758. (org-with-point-at start (looking-at "\\( [ \t]+\\)\\S-"))
  3759. (org-table--make-shrinking-overlay
  3760. start (match-end 1) org-table-separator-space nil 'pre)))
  3761. (post-overlay
  3762. (let* ((start (if pre-overlay (overlay-end pre-overlay)
  3763. (1+ start)))
  3764. (w (org-string-width (buffer-substring start (1- end)))))
  3765. (if (>= width w)
  3766. ;; Field is too short. Extend its size by adding
  3767. ;; white space characters to the right overlay.
  3768. (org-table--make-shrinking-overlay
  3769. (1- end) end (concat (make-string (- width w) ?\s)
  3770. org-table-shrunk-column-indicator)
  3771. contents)
  3772. ;; Find cut location so that WIDTH characters are visible.
  3773. (org-table--make-shrinking-overlay
  3774. (let* ((begin start)
  3775. (lower begin)
  3776. (upper (1- end)))
  3777. (catch :exit
  3778. (while (> (- upper lower) 1)
  3779. (let ((mean (+ (ash lower -1)
  3780. (ash upper -1)
  3781. (logand lower upper 1))))
  3782. (pcase (org-string-width (buffer-substring begin mean))
  3783. ((pred (= width)) (throw :exit mean))
  3784. ((pred (< width)) (setq upper mean))
  3785. (_ (setq lower mean)))))
  3786. upper))
  3787. end org-table-shrunk-column-indicator contents)))))
  3788. (delq nil (list pre-overlay post-overlay))))))
  3789. (defun org-table--read-column-selection (select max)
  3790. "Read column selection select as a list of numbers.
  3791. SELECT is a string containing column ranges, separated by white
  3792. space characters, see `org-table-hide-column' for details. MAX
  3793. is the maximum column number.
  3794. Return value is a sorted list of numbers. Ignore any number
  3795. outside of the [1;MAX] range."
  3796. (catch :all
  3797. (sort
  3798. (delete-dups
  3799. (cl-mapcan
  3800. (lambda (s)
  3801. (cond
  3802. ((member s '("-" "1-")) (throw :all (number-sequence 1 max)))
  3803. ((string-match-p "\\`[0-9]+\\'" s)
  3804. (let ((n (string-to-number s)))
  3805. (and (> n 0) (<= n max) (list n))))
  3806. ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s)
  3807. (let ((n (match-string 1 s))
  3808. (m (match-string 2 s)))
  3809. (number-sequence (if n (max 1 (string-to-number n))
  3810. 1)
  3811. (if m (min max (string-to-number m))
  3812. max))))
  3813. (t nil))) ;invalid specification
  3814. (split-string select)))
  3815. #'<)))
  3816. (defun org-table--shrink-columns (columns beg end)
  3817. "Shrink COLUMNS in a table.
  3818. COLUMNS is a sorted list of column numbers. BEG and END are,
  3819. respectively, the beginning position and the end position of the
  3820. table."
  3821. (org-with-wide-buffer
  3822. (org-font-lock-ensure beg end)
  3823. (dolist (c columns)
  3824. (goto-char beg)
  3825. (let ((width nil)
  3826. (fields nil))
  3827. (while (< (point) end)
  3828. (catch :continue
  3829. (let* ((hline? (org-at-table-hline-p))
  3830. (separator (if hline? "+" "|")))
  3831. ;; Move to COLUMN.
  3832. (search-forward "|")
  3833. (or (= c 1) ;already there
  3834. (search-forward separator (line-end-position) t (1- c))
  3835. (throw :continue nil)) ;skip invalid columns
  3836. ;; Extract boundaries and contents from current field.
  3837. ;; Also set the column's width if we encounter a width
  3838. ;; cookie for the first time.
  3839. (let* ((start (point))
  3840. (end (progn
  3841. (skip-chars-forward (concat "^|" separator)
  3842. (line-end-position))
  3843. (point)))
  3844. (contents (if hline? 'hline
  3845. (org-trim (buffer-substring start end)))))
  3846. (push (list start end contents) fields)
  3847. (when (and (null width)
  3848. (not hline?)
  3849. (string-match "\\`<[lrc]?\\([0-9]+\\)>\\'" contents))
  3850. (setq width (string-to-number (match-string 1 contents)))))))
  3851. (forward-line))
  3852. ;; Link overlays for current field to the other overlays in the
  3853. ;; same column.
  3854. (let ((chain (list 'siblings)))
  3855. (dolist (field fields)
  3856. (dolist (new (apply #'org-table--shrink-field (or width 0) field))
  3857. (push new (cdr chain))
  3858. (overlay-put new 'org-table-column-overlays chain))))))))
  3859. ;;;###autoload
  3860. (defun org-table-toggle-column-width (&optional arg)
  3861. "Shrink or expand current column in an Org table.
  3862. If a width cookie specifies a width W for the column, the first
  3863. W visible characters are displayed. Otherwise, the column is
  3864. shrunk to a single character.
  3865. When point is before the first column or after the last one, ask
  3866. for the columns to shrink or expand, as a list of ranges.
  3867. A column range can be one of the following patterns:
  3868. N column N only
  3869. N-M every column between N and M (both inclusive)
  3870. N- every column between N (inclusive) and the last column
  3871. -M every column between the first one and M (inclusive)
  3872. - every column
  3873. When optional argument ARG is a string, use it as white space
  3874. separated list of column ranges.
  3875. When called with `\\[universal-argument]' prefix, call \
  3876. `org-table-shrink', i.e.,
  3877. shrink columns with a width cookie and expand the others.
  3878. When called with `\\[universal-argument] \\[universal-argument]' \
  3879. prefix, expand all columns."
  3880. (interactive "P")
  3881. (unless (org-at-table-p) (user-error "Not in a table"))
  3882. (let* ((begin (org-table-begin))
  3883. (end (org-table-end))
  3884. ;; Compute an upper bound for the number of columns.
  3885. ;; Nonexistent columns are ignored anyway.
  3886. (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
  3887. (shrunk (org-table--list-shrunk-columns))
  3888. (columns
  3889. (pcase arg
  3890. (`nil
  3891. (if (save-excursion
  3892. (skip-chars-backward "^|" (line-beginning-position))
  3893. (or (bolp) (looking-at-p "[ \t]*$")))
  3894. ;; Point is either before first column or past last
  3895. ;; one. Ask for columns to operate on.
  3896. (org-table--read-column-selection
  3897. (read-string "Column ranges (e.g. 2-4 6-): ")
  3898. max-columns)
  3899. (list (org-table-current-column))))
  3900. ((pred stringp) (org-table--read-column-selection arg max-columns))
  3901. ((or `(4) `(16)) nil)
  3902. (_ (user-error "Invalid argument: %S" arg)))))
  3903. (pcase arg
  3904. (`(4) (org-table-shrink begin end))
  3905. (`(16) (org-table-expand begin end))
  3906. (_
  3907. (org-table-expand begin end)
  3908. (org-table--shrink-columns
  3909. (cl-set-exclusive-or columns shrunk) begin end)))))
  3910. ;;;###autoload
  3911. (defun org-table-shrink (&optional begin end)
  3912. "Shrink all columns with a width cookie in the table at point.
  3913. Columns without a width cookie are expanded.
  3914. Optional arguments BEGIN and END, when non-nil, specify the
  3915. beginning and end position of the current table."
  3916. (interactive)
  3917. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3918. (org-with-wide-buffer
  3919. (let ((begin (or begin (org-table-begin)))
  3920. (end (or end (org-table-end)))
  3921. (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
  3922. (columns))
  3923. (goto-char begin)
  3924. (while (re-search-forward regexp end t)
  3925. (goto-char (match-beginning 1))
  3926. (cl-pushnew (org-table-current-column) columns))
  3927. (org-table-expand begin end)
  3928. ;; Make sure invisible characters in the table are at the right
  3929. ;; place since column widths take them into account.
  3930. (org-font-lock-ensure begin end)
  3931. (org-table--shrink-columns (sort columns #'<) begin end))))
  3932. ;;;###autoload
  3933. (defun org-table-expand (&optional begin end)
  3934. "Expand all columns in the table at point.
  3935. Optional arguments BEGIN and END, when non-nil, specify the
  3936. beginning and end position of the current table."
  3937. (interactive)
  3938. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3939. (org-with-wide-buffer
  3940. (let ((begin (or begin (org-table-begin)))
  3941. (end (or end (org-table-end))))
  3942. (remove-overlays begin end 'org-overlay-type 'table-column-hide))))
  3943. ;;; Formula editing
  3944. (defun org-table-fedit-convert-buffer (function)
  3945. "Convert all references in this buffer, using FUNCTION."
  3946. (let ((origin (copy-marker (line-beginning-position))))
  3947. (goto-char (point-min))
  3948. (while (not (eobp))
  3949. (insert (funcall function (buffer-substring (point) (line-end-position))))
  3950. (delete-region (point) (line-end-position))
  3951. (forward-line))
  3952. (goto-char origin)
  3953. (set-marker origin nil)))
  3954. (defun org-table-fedit-toggle-ref-type ()
  3955. "Convert all references in the buffer from B3 to @3$2 and back."
  3956. (interactive)
  3957. (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
  3958. (org-table-fedit-convert-buffer
  3959. (if org-table-buffer-is-an
  3960. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3961. (message "Reference type switched to %s"
  3962. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3963. (defun org-table-fedit-ref-up ()
  3964. "Shift the reference at point one row/hline up."
  3965. (interactive)
  3966. (org-table-fedit-shift-reference 'up))
  3967. (defun org-table-fedit-ref-down ()
  3968. "Shift the reference at point one row/hline down."
  3969. (interactive)
  3970. (org-table-fedit-shift-reference 'down))
  3971. (defun org-table-fedit-ref-left ()
  3972. "Shift the reference at point one field to the left."
  3973. (interactive)
  3974. (org-table-fedit-shift-reference 'left))
  3975. (defun org-table-fedit-ref-right ()
  3976. "Shift the reference at point one field to the right."
  3977. (interactive)
  3978. (org-table-fedit-shift-reference 'right))
  3979. (defun org-table-fedit-shift-reference (dir)
  3980. (cond
  3981. ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
  3982. (if (memq dir '(left right))
  3983. (org-rematch-and-replace 1 (eq dir 'left))
  3984. (user-error "Cannot shift reference in this direction")))
  3985. ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3986. ;; A B3-like reference
  3987. (if (memq dir '(up down))
  3988. (org-rematch-and-replace 2 (eq dir 'up))
  3989. (org-rematch-and-replace 1 (eq dir 'left))))
  3990. ((org-in-regexp
  3991. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3992. ;; An internal reference
  3993. (if (memq dir '(up down))
  3994. (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3995. (org-rematch-and-replace 5 (eq dir 'left))))))
  3996. (defun org-rematch-and-replace (n &optional decr hline)
  3997. "Re-match the group N, and replace it with the shifted reference."
  3998. (or (match-end n) (user-error "Cannot shift reference in this direction"))
  3999. (goto-char (match-beginning n))
  4000. (and (looking-at (regexp-quote (match-string n)))
  4001. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  4002. t t)))
  4003. (defun org-table-shift-refpart (ref &optional decr hline)
  4004. "Shift a reference part REF.
  4005. If DECR is set, decrease the references row/column, else increase.
  4006. If HLINE is set, this may be a hline reference, it certainly is not
  4007. a translation reference."
  4008. (save-match-data
  4009. (let* ((sign (string-match "^[-+]" ref)) n)
  4010. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  4011. (cond
  4012. ((and hline (string-match "^I+" ref))
  4013. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  4014. (setq n (+ n (if decr -1 1)))
  4015. (if (= n 0) (setq n (+ n (if decr -1 1))))
  4016. (if sign
  4017. (setq sign (if (< n 0) "-" "+") n (abs n))
  4018. (setq n (max 1 n)))
  4019. (concat sign (make-string n ?I)))
  4020. ((string-match "^[0-9]+" ref)
  4021. (setq n (string-to-number (concat sign ref)))
  4022. (setq n (+ n (if decr -1 1)))
  4023. (if sign
  4024. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  4025. (number-to-string (max 1 n))))
  4026. ((string-match "^[a-zA-Z]+" ref)
  4027. (org-number-to-letters
  4028. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  4029. (t (user-error "Cannot shift reference"))))))
  4030. (defun org-table-fedit-toggle-coordinates ()
  4031. "Toggle the display of coordinates in the referenced table."
  4032. (interactive)
  4033. (let ((pos (marker-position org-pos)))
  4034. (with-current-buffer (marker-buffer org-pos)
  4035. (save-excursion
  4036. (goto-char pos)
  4037. (org-table-toggle-coordinate-overlays)))))
  4038. (defun org-table-fedit-finish (&optional arg)
  4039. "Parse the buffer for formula definitions and install them.
  4040. With prefix ARG, apply the new formulas to the table."
  4041. (interactive "P")
  4042. (org-table-remove-rectangle-highlight)
  4043. (when org-table-use-standard-references
  4044. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  4045. (setq org-table-buffer-is-an nil))
  4046. (let ((pos org-pos)
  4047. (sel-win org-selected-window)
  4048. (source org-table--fedit-source)
  4049. eql)
  4050. (goto-char (point-min))
  4051. (while (re-search-forward
  4052. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  4053. nil t)
  4054. (let ((var (match-string 1))
  4055. (form (org-trim (match-string 3))))
  4056. (unless (equal form "")
  4057. (while (string-match "[ \t]*\n[ \t]*" form)
  4058. (setq form (replace-match " " t t form)))
  4059. (when (assoc var eql)
  4060. (user-error "Double formulas for %s" var))
  4061. (push (cons var form) eql))))
  4062. (set-window-configuration org-window-configuration)
  4063. (select-window sel-win)
  4064. (goto-char source)
  4065. (org-table-store-formulas eql)
  4066. (set-marker pos nil)
  4067. (set-marker source nil)
  4068. (kill-buffer "*Edit Formulas*")
  4069. (if arg
  4070. (org-table-recalculate 'all)
  4071. (message "New formulas installed - press C-u C-c C-c to apply."))))
  4072. (defun org-table-fedit-abort ()
  4073. "Abort editing formulas, without installing the changes."
  4074. (interactive)
  4075. (org-table-remove-rectangle-highlight)
  4076. (let ((pos org-pos) (sel-win org-selected-window))
  4077. (set-window-configuration org-window-configuration)
  4078. (select-window sel-win)
  4079. (goto-char pos)
  4080. (move-marker pos nil)
  4081. (message "Formula editing aborted without installing changes")))
  4082. (defun org-table-fedit-lisp-indent ()
  4083. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  4084. (interactive)
  4085. (let ((pos (point)) beg end ind)
  4086. (beginning-of-line 1)
  4087. (cond
  4088. ((looking-at "[ \t]")
  4089. (goto-char pos)
  4090. (call-interactively 'lisp-indent-line))
  4091. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  4092. ((not (fboundp 'pp-buffer))
  4093. (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
  4094. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  4095. (goto-char (- (match-end 0) 2))
  4096. (setq beg (point))
  4097. (setq ind (make-string (current-column) ?\ ))
  4098. (condition-case nil (forward-sexp 1)
  4099. (error
  4100. (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  4101. (setq end (point))
  4102. (save-restriction
  4103. (narrow-to-region beg end)
  4104. (if (eq last-command this-command)
  4105. (progn
  4106. (goto-char (point-min))
  4107. (setq this-command nil)
  4108. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  4109. (replace-match " ")))
  4110. (pp-buffer)
  4111. (untabify (point-min) (point-max))
  4112. (goto-char (1+ (point-min)))
  4113. (while (re-search-forward "^." nil t)
  4114. (beginning-of-line 1)
  4115. (insert ind))
  4116. (goto-char (point-max))
  4117. (org-delete-backward-char 1)))
  4118. (goto-char beg))
  4119. (t nil))))
  4120. (defvar org-show-positions nil)
  4121. (defun org-table-show-reference (&optional local)
  4122. "Show the location/value of the $ expression at point.
  4123. When LOCAL is non-nil, show references for the table at point."
  4124. (interactive)
  4125. (org-table-remove-rectangle-highlight)
  4126. (when local (org-table-analyze))
  4127. (catch 'exit
  4128. (let ((pos (if local (point) org-pos))
  4129. (face2 'highlight)
  4130. (org-inhibit-highlight-removal t)
  4131. (win (selected-window))
  4132. (org-show-positions nil)
  4133. var name e what match dest)
  4134. (setq what (cond
  4135. ((org-in-regexp "^@[0-9]+[ \t=]")
  4136. (setq match (concat (substring (match-string 0) 0 -1)
  4137. "$1.."
  4138. (substring (match-string 0) 0 -1)
  4139. "$100"))
  4140. 'range)
  4141. ((or (org-in-regexp org-table-range-regexp2)
  4142. (org-in-regexp org-table-translate-regexp)
  4143. (org-in-regexp org-table-range-regexp))
  4144. (setq match
  4145. (save-match-data
  4146. (org-table-convert-refs-to-rc (match-string 0))))
  4147. 'range)
  4148. ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  4149. ((org-in-regexp "\\$[0-9]+") 'column)
  4150. ((not local) nil)
  4151. (t (user-error "No reference at point")))
  4152. match (and what (or match (match-string 0))))
  4153. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  4154. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  4155. 'secondary-selection))
  4156. (add-hook 'before-change-functions
  4157. #'org-table-remove-rectangle-highlight)
  4158. (when (eq what 'name) (setq var (substring match 1)))
  4159. (when (eq what 'range)
  4160. (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
  4161. (setq match (org-table-formula-substitute-names match)))
  4162. (unless local
  4163. (save-excursion
  4164. (end-of-line)
  4165. (re-search-backward "^\\S-" nil t)
  4166. (beginning-of-line)
  4167. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
  4168. \\([0-9]+\\|&\\)\\) *=")
  4169. (setq dest
  4170. (save-match-data
  4171. (org-table-convert-refs-to-rc (match-string 1))))
  4172. (org-table-add-rectangle-overlay
  4173. (match-beginning 1) (match-end 1) face2))))
  4174. (if (and (markerp pos) (marker-buffer pos))
  4175. (if (get-buffer-window (marker-buffer pos))
  4176. (select-window (get-buffer-window (marker-buffer pos)))
  4177. (org-switch-to-buffer-other-window (get-buffer-window
  4178. (marker-buffer pos)))))
  4179. (goto-char pos)
  4180. (org-table-force-dataline)
  4181. (let ((table-start
  4182. (if local org-table-current-begin-pos (org-table-begin))))
  4183. (when dest
  4184. (setq name (substring dest 1))
  4185. (cond
  4186. ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  4187. (org-table-goto-field dest))
  4188. ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
  4189. dest)
  4190. (org-table-goto-field dest))
  4191. (t (org-table-goto-column (string-to-number name))))
  4192. (move-marker pos (point))
  4193. (org-table-highlight-rectangle nil nil face2))
  4194. (cond
  4195. ((equal dest match))
  4196. ((not match))
  4197. ((eq what 'range)
  4198. (ignore-errors (org-table-get-range match table-start nil 'highlight)))
  4199. ((setq e (assoc var org-table-named-field-locations))
  4200. (org-table-goto-field var)
  4201. (org-table-highlight-rectangle)
  4202. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  4203. ((setq e (assoc var org-table-column-names))
  4204. (org-table-goto-column (string-to-number (cdr e)))
  4205. (org-table-highlight-rectangle)
  4206. (goto-char table-start)
  4207. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  4208. (org-table-end) t)
  4209. (progn
  4210. (goto-char (match-beginning 1))
  4211. (org-table-highlight-rectangle)
  4212. (message "Named column (column %s)" (cdr e)))
  4213. (user-error "Column name not found")))
  4214. ((eq what 'column)
  4215. ;; Column number.
  4216. (org-table-goto-column (string-to-number (substring match 1)))
  4217. (org-table-highlight-rectangle)
  4218. (message "Column %s" (substring match 1)))
  4219. ((setq e (assoc var org-table-local-parameters))
  4220. (goto-char table-start)
  4221. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  4222. (progn
  4223. (goto-char (match-beginning 1))
  4224. (org-table-highlight-rectangle)
  4225. (message "Local parameter."))
  4226. (user-error "Parameter not found")))
  4227. ((not var) (user-error "No reference at point"))
  4228. ((setq e (assoc var org-table-formula-constants-local))
  4229. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  4230. var (cdr e)))
  4231. ((setq e (assoc var org-table-formula-constants))
  4232. (message "Constant: $%s=%s in `org-table-formula-constants'."
  4233. var (cdr e)))
  4234. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  4235. (message "Constant: $%s=%s, from `constants.el'%s."
  4236. var e (format " (%s units)" constants-unit-system)))
  4237. (t (user-error "Undefined name $%s" var)))
  4238. (goto-char pos)
  4239. (when (and org-show-positions
  4240. (not (memq this-command '(org-table-fedit-scroll
  4241. org-table-fedit-scroll-down))))
  4242. (push pos org-show-positions)
  4243. (push table-start org-show-positions)
  4244. (let ((min (apply 'min org-show-positions))
  4245. (max (apply 'max org-show-positions)))
  4246. (set-window-start (selected-window) min)
  4247. (goto-char max)
  4248. (or (pos-visible-in-window-p max)
  4249. (set-window-start (selected-window) max)))))
  4250. (select-window win))))
  4251. (defun org-table-force-dataline ()
  4252. "Move point to the closest data line in a table.
  4253. Raise an error if the table contains no data line. Preserve
  4254. column when moving point."
  4255. (unless (org-match-line org-table-dataline-regexp)
  4256. (let* ((re org-table-dataline-regexp)
  4257. (column (current-column))
  4258. (p1 (save-excursion (re-search-forward re (org-table-end) t)))
  4259. (p2 (save-excursion (re-search-backward re (org-table-begin) t))))
  4260. (cond ((and p1 p2)
  4261. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  4262. p1
  4263. p2)))
  4264. ((or p1 p2) (goto-char (or p1 p2)))
  4265. (t (user-error "No table data line around here")))
  4266. (org-move-to-column column))))
  4267. (defun org-table-fedit-line-up ()
  4268. "Move cursor one line up in the window showing the table."
  4269. (interactive)
  4270. (org-table-fedit-move 'previous-line))
  4271. (defun org-table-fedit-line-down ()
  4272. "Move cursor one line down in the window showing the table."
  4273. (interactive)
  4274. (org-table-fedit-move 'next-line))
  4275. (defun org-table-fedit-move (command)
  4276. "Move the cursor in the window showing the table.
  4277. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  4278. (let ((org-table-allow-automatic-line-recalculation nil)
  4279. (pos org-pos) (win (selected-window)) p)
  4280. (select-window (get-buffer-window (marker-buffer org-pos)))
  4281. (setq p (point))
  4282. (call-interactively command)
  4283. (while (and (org-at-table-p)
  4284. (org-at-table-hline-p))
  4285. (call-interactively command))
  4286. (or (org-at-table-p) (goto-char p))
  4287. (move-marker pos (point))
  4288. (select-window win)))
  4289. (defun org-table-fedit-scroll (N)
  4290. (interactive "p")
  4291. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  4292. (scroll-other-window N)))
  4293. (defun org-table-fedit-scroll-down (N)
  4294. (interactive "p")
  4295. (org-table-fedit-scroll (- N)))
  4296. (defvar org-table-rectangle-overlays nil)
  4297. (defun org-table-add-rectangle-overlay (beg end &optional face)
  4298. "Add a new overlay."
  4299. (let ((ov (make-overlay beg end)))
  4300. (overlay-put ov 'face (or face 'secondary-selection))
  4301. (push ov org-table-rectangle-overlays)))
  4302. (defun org-table-highlight-rectangle (&optional beg end face)
  4303. "Highlight rectangular region in a table.
  4304. When buffer positions BEG and END are provided, use them to
  4305. delimit the region to highlight. Otherwise, refer to point. Use
  4306. FACE, when non-nil, for the highlight."
  4307. (let* ((beg (or beg (point)))
  4308. (end (or end (point)))
  4309. (b (min beg end))
  4310. (e (max beg end))
  4311. (start-coordinates
  4312. (save-excursion
  4313. (goto-char b)
  4314. (cons (line-beginning-position) (org-table-current-column))))
  4315. (end-coordinates
  4316. (save-excursion
  4317. (goto-char e)
  4318. (cons (line-beginning-position) (org-table-current-column)))))
  4319. (when (boundp 'org-show-positions)
  4320. (setq org-show-positions (cons b (cons e org-show-positions))))
  4321. (goto-char (car start-coordinates))
  4322. (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
  4323. (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
  4324. (last-row (car end-coordinates)))
  4325. (while (<= (point) last-row)
  4326. (when (looking-at org-table-dataline-regexp)
  4327. (org-table-goto-column column-start)
  4328. (skip-chars-backward "^|\n")
  4329. (let ((p (point)))
  4330. (org-table-goto-column column-end)
  4331. (skip-chars-forward "^|\n")
  4332. (org-table-add-rectangle-overlay p (point) face)))
  4333. (forward-line)))
  4334. (goto-char (car start-coordinates)))
  4335. (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
  4336. (defun org-table-remove-rectangle-highlight (&rest _ignore)
  4337. "Remove the rectangle overlays."
  4338. (unless org-inhibit-highlight-removal
  4339. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  4340. (mapc 'delete-overlay org-table-rectangle-overlays)
  4341. (setq org-table-rectangle-overlays nil)))
  4342. (defvar-local org-table-coordinate-overlays nil
  4343. "Collects the coordinate grid overlays, so that they can be removed.")
  4344. (defun org-table-overlay-coordinates ()
  4345. "Add overlays to the table at point, to show row/column coordinates."
  4346. (interactive)
  4347. (mapc 'delete-overlay org-table-coordinate-overlays)
  4348. (setq org-table-coordinate-overlays nil)
  4349. (save-excursion
  4350. (let ((id 0) (ih 0) hline eol str ov)
  4351. (goto-char (org-table-begin))
  4352. (while (org-at-table-p)
  4353. (setq eol (point-at-eol))
  4354. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  4355. (push ov org-table-coordinate-overlays)
  4356. (setq hline (looking-at org-table-hline-regexp))
  4357. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  4358. (format "%4d" (setq id (1+ id)))))
  4359. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  4360. (when hline
  4361. (let ((ic 0))
  4362. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  4363. (cl-incf ic)
  4364. (let* ((beg (1+ (match-beginning 0)))
  4365. (s1 (format "$%d" ic))
  4366. (s2 (org-number-to-letters ic))
  4367. (str (if (eq t org-table-use-standard-references) s2 s1))
  4368. (ov (make-overlay beg (+ beg (length str)))))
  4369. (push ov org-table-coordinate-overlays)
  4370. (org-overlay-display ov str 'org-special-keyword 'evaporate)))))
  4371. (forward-line)))))
  4372. ;;;###autoload
  4373. (defun org-table-toggle-coordinate-overlays ()
  4374. "Toggle the display of Row/Column numbers in tables."
  4375. (interactive)
  4376. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  4377. (message "Tables Row/Column numbers display turned %s"
  4378. (if org-table-overlay-coordinates "on" "off"))
  4379. (when (and (org-at-table-p) org-table-overlay-coordinates)
  4380. (org-table-align))
  4381. (unless org-table-overlay-coordinates
  4382. (mapc 'delete-overlay org-table-coordinate-overlays)
  4383. (setq org-table-coordinate-overlays nil)))
  4384. ;;;###autoload
  4385. (defun org-table-toggle-formula-debugger ()
  4386. "Toggle the formula debugger in tables."
  4387. (interactive)
  4388. (setq org-table-formula-debug (not org-table-formula-debug))
  4389. (message "Formula debugging has been turned %s"
  4390. (if org-table-formula-debug "on" "off")))
  4391. ;;; The orgtbl minor mode
  4392. ;; Define a minor mode which can be used in other modes in order to
  4393. ;; integrate the Org table editor.
  4394. ;; This is really a hack, because the Org table editor uses several
  4395. ;; keys which normally belong to the major mode, for example the TAB
  4396. ;; and RET keys. Here is how it works: The minor mode defines all the
  4397. ;; keys necessary to operate the table editor, but wraps the commands
  4398. ;; into a function which tests if the cursor is currently inside
  4399. ;; a table. If that is the case, the table editor command is
  4400. ;; executed. However, when any of those keys is used outside a table,
  4401. ;; the function uses `key-binding' to look up if the key has an
  4402. ;; associated command in another currently active keymap (minor modes,
  4403. ;; major mode, global), and executes that command. There might be
  4404. ;; problems if any of the keys used by the table editor is otherwise
  4405. ;; used as a prefix key.
  4406. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  4407. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  4408. ;; addresses this by checking explicitly for both bindings.
  4409. ;; The optimized version (see variable `orgtbl-optimized') takes over
  4410. ;; all keys which are bound to `self-insert-command' in the *global map*.
  4411. ;; Some modes bind other commands to simple characters, for example
  4412. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  4413. ;; active, this binding is ignored inside tables and replaced with a
  4414. ;; modified self-insert.
  4415. (defvar orgtbl-mode-map (make-keymap)
  4416. "Keymap for `orgtbl-mode'.")
  4417. (defvar org-old-auto-fill-inhibit-regexp nil
  4418. "Local variable used by `orgtbl-mode'.")
  4419. (defconst orgtbl-line-start-regexp
  4420. "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
  4421. "Matches a line belonging to an orgtbl.")
  4422. (defconst orgtbl-extra-font-lock-keywords
  4423. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  4424. 0 (quote 'org-table) 'prepend))
  4425. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  4426. ;; Install it as a minor mode.
  4427. (put 'orgtbl-mode :included t)
  4428. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  4429. ;;;###autoload
  4430. (define-minor-mode orgtbl-mode
  4431. "The Org mode table editor as a minor mode for use in other modes."
  4432. :lighter " OrgTbl" :keymap orgtbl-mode-map
  4433. (org-load-modules-maybe)
  4434. (cond
  4435. ((derived-mode-p 'org-mode)
  4436. ;; Exit without error, in case some hook functions calls this by
  4437. ;; accident in Org mode.
  4438. (message "Orgtbl mode is not useful in Org mode, command ignored"))
  4439. (orgtbl-mode
  4440. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  4441. ;; Make sure we are first in minor-mode-map-alist
  4442. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  4443. ;; FIXME: maybe it should use emulation-mode-map-alists?
  4444. (and c (setq minor-mode-map-alist
  4445. (cons c (delq c minor-mode-map-alist)))))
  4446. (setq-local org-table-may-need-update t)
  4447. (add-hook 'before-change-functions 'org-before-change-function
  4448. nil 'local)
  4449. (setq-local org-old-auto-fill-inhibit-regexp
  4450. auto-fill-inhibit-regexp)
  4451. (setq-local auto-fill-inhibit-regexp
  4452. (if auto-fill-inhibit-regexp
  4453. (concat orgtbl-line-start-regexp "\\|"
  4454. auto-fill-inhibit-regexp)
  4455. orgtbl-line-start-regexp))
  4456. (when (fboundp 'font-lock-add-keywords)
  4457. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  4458. (org-restart-font-lock))
  4459. (easy-menu-add orgtbl-mode-menu))
  4460. (t
  4461. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  4462. (remove-hook 'before-change-functions 'org-before-change-function t)
  4463. (when (fboundp 'font-lock-remove-keywords)
  4464. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  4465. (org-restart-font-lock))
  4466. (easy-menu-remove orgtbl-mode-menu)
  4467. (force-mode-line-update 'all))))
  4468. (defun orgtbl-make-binding (fun n &rest keys)
  4469. "Create a function for binding in the table minor mode.
  4470. FUN is the command to call inside a table. N is used to create a unique
  4471. command name. KEYS are keys that should be checked in for a command
  4472. to execute outside of tables."
  4473. (eval
  4474. (list 'defun
  4475. (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
  4476. '(arg)
  4477. (concat "In tables, run `" (symbol-name fun) "'.\n"
  4478. "Outside of tables, run the binding of `"
  4479. (mapconcat #'key-description keys "' or `")
  4480. "'.")
  4481. '(interactive "p")
  4482. (list 'if
  4483. '(org-at-table-p)
  4484. (list 'call-interactively (list 'quote fun))
  4485. (list 'let '(orgtbl-mode)
  4486. (list 'call-interactively
  4487. (append '(or)
  4488. (mapcar (lambda (k)
  4489. (list 'key-binding k))
  4490. keys)
  4491. '('orgtbl-error))))))))
  4492. (defun orgtbl-error ()
  4493. "Error when there is no default binding for a table key."
  4494. (interactive)
  4495. (user-error "This key has no function outside tables"))
  4496. (defun orgtbl-setup ()
  4497. "Setup orgtbl keymaps."
  4498. (let ((nfunc 0)
  4499. (bindings
  4500. '(([(meta shift left)] org-table-delete-column)
  4501. ([(meta left)] org-table-move-column-left)
  4502. ([(meta right)] org-table-move-column-right)
  4503. ([(meta shift right)] org-table-insert-column)
  4504. ([(meta shift up)] org-table-kill-row)
  4505. ([(meta shift down)] org-table-insert-row)
  4506. ([(meta up)] org-table-move-row-up)
  4507. ([(meta down)] org-table-move-row-down)
  4508. ("\C-c\C-w" org-table-cut-region)
  4509. ("\C-c\M-w" org-table-copy-region)
  4510. ("\C-c\C-y" org-table-paste-rectangle)
  4511. ("\C-c\C-w" org-table-wrap-region)
  4512. ("\C-c-" org-table-insert-hline)
  4513. ("\C-c}" org-table-toggle-coordinate-overlays)
  4514. ("\C-c{" org-table-toggle-formula-debugger)
  4515. ("\C-m" org-table-next-row)
  4516. ([(shift return)] org-table-copy-down)
  4517. ("\C-c?" org-table-field-info)
  4518. ("\C-c " org-table-blank-field)
  4519. ("\C-c+" org-table-sum)
  4520. ("\C-c=" org-table-eval-formula)
  4521. ("\C-c'" org-table-edit-formulas)
  4522. ("\C-c`" org-table-edit-field)
  4523. ("\C-c*" org-table-recalculate)
  4524. ("\C-c^" org-table-sort-lines)
  4525. ("\M-a" org-table-beginning-of-field)
  4526. ("\M-e" org-table-end-of-field)
  4527. ([(control ?#)] org-table-rotate-recalc-marks)))
  4528. elt key fun cmd)
  4529. (while (setq elt (pop bindings))
  4530. (setq nfunc (1+ nfunc))
  4531. (setq key (org-key (car elt))
  4532. fun (nth 1 elt)
  4533. cmd (orgtbl-make-binding fun nfunc key))
  4534. (org-defkey orgtbl-mode-map key cmd))
  4535. ;; Special treatment needed for TAB, RET and DEL
  4536. (org-defkey orgtbl-mode-map [(return)]
  4537. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  4538. (org-defkey orgtbl-mode-map "\C-m"
  4539. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  4540. (org-defkey orgtbl-mode-map [(tab)]
  4541. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  4542. (org-defkey orgtbl-mode-map "\C-i"
  4543. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  4544. (org-defkey orgtbl-mode-map [(shift tab)]
  4545. (orgtbl-make-binding 'org-table-previous-field 104
  4546. [(shift tab)] [(tab)] "\C-i"))
  4547. (org-defkey orgtbl-mode-map [backspace]
  4548. (orgtbl-make-binding 'org-delete-backward-char 109
  4549. [backspace] (kbd "DEL")))
  4550. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  4551. (orgtbl-make-binding 'org-table-previous-field 107
  4552. [S-iso-lefttab] [backtab] [(shift tab)]
  4553. [(tab)] "\C-i"))
  4554. (org-defkey orgtbl-mode-map [backtab]
  4555. (orgtbl-make-binding 'org-table-previous-field 108
  4556. [backtab] [S-iso-lefttab] [(shift tab)]
  4557. [(tab)] "\C-i"))
  4558. (org-defkey orgtbl-mode-map "\M-\C-m"
  4559. (orgtbl-make-binding 'org-table-wrap-region 105
  4560. "\M-\C-m" [(meta return)]))
  4561. (org-defkey orgtbl-mode-map [(meta return)]
  4562. (orgtbl-make-binding 'org-table-wrap-region 106
  4563. [(meta return)] "\M-\C-m"))
  4564. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  4565. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  4566. (when orgtbl-optimized
  4567. ;; If the user wants maximum table support, we need to hijack
  4568. ;; some standard editing functions
  4569. (org-remap orgtbl-mode-map
  4570. 'self-insert-command 'orgtbl-self-insert-command
  4571. 'delete-char 'org-delete-char
  4572. 'delete-backward-char 'org-delete-backward-char)
  4573. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  4574. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
  4575. '("OrgTbl"
  4576. ["Create or convert" org-table-create-or-convert-from-region
  4577. :active (not (org-at-table-p)) :keys "C-c |" ]
  4578. "--"
  4579. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  4580. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  4581. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  4582. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  4583. "--"
  4584. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  4585. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  4586. ["Copy Field from Above"
  4587. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  4588. "--"
  4589. ("Column"
  4590. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  4591. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  4592. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  4593. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  4594. ("Row"
  4595. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  4596. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  4597. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  4598. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  4599. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  4600. "--"
  4601. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  4602. ("Rectangle"
  4603. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  4604. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  4605. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  4606. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  4607. "--"
  4608. ("Radio tables"
  4609. ["Insert table template" orgtbl-insert-radio-table
  4610. (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
  4611. ["Comment/uncomment table" orgtbl-toggle-comment t])
  4612. "--"
  4613. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  4614. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  4615. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  4616. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  4617. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  4618. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  4619. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  4620. ["Sum Column/Rectangle" org-table-sum
  4621. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  4622. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  4623. ["Debug Formulas"
  4624. org-table-toggle-formula-debugger :active (org-at-table-p)
  4625. :keys "C-c {"
  4626. :style toggle :selected org-table-formula-debug]
  4627. ["Show Col/Row Numbers"
  4628. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  4629. :keys "C-c }"
  4630. :style toggle :selected org-table-overlay-coordinates]
  4631. "--"
  4632. ("Plot"
  4633. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4634. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4635. t))
  4636. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4637. "If the cursor is inside a table, realign the table.
  4638. If it is a table to be sent away to a receiver, do it.
  4639. With prefix arg, also recompute table."
  4640. (interactive "P")
  4641. (let ((case-fold-search t) (pos (point)) action)
  4642. (save-excursion
  4643. (beginning-of-line 1)
  4644. (setq action (cond
  4645. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4646. ((looking-at "[ \t]*|") pos)
  4647. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4648. (cond
  4649. ((integerp action)
  4650. (goto-char action)
  4651. (org-table-maybe-eval-formula)
  4652. (if arg
  4653. (call-interactively 'org-table-recalculate)
  4654. (org-table-maybe-recalculate-line))
  4655. (call-interactively 'org-table-align)
  4656. (when (orgtbl-send-table 'maybe)
  4657. (run-hooks 'orgtbl-after-send-table-hook)))
  4658. ((eq action 'recalc)
  4659. (save-excursion
  4660. (beginning-of-line 1)
  4661. (skip-chars-backward " \r\n\t")
  4662. (if (org-at-table-p)
  4663. (org-call-with-arg 'org-table-recalculate t))))
  4664. (t (let (orgtbl-mode)
  4665. (call-interactively (key-binding "\C-c\C-c")))))))
  4666. (defun orgtbl-create-or-convert-from-region (_arg)
  4667. "Create table or convert region to table, if no conflicting binding.
  4668. This installs the table binding `C-c |', but only if there is no
  4669. conflicting binding to this key outside orgtbl-mode."
  4670. (interactive "P")
  4671. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4672. (if cmd
  4673. (call-interactively cmd)
  4674. (call-interactively 'org-table-create-or-convert-from-region))))
  4675. (defun orgtbl-tab (arg)
  4676. "Justification and field motion for `orgtbl-mode'."
  4677. (interactive "P")
  4678. (if arg (org-table-edit-field t)
  4679. (org-table-justify-field-maybe)
  4680. (org-table-next-field)))
  4681. (defun orgtbl-ret ()
  4682. "Justification and field motion for `orgtbl-mode'."
  4683. (interactive)
  4684. (if (bobp)
  4685. (newline)
  4686. (org-table-justify-field-maybe)
  4687. (org-table-next-row)))
  4688. (defun orgtbl-self-insert-command (N)
  4689. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4690. If the cursor is in a table looking at whitespace, the whitespace is
  4691. overwritten, and the table is not marked as requiring realignment."
  4692. (interactive "p")
  4693. (if (and (org-at-table-p)
  4694. (or
  4695. (and org-table-auto-blank-field
  4696. (member last-command
  4697. '(orgtbl-hijacker-command-100
  4698. orgtbl-hijacker-command-101
  4699. orgtbl-hijacker-command-102
  4700. orgtbl-hijacker-command-103
  4701. orgtbl-hijacker-command-104
  4702. orgtbl-hijacker-command-105
  4703. yas/expand))
  4704. (org-table-blank-field))
  4705. t)
  4706. (eq N 1)
  4707. (looking-at "[^|\n]* \\( \\)|"))
  4708. (let (org-table-may-need-update)
  4709. (delete-region (match-beginning 1) (match-end 1))
  4710. (self-insert-command N))
  4711. (setq org-table-may-need-update t)
  4712. (let* (orgtbl-mode
  4713. a
  4714. (cmd (or (key-binding
  4715. (or (and (listp function-key-map)
  4716. (setq a (assoc last-input-event function-key-map))
  4717. (cdr a))
  4718. (vector last-input-event)))
  4719. 'self-insert-command)))
  4720. (call-interactively cmd)
  4721. (if (and org-self-insert-cluster-for-undo
  4722. (eq cmd 'self-insert-command))
  4723. (if (not (eq last-command 'orgtbl-self-insert-command))
  4724. (setq org-self-insert-command-undo-counter 1)
  4725. (if (>= org-self-insert-command-undo-counter 20)
  4726. (setq org-self-insert-command-undo-counter 1)
  4727. (and (> org-self-insert-command-undo-counter 0)
  4728. buffer-undo-list
  4729. (not (cadr buffer-undo-list)) ; remove nil entry
  4730. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  4731. (setq org-self-insert-command-undo-counter
  4732. (1+ org-self-insert-command-undo-counter))))))))
  4733. ;;;###autoload
  4734. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  4735. "Regular expression matching exponentials as produced by calc.")
  4736. (defun orgtbl-gather-send-defs ()
  4737. "Gather a plist of :name, :transform, :params for each destination before
  4738. a radio table."
  4739. (save-excursion
  4740. (goto-char (org-table-begin))
  4741. (let (rtn)
  4742. (beginning-of-line 0)
  4743. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  4744. (let ((name (org-no-properties (match-string 1)))
  4745. (transform (intern (match-string 2)))
  4746. (params (if (match-end 3)
  4747. (read (concat "(" (match-string 3) ")")))))
  4748. (push (list :name name :transform transform :params params)
  4749. rtn)
  4750. (beginning-of-line 0)))
  4751. rtn)))
  4752. (defun orgtbl-send-replace-tbl (name text)
  4753. "Find and replace table NAME with TEXT."
  4754. (save-excursion
  4755. (goto-char (point-min))
  4756. (let* ((location-flag nil)
  4757. (name (regexp-quote name))
  4758. (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
  4759. (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
  4760. (while (re-search-forward begin-re nil t)
  4761. (unless location-flag (setq location-flag t))
  4762. (let ((beg (line-beginning-position 2)))
  4763. (unless (re-search-forward end-re nil t)
  4764. (user-error "Cannot find end of receiver location at %d" beg))
  4765. (beginning-of-line)
  4766. (delete-region beg (point))
  4767. (insert text "\n")))
  4768. (unless location-flag
  4769. (user-error "No valid receiver location found in the buffer")))))
  4770. ;;;###autoload
  4771. (defun org-table-to-lisp (&optional txt)
  4772. "Convert the table at point to a Lisp structure.
  4773. The structure will be a list. Each item is either the symbol `hline'
  4774. for a horizontal separator line, or a list of field values as strings.
  4775. The table is taken from the parameter TXT, or from the buffer at point."
  4776. (unless (or txt (org-at-table-p)) (user-error "No table at point"))
  4777. (let ((txt (or txt
  4778. (buffer-substring-no-properties (org-table-begin)
  4779. (org-table-end)))))
  4780. (mapcar (lambda (x)
  4781. (if (string-match org-table-hline-regexp x) 'hline
  4782. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  4783. (org-split-string txt "[ \t]*\n[ \t]*"))))
  4784. (defun orgtbl-send-table (&optional maybe)
  4785. "Send a transformed version of table at point to the receiver position.
  4786. With argument MAYBE, fail quietly if no transformation is defined
  4787. for this table."
  4788. (interactive)
  4789. (catch 'exit
  4790. (unless (org-at-table-p) (user-error "Not at a table"))
  4791. ;; when non-interactive, we assume align has just happened.
  4792. (when (called-interactively-p 'any) (org-table-align))
  4793. (let ((dests (orgtbl-gather-send-defs))
  4794. (table (org-table-to-lisp
  4795. (buffer-substring-no-properties (org-table-begin)
  4796. (org-table-end))))
  4797. (ntbl 0))
  4798. (unless dests
  4799. (if maybe (throw 'exit nil)
  4800. (user-error "Don't know how to transform this table")))
  4801. (dolist (dest dests)
  4802. (let ((name (plist-get dest :name))
  4803. (transform (plist-get dest :transform))
  4804. (params (plist-get dest :params)))
  4805. (unless (fboundp transform)
  4806. (user-error "No such transformation function %s" transform))
  4807. (orgtbl-send-replace-tbl name (funcall transform table params)))
  4808. (cl-incf ntbl))
  4809. (message "Table converted and installed at %d receiver location%s"
  4810. ntbl (if (> ntbl 1) "s" ""))
  4811. (and (> ntbl 0) ntbl))))
  4812. (defun org-remove-by-index (list indices &optional i0)
  4813. "Remove the elements in LIST with indices in INDICES.
  4814. First element has index 0, or I0 if given."
  4815. (if (not indices)
  4816. list
  4817. (if (integerp indices) (setq indices (list indices)))
  4818. (setq i0 (1- (or i0 0)))
  4819. (delq :rm (mapcar (lambda (x)
  4820. (setq i0 (1+ i0))
  4821. (if (memq i0 indices) :rm x))
  4822. list))))
  4823. (defun orgtbl-toggle-comment ()
  4824. "Comment or uncomment the orgtbl at point."
  4825. (interactive)
  4826. (let* ((case-fold-search t)
  4827. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  4828. (re2 (concat "^" orgtbl-line-start-regexp))
  4829. (commented (save-excursion (beginning-of-line 1)
  4830. (cond ((looking-at re1) t)
  4831. ((looking-at re2) nil)
  4832. (t (user-error "Not at an org table")))))
  4833. (re (if commented re1 re2))
  4834. beg end)
  4835. (save-excursion
  4836. (beginning-of-line 1)
  4837. (while (looking-at re) (beginning-of-line 0))
  4838. (beginning-of-line 2)
  4839. (setq beg (point))
  4840. (while (looking-at re) (beginning-of-line 2))
  4841. (setq end (point)))
  4842. (comment-region beg end (if commented '(4) nil))))
  4843. (defun orgtbl-insert-radio-table ()
  4844. "Insert a radio table template appropriate for this major mode."
  4845. (interactive)
  4846. (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
  4847. (txt (nth 1 e))
  4848. name pos)
  4849. (unless e (user-error "No radio table setup defined for %s" major-mode))
  4850. (setq name (read-string "Table name: "))
  4851. (while (string-match "%n" txt)
  4852. (setq txt (replace-match name t t txt)))
  4853. (or (bolp) (insert "\n"))
  4854. (setq pos (point))
  4855. (insert txt)
  4856. (goto-char pos)))
  4857. ;;;###autoload
  4858. (defun orgtbl-to-generic (table params)
  4859. "Convert the orgtbl-mode TABLE to some other format.
  4860. This generic routine can be used for many standard cases.
  4861. TABLE is a list, each entry either the symbol `hline' for
  4862. a horizontal separator line, or a list of fields for that
  4863. line. PARAMS is a property list of parameters that can
  4864. influence the conversion.
  4865. Valid parameters are:
  4866. :backend, :raw
  4867. Export back-end used as a basis to transcode elements of the
  4868. table, when no specific parameter applies to it. It is also
  4869. used to translate cells contents. You can prevent this by
  4870. setting :raw property to a non-nil value.
  4871. :splice
  4872. When non-nil, only convert rows, not the table itself. This is
  4873. equivalent to setting to the empty string both :tstart
  4874. and :tend, which see.
  4875. :skip
  4876. When set to an integer N, skip the first N lines of the table.
  4877. Horizontal separation lines do count for this parameter!
  4878. :skipcols
  4879. List of columns that should be skipped. If the table has
  4880. a column with calculation marks, that column is automatically
  4881. discarded beforehand.
  4882. :hline
  4883. String to be inserted on horizontal separation lines. May be
  4884. nil to ignore these lines altogether.
  4885. :sep
  4886. Separator between two fields, as a string.
  4887. Each in the following group may be either a string or a function
  4888. of no arguments returning a string:
  4889. :tstart, :tend
  4890. Strings to start and end the table. Ignored when :splice is t.
  4891. :lstart, :lend
  4892. Strings to start and end a new table line.
  4893. :llstart, :llend
  4894. Strings to start and end the last table line. Default,
  4895. respectively, to :lstart and :lend.
  4896. Each in the following group may be a string or a function of one
  4897. argument (either the cells in the current row, as a list of
  4898. strings, or the current cell) returning a string:
  4899. :lfmt
  4900. Format string for an entire row, with enough %s to capture all
  4901. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  4902. :llfmt
  4903. Format for the entire last line, defaults to :lfmt.
  4904. :fmt
  4905. A format to be used to wrap the field, should contain %s for
  4906. the original field value. For example, to wrap everything in
  4907. dollars, you could use :fmt \"$%s$\". This may also be
  4908. a property list with column numbers and format strings, or
  4909. functions, e.g.,
  4910. (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  4911. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  4912. Same as above, specific for the header lines in the table.
  4913. All lines before the first hline are treated as header. If
  4914. any of these is not present, the data line value is used.
  4915. This may be either a string or a function of two arguments:
  4916. :efmt
  4917. Use this format to print numbers with exponential. The format
  4918. should have %s twice for inserting mantissa and exponent, for
  4919. example \"%s\\\\times10^{%s}\". This may also be a property
  4920. list with column numbers and format strings or functions.
  4921. :fmt will still be applied after :efmt."
  4922. ;; Make sure `org-export-create-backend' is available.
  4923. (require 'ox)
  4924. (let* ((backend (plist-get params :backend))
  4925. (custom-backend
  4926. ;; Build a custom back-end according to PARAMS. Before
  4927. ;; defining a translator, check if there is anything to do.
  4928. ;; When there isn't, let BACKEND handle the element.
  4929. (org-export-create-backend
  4930. :parent (or backend 'org)
  4931. :transcoders
  4932. `((table . ,(org-table--to-generic-table params))
  4933. (table-row . ,(org-table--to-generic-row params))
  4934. (table-cell . ,(org-table--to-generic-cell params))
  4935. ;; Macros are not going to be expanded. However, no
  4936. ;; regular back-end has a transcoder for them. We
  4937. ;; provide one so they are not ignored, but displayed
  4938. ;; as-is instead.
  4939. (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
  4940. data info)
  4941. ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
  4942. ;; Initialize communication channel in INFO.
  4943. (with-temp-buffer
  4944. (let ((org-inhibit-startup t)) (org-mode))
  4945. (let ((standard-output (current-buffer))
  4946. (org-element-use-cache nil))
  4947. (dolist (e table)
  4948. (cond ((eq e 'hline) (princ "|--\n"))
  4949. ((consp e)
  4950. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  4951. (princ "\n")))))
  4952. ;; Add back-end specific filters, but not user-defined ones. In
  4953. ;; particular, make sure to call parse-tree filters on the
  4954. ;; table.
  4955. (setq info
  4956. (let ((org-export-filters-alist nil))
  4957. (org-export-install-filters
  4958. (org-combine-plists
  4959. (org-export-get-environment backend nil params)
  4960. `(:back-end ,(org-export-get-backend backend))))))
  4961. (setq data
  4962. (org-export-filter-apply-functions
  4963. (plist-get info :filter-parse-tree)
  4964. (org-element-map (org-element-parse-buffer) 'table
  4965. #'identity nil t)
  4966. info)))
  4967. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  4968. (user-error "Unknown :backend value"))
  4969. (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
  4970. ;; Handle :skip parameter.
  4971. (let ((skip (plist-get info :skip)))
  4972. (when skip
  4973. (unless (wholenump skip) (user-error "Wrong :skip value"))
  4974. (let ((n 0))
  4975. (org-element-map data 'table-row
  4976. (lambda (row)
  4977. (if (>= n skip) t
  4978. (org-element-extract-element row)
  4979. (cl-incf n)
  4980. nil))
  4981. nil t))))
  4982. ;; Handle :skipcols parameter.
  4983. (let ((skipcols (plist-get info :skipcols)))
  4984. (when skipcols
  4985. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  4986. (org-element-map data 'table
  4987. (lambda (table)
  4988. (let ((specialp (org-export-table-has-special-column-p table)))
  4989. (dolist (row (org-element-contents table))
  4990. (when (eq (org-element-property :type row) 'standard)
  4991. (let ((c 1))
  4992. (dolist (cell (nthcdr (if specialp 1 0)
  4993. (org-element-contents row)))
  4994. (when (memq c skipcols)
  4995. (org-element-extract-element cell))
  4996. (cl-incf c))))))))))
  4997. ;; Since we are going to export using a low-level mechanism,
  4998. ;; ignore special column and special rows manually.
  4999. (let ((special? (org-export-table-has-special-column-p data))
  5000. ignore)
  5001. (org-element-map data (if special? '(table-cell table-row) 'table-row)
  5002. (lambda (datum)
  5003. (when (if (eq (org-element-type datum) 'table-row)
  5004. (org-export-table-row-is-special-p datum nil)
  5005. (org-export-first-sibling-p datum nil))
  5006. (push datum ignore))))
  5007. (setq info (plist-put info :ignore-list ignore)))
  5008. ;; We use a low-level mechanism to export DATA so as to skip all
  5009. ;; usual pre-processing and post-processing, i.e., hooks, Babel
  5010. ;; code evaluation, include keywords and macro expansion. Only
  5011. ;; back-end specific filters are retained.
  5012. (let ((output (org-export-data-with-backend data custom-backend info)))
  5013. ;; Remove final newline.
  5014. (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
  5015. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  5016. (cond ((null value) nil)
  5017. ((functionp value) `(funcall ',value ,@args))
  5018. ((stringp value)
  5019. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  5020. (args `(format ,value ,@args))
  5021. (t value)))
  5022. ((and with-cons (consp value))
  5023. `(let ((val (cadr (memq column ',value))))
  5024. (cond ((null val) contents)
  5025. ((stringp val) (format val ,@args))
  5026. ((functionp val) (funcall val ,@args))
  5027. (t (user-error "Wrong %s value" ,name)))))
  5028. (t (user-error "Wrong %s value" name))))
  5029. (defun org-table--to-generic-table (params)
  5030. "Return custom table transcoder according to PARAMS.
  5031. PARAMS is a plist. See `orgtbl-to-generic' for more
  5032. information."
  5033. (let ((backend (plist-get params :backend))
  5034. (splice (plist-get params :splice))
  5035. (tstart (plist-get params :tstart))
  5036. (tend (plist-get params :tend)))
  5037. `(lambda (table contents info)
  5038. (concat
  5039. ,(and tstart (not splice)
  5040. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  5041. ,(if (or (not backend) tstart tend splice) 'contents
  5042. `(org-export-with-backend ',backend table contents info))
  5043. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  5044. (defun org-table--to-generic-row (params)
  5045. "Return custom table row transcoder according to PARAMS.
  5046. PARAMS is a plist. See `orgtbl-to-generic' for more
  5047. information."
  5048. (let* ((backend (plist-get params :backend))
  5049. (lstart (plist-get params :lstart))
  5050. (llstart (plist-get params :llstart))
  5051. (hlstart (plist-get params :hlstart))
  5052. (hllstart (plist-get params :hllstart))
  5053. (lend (plist-get params :lend))
  5054. (llend (plist-get params :llend))
  5055. (hlend (plist-get params :hlend))
  5056. (hllend (plist-get params :hllend))
  5057. (lfmt (plist-get params :lfmt))
  5058. (llfmt (plist-get params :llfmt))
  5059. (hlfmt (plist-get params :hlfmt))
  5060. (hllfmt (plist-get params :hllfmt)))
  5061. `(lambda (row contents info)
  5062. (if (eq (org-element-property :type row) 'rule)
  5063. ,(cond
  5064. ((plist-member params :hline)
  5065. (org-table--generic-apply (plist-get params :hline) ":hline"))
  5066. (backend `(org-export-with-backend ',backend row nil info)))
  5067. (let ((headerp ,(and (or hlfmt hlstart hlend)
  5068. '(org-export-table-row-in-header-p row info)))
  5069. (last-header-p
  5070. ,(and (or hllfmt hllstart hllend)
  5071. '(org-export-table-row-ends-header-p row info)))
  5072. (lastp (not (org-export-get-next-element row info))))
  5073. (when contents
  5074. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  5075. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  5076. ;; `:lstart', `:lend' and their relatives.
  5077. ,(let ((cells
  5078. '(org-element-map row 'table-cell
  5079. (lambda (cell)
  5080. ;; Export all cells, without separators.
  5081. ;;
  5082. ;; Use `org-export-data-with-backend'
  5083. ;; instead of `org-export-data' to eschew
  5084. ;; cached values, which
  5085. ;; ignore :orgtbl-ignore-sep parameter.
  5086. (org-export-data-with-backend
  5087. cell
  5088. (plist-get info :back-end)
  5089. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  5090. info)))
  5091. `(cond
  5092. ,(and hllfmt
  5093. `(last-header-p ,(org-table--generic-apply
  5094. hllfmt ":hllfmt" nil cells)))
  5095. ,(and hlfmt
  5096. `(headerp ,(org-table--generic-apply
  5097. hlfmt ":hlfmt" nil cells)))
  5098. ,(and llfmt
  5099. `(lastp ,(org-table--generic-apply
  5100. llfmt ":llfmt" nil cells)))
  5101. (t
  5102. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  5103. `(concat
  5104. (cond
  5105. ,(and
  5106. (or hllstart hllend)
  5107. `(last-header-p
  5108. (concat
  5109. ,(org-table--generic-apply hllstart ":hllstart")
  5110. contents
  5111. ,(org-table--generic-apply hllend ":hllend"))))
  5112. ,(and
  5113. (or hlstart hlend)
  5114. `(headerp
  5115. (concat
  5116. ,(org-table--generic-apply hlstart ":hlstart")
  5117. contents
  5118. ,(org-table--generic-apply hlend ":hlend"))))
  5119. ,(and
  5120. (or llstart llend)
  5121. `(lastp
  5122. (concat
  5123. ,(org-table--generic-apply llstart ":llstart")
  5124. contents
  5125. ,(org-table--generic-apply llend ":llend"))))
  5126. (t
  5127. ,(cond
  5128. ((or lstart lend)
  5129. `(concat
  5130. ,(org-table--generic-apply lstart ":lstart")
  5131. contents
  5132. ,(org-table--generic-apply lend ":lend")))
  5133. (backend
  5134. `(org-export-with-backend
  5135. ',backend row contents info))
  5136. (t 'contents)))))))))))))))
  5137. (defun org-table--to-generic-cell (params)
  5138. "Return custom table cell transcoder according to PARAMS.
  5139. PARAMS is a plist. See `orgtbl-to-generic' for more
  5140. information."
  5141. (let* ((backend (plist-get params :backend))
  5142. (efmt (plist-get params :efmt))
  5143. (fmt (plist-get params :fmt))
  5144. (hfmt (plist-get params :hfmt))
  5145. (sep (plist-get params :sep))
  5146. (hsep (plist-get params :hsep)))
  5147. `(lambda (cell contents info)
  5148. ;; Make sure that contents are exported as Org data when :raw
  5149. ;; parameter is non-nil.
  5150. ,(when (and backend (plist-get params :raw))
  5151. `(setq contents
  5152. ;; Since we don't know what are the pseudo object
  5153. ;; types defined in backend, we cannot pass them to
  5154. ;; `org-element-interpret-data'. As a consequence,
  5155. ;; they will be treated as pseudo elements, and will
  5156. ;; have newlines appended instead of spaces.
  5157. ;; Therefore, we must make sure :post-blank value is
  5158. ;; really turned into spaces.
  5159. (replace-regexp-in-string
  5160. "\n" " "
  5161. (org-trim
  5162. (org-element-interpret-data
  5163. (org-element-contents cell))))))
  5164. (let ((headerp ,(and (or hfmt hsep)
  5165. '(org-export-table-row-in-header-p
  5166. (org-export-get-parent-element cell) info)))
  5167. (column
  5168. ;; Call costly `org-export-table-cell-address' only if
  5169. ;; absolutely necessary, i.e., if one
  5170. ;; of :fmt :efmt :hfmt has a "plist type" value.
  5171. ,(and (cl-some (lambda (v) (integerp (car-safe v)))
  5172. (list efmt hfmt fmt))
  5173. '(1+ (cdr (org-export-table-cell-address cell info))))))
  5174. (when contents
  5175. ;; Check if we can apply `:efmt' on CONTENTS.
  5176. ,(when efmt
  5177. `(when (string-match orgtbl-exp-regexp contents)
  5178. (let ((mantissa (match-string 1 contents))
  5179. (exponent (match-string 2 contents)))
  5180. (setq contents ,(org-table--generic-apply
  5181. efmt ":efmt" t 'mantissa 'exponent)))))
  5182. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  5183. (cond
  5184. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  5185. hfmt ":hfmt" t 'contents))))
  5186. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  5187. fmt ":fmt" t 'contents))))))
  5188. ;; If a separator is provided, use it instead of BACKEND's.
  5189. ;; Separators are ignored when LFMT (or equivalent) is
  5190. ;; provided.
  5191. ,(cond
  5192. ((or hsep sep)
  5193. `(if (or ,(and (not sep) '(not headerp))
  5194. (plist-get info :orgtbl-ignore-sep)
  5195. (not (org-export-get-next-element cell info)))
  5196. ,(if (not backend) 'contents
  5197. `(org-export-with-backend ',backend cell contents info))
  5198. (concat contents
  5199. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  5200. (or hsep sep)))))
  5201. (backend `(org-export-with-backend ',backend cell contents info))
  5202. (t 'contents))))))
  5203. ;;;###autoload
  5204. (defun orgtbl-to-tsv (table params)
  5205. "Convert the orgtbl-mode table to TAB separated material."
  5206. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  5207. ;;;###autoload
  5208. (defun orgtbl-to-csv (table params)
  5209. "Convert the orgtbl-mode table to CSV material.
  5210. This does take care of the proper quoting of fields with comma or quotes."
  5211. (orgtbl-to-generic table
  5212. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  5213. params)))
  5214. ;;;###autoload
  5215. (defun orgtbl-to-latex (table params)
  5216. "Convert the orgtbl-mode TABLE to LaTeX.
  5217. TABLE is a list, each entry either the symbol `hline' for
  5218. a horizontal separator line, or a list of fields for that line.
  5219. PARAMS is a property list of parameters that can influence the
  5220. conversion. All parameters from `orgtbl-to-generic' are
  5221. supported. It is also possible to use the following ones:
  5222. :booktabs
  5223. When non-nil, use formal \"booktabs\" style.
  5224. :environment
  5225. Specify environment to use, as a string. If you use
  5226. \"longtable\", you may also want to specify :language property,
  5227. as a string, to get proper continuation strings."
  5228. (require 'ox-latex)
  5229. (orgtbl-to-generic
  5230. table
  5231. (org-combine-plists
  5232. ;; Provide sane default values.
  5233. (list :backend 'latex
  5234. :latex-default-table-mode 'table
  5235. :latex-tables-centered nil
  5236. :latex-tables-booktabs (plist-get params :booktabs)
  5237. :latex-table-scientific-notation nil
  5238. :latex-default-table-environment
  5239. (or (plist-get params :environment) "tabular"))
  5240. params)))
  5241. ;;;###autoload
  5242. (defun orgtbl-to-html (table params)
  5243. "Convert the orgtbl-mode TABLE to HTML.
  5244. TABLE is a list, each entry either the symbol `hline' for
  5245. a horizontal separator line, or a list of fields for that line.
  5246. PARAMS is a property list of parameters that can influence the
  5247. conversion. All parameters from `orgtbl-to-generic' are
  5248. supported. It is also possible to use the following one:
  5249. :attributes
  5250. Attributes and values, as a plist, which will be used in
  5251. <table> tag."
  5252. (require 'ox-html)
  5253. (orgtbl-to-generic
  5254. table
  5255. (org-combine-plists
  5256. ;; Provide sane default values.
  5257. (list :backend 'html
  5258. :html-table-data-tags '("<td%s>" . "</td>")
  5259. :html-table-use-header-tags-for-first-column nil
  5260. :html-table-align-individual-fields t
  5261. :html-table-row-tags '("<tr>" . "</tr>")
  5262. :html-table-attributes
  5263. (if (plist-member params :attributes)
  5264. (plist-get params :attributes)
  5265. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  5266. :frame "hsides")))
  5267. params)))
  5268. ;;;###autoload
  5269. (defun orgtbl-to-texinfo (table params)
  5270. "Convert the orgtbl-mode TABLE to Texinfo.
  5271. TABLE is a list, each entry either the symbol `hline' for
  5272. a horizontal separator line, or a list of fields for that line.
  5273. PARAMS is a property list of parameters that can influence the
  5274. conversion. All parameters from `orgtbl-to-generic' are
  5275. supported. It is also possible to use the following one:
  5276. :columns
  5277. Column widths, as a string. When providing column fractions,
  5278. \"@columnfractions\" command can be omitted."
  5279. (require 'ox-texinfo)
  5280. (let ((output
  5281. (orgtbl-to-generic
  5282. table
  5283. (org-combine-plists
  5284. (list :backend 'texinfo
  5285. :texinfo-tables-verbatim nil
  5286. :texinfo-table-scientific-notation nil)
  5287. params)))
  5288. (columns (let ((w (plist-get params :columns)))
  5289. (cond ((not w) nil)
  5290. ((string-match-p "{\\|@columnfractions " w) w)
  5291. (t (concat "@columnfractions " w))))))
  5292. (if (not columns) output
  5293. (replace-regexp-in-string
  5294. "@multitable \\(.*\\)" columns output t nil 1))))
  5295. ;;;###autoload
  5296. (defun orgtbl-to-orgtbl (table params)
  5297. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  5298. TABLE is a list, each entry either the symbol `hline' for
  5299. a horizontal separator line, or a list of fields for that line.
  5300. PARAMS is a property list of parameters that can influence the
  5301. conversion. All parameters from `orgtbl-to-generic' are
  5302. supported.
  5303. Useful when slicing one table into many. The :hline, :sep,
  5304. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  5305. be set to provide ORGTBL directives for the generated table."
  5306. (require 'ox-org)
  5307. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  5308. (defun orgtbl-to-table.el (table params)
  5309. "Convert the orgtbl-mode TABLE into a table.el table.
  5310. TABLE is a list, each entry either the symbol `hline' for
  5311. a horizontal separator line, or a list of fields for that line.
  5312. PARAMS is a property list of parameters that can influence the
  5313. conversion. All parameters from `orgtbl-to-generic' are
  5314. supported."
  5315. (with-temp-buffer
  5316. (insert (orgtbl-to-orgtbl table params))
  5317. (org-table-align)
  5318. (replace-regexp-in-string
  5319. "-|" "-+"
  5320. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  5321. (defun orgtbl-to-unicode (table params)
  5322. "Convert the orgtbl-mode TABLE into a table with unicode characters.
  5323. TABLE is a list, each entry either the symbol `hline' for
  5324. a horizontal separator line, or a list of fields for that line.
  5325. PARAMS is a property list of parameters that can influence the
  5326. conversion. All parameters from `orgtbl-to-generic' are
  5327. supported. It is also possible to use the following ones:
  5328. :ascii-art
  5329. When non-nil, use \"ascii-art-to-unicode\" package to translate
  5330. the table. You can download it here:
  5331. http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  5332. :narrow
  5333. When non-nil, narrow columns width than provided width cookie,
  5334. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  5335. (require 'ox-ascii)
  5336. (orgtbl-to-generic
  5337. table
  5338. (org-combine-plists
  5339. (list :backend 'ascii
  5340. :ascii-charset 'utf-8
  5341. :ascii-table-widen-columns (not (plist-get params :narrow))
  5342. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  5343. params)))
  5344. ;; Put the cursor in a column containing numerical values
  5345. ;; of an Org table,
  5346. ;; type C-c " a
  5347. ;; A new column is added with a bar plot.
  5348. ;; When the table is refreshed (C-u C-c *),
  5349. ;; the plot is updated to reflect the new values.
  5350. (defun orgtbl-ascii-draw (value min max &optional width characters)
  5351. "Draw an ascii bar in a table.
  5352. VALUE is the value to plot, it determines the width of the bar to draw.
  5353. MIN is the value that will be displayed as empty (zero width bar).
  5354. MAX is the value that will draw a bar filling all the WIDTH.
  5355. WIDTH is the span in characters from MIN to MAX.
  5356. CHARACTERS is a string that will compose the bar, with shades of grey
  5357. from pure white to pure black. It defaults to a 10 characters string
  5358. of regular ascii characters."
  5359. (let* ((width (ceiling (or width 12)))
  5360. (characters (or characters " .:;c!lhVHW"))
  5361. (len (1- (length characters)))
  5362. (value (float (if (numberp value)
  5363. value (string-to-number value))))
  5364. (relative (/ (- value min) (- max min)))
  5365. (steps (round (* relative width len))))
  5366. (cond ((< steps 0) "too small")
  5367. ((> steps (* width len)) "too large")
  5368. (t (let* ((int-division (/ steps len))
  5369. (remainder (- steps (* int-division len))))
  5370. (concat (make-string int-division (elt characters len))
  5371. (string (elt characters remainder))))))))
  5372. ;;;###autoload
  5373. (defun orgtbl-ascii-plot (&optional ask)
  5374. "Draw an ASCII bar plot in a column.
  5375. With cursor in a column containing numerical values, this function
  5376. will draw a plot in a new column.
  5377. ASK, if given, is a numeric prefix to override the default 12
  5378. characters width of the plot. ASK may also be the `\\[universal-argument]' \
  5379. prefix,
  5380. which will prompt for the width."
  5381. (interactive "P")
  5382. (let ((col (org-table-current-column))
  5383. (min 1e999) ; 1e999 will be converted to infinity
  5384. (max -1e999) ; which is the desired result
  5385. (table (org-table-to-lisp))
  5386. (length
  5387. (cond ((consp ask)
  5388. (read-number "Length of column " 12))
  5389. ((numberp ask) ask)
  5390. (t 12))))
  5391. ;; Skip any hline a the top of table.
  5392. (while (eq (car table) 'hline) (setq table (cdr table)))
  5393. ;; Skip table header if any.
  5394. (dolist (x (or (cdr (memq 'hline table)) table))
  5395. (when (consp x)
  5396. (setq x (nth (1- col) x))
  5397. (when (string-match
  5398. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  5399. x)
  5400. (setq x (string-to-number x))
  5401. (when (> min x) (setq min x))
  5402. (when (< max x) (setq max x)))))
  5403. (org-table-insert-column)
  5404. (org-table-move-column-right)
  5405. (org-table-store-formulas
  5406. (cons
  5407. (cons
  5408. (concat "$" (number-to-string (1+ col)))
  5409. (format "'(%s $%s %s %s %s)"
  5410. "orgtbl-ascii-draw" col min max length))
  5411. (org-table-get-stored-formulas)))
  5412. (org-table-recalculate t)))
  5413. ;; Example of extension: unicode characters
  5414. ;; Here are two examples of different styles.
  5415. ;; Unicode block characters are used to give a smooth effect.
  5416. ;; See http://en.wikipedia.org/wiki/Block_Elements
  5417. ;; Use one of those drawing functions
  5418. ;; - orgtbl-ascii-draw (the default ascii)
  5419. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  5420. ;; - orgtbl-uc-draw-cont (smooth unicode)
  5421. ;; This is best viewed with the "DejaVu Sans Mono" font
  5422. ;; (use M-x set-frame-font).
  5423. (defun orgtbl-uc-draw-grid (value min max &optional width)
  5424. "Draw a bar in a table using block unicode characters.
  5425. It is a variant of orgtbl-ascii-draw with Unicode block
  5426. characters, for a smooth display. Bars appear as grids (to the
  5427. extent the font allows)."
  5428. ;; http://en.wikipedia.org/wiki/Block_Elements
  5429. ;; best viewed with the "DejaVu Sans Mono" font.
  5430. (orgtbl-ascii-draw value min max width
  5431. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  5432. (defun orgtbl-uc-draw-cont (value min max &optional width)
  5433. "Draw a bar in a table using block unicode characters.
  5434. It is a variant of orgtbl-ascii-draw with Unicode block
  5435. characters, for a smooth display. Bars are solid (to the extent
  5436. the font allows)."
  5437. (orgtbl-ascii-draw value min max width
  5438. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  5439. (defun org-table-get-remote-range (name-or-id form)
  5440. "Get a field value or a list of values in a range from table at ID.
  5441. NAME-OR-ID may be the name of a table in the current file as set
  5442. by a \"#+NAME:\" directive. The first table following this line
  5443. will then be used. Alternatively, it may be an ID referring to
  5444. any entry, also in a different file. In this case, the first
  5445. table in that entry will be referenced.
  5446. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  5447. \"@I$2..@II$2\". All the references must be absolute, not relative.
  5448. The return value is either a single string for a single field, or a
  5449. list of the fields in the rectangle."
  5450. (save-match-data
  5451. (let ((case-fold-search t) (id-loc nil)
  5452. ;; Protect a bunch of variables from being overwritten by
  5453. ;; the context of the remote table.
  5454. org-table-column-names org-table-column-name-regexp
  5455. org-table-local-parameters org-table-named-field-locations
  5456. org-table-current-line-types
  5457. org-table-current-begin-pos org-table-dlines
  5458. org-table-current-ncol
  5459. org-table-hlines
  5460. org-table-last-column-widths
  5461. org-table-last-alignment
  5462. buffer loc)
  5463. (setq form (org-table-convert-refs-to-rc form))
  5464. (org-with-wide-buffer
  5465. (goto-char (point-min))
  5466. (if (re-search-forward
  5467. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  5468. (regexp-quote name-or-id) "[ \t]*$")
  5469. nil t)
  5470. (setq buffer (current-buffer) loc (match-beginning 0))
  5471. (setq id-loc (org-id-find name-or-id 'marker))
  5472. (unless (and id-loc (markerp id-loc))
  5473. (user-error "Can't find remote table \"%s\"" name-or-id))
  5474. (setq buffer (marker-buffer id-loc)
  5475. loc (marker-position id-loc))
  5476. (move-marker id-loc nil))
  5477. (with-current-buffer buffer
  5478. (org-with-wide-buffer
  5479. (goto-char loc)
  5480. (forward-char 1)
  5481. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  5482. (not (match-beginning 1)))
  5483. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  5484. (org-table-analyze)
  5485. (setq form (org-table-formula-substitute-names
  5486. (org-table-formula-handle-first/last-rc form)))
  5487. (if (and (string-match org-table-range-regexp form)
  5488. (> (length (match-string 0 form)) 1))
  5489. (org-table-get-range
  5490. (match-string 0 form) org-table-current-begin-pos 1)
  5491. form)))))))
  5492. (defun org-table-remote-reference-indirection (form)
  5493. "Return formula with table remote references substituted by indirection.
  5494. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  5495. This indirection works only with the format @ROW$COLUMN. The
  5496. format \"B3\" is not supported because it can not be
  5497. distinguished from a plain table name or ID."
  5498. (let ((regexp
  5499. ;; Same as in `org-table-eval-formula'.
  5500. (concat "\\<remote([ \t]*\\("
  5501. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  5502. "[@$][^ \t,]+"
  5503. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
  5504. (replace-regexp-in-string
  5505. regexp
  5506. (lambda (m)
  5507. (save-match-data
  5508. (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
  5509. (org-table-get-range
  5510. (if (string-match-p "\\`\\$[0-9]+\\'" eq)
  5511. (concat "@0" eq)
  5512. eq)))))
  5513. form t t 1)))
  5514. (defmacro org-define-lookup-function (mode)
  5515. (let ((mode-str (symbol-name mode))
  5516. (first-p (eq mode 'first))
  5517. (all-p (eq mode 'all)))
  5518. (let ((plural-str (if all-p "s" "")))
  5519. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  5520. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  5521. If R-LIST is nil, return matching element%s of S-LIST.
  5522. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  5523. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  5524. This function is generated by a call to the macro `org-define-lookup-function'."
  5525. mode-str plural-str plural-str plural-str)
  5526. (let ,(let ((lvars '((p (or predicate 'equal))
  5527. (sl s-list)
  5528. (rl (or r-list s-list))
  5529. (ret nil))))
  5530. (if first-p (cons '(match-p nil) lvars) lvars))
  5531. (while ,(if first-p '(and (not match-p) sl) 'sl)
  5532. (when (funcall p val (car sl))
  5533. ,(when first-p '(setq match-p t))
  5534. (let ((rval (car rl)))
  5535. (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
  5536. (setq sl (cdr sl) rl (cdr rl)))
  5537. ret)))))
  5538. (org-define-lookup-function first)
  5539. (org-define-lookup-function last)
  5540. (org-define-lookup-function all)
  5541. (provide 'org-table)
  5542. ;; Local variables:
  5543. ;; generated-autoload-file: "org-loaddefs.el"
  5544. ;; End:
  5545. ;;; org-table.el ends here