org-table.el 234 KB

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