org-table.el 208 KB

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