org-table.el 231 KB

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