org-table.el 234 KB

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