org-table.el 234 KB

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