org-table.el 208 KB

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