org-table.el 234 KB

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