org-table.el 231 KB

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