org-table.el 206 KB

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