org-table.el 218 KB

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