org-table.el 233 KB

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