org-table.el 235 KB

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