org-table.el 205 KB

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