org-table.el 235 KB

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