org-table.el 216 KB

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