org-table.el 207 KB

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