org-table.el 235 KB

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