org-table.el 228 KB

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