org-table.el 234 KB

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