org-table.el 234 KB

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