org-table.el 207 KB

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