org-table.el 218 KB

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