org-table.el 236 KB

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