org-table.el 235 KB

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