org-table.el 202 KB

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