org-table.el 205 KB

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