org-table.el 234 KB

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