org-table.el 216 KB

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