org-table.el 207 KB

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