org-table.el 234 KB

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