org-table.el 216 KB

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