org-table.el 218 KB

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