org-table.el 236 KB

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