org-table.el 199 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358
  1. ;;; org-table.el --- The table editor for Org-mode
  2. ;; Copyright (C) 2004-2014 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-do-sort lns "Table" with-case sorting-type getkey-func compare-func))
  1616. (when org-table-overlay-coordinates
  1617. (org-table-toggle-coordinate-overlays))
  1618. (delete-region beg end)
  1619. (move-marker beg nil)
  1620. (move-marker end nil)
  1621. (insert (mapconcat 'cdr lns "\n") "\n")
  1622. (org-goto-line thisline)
  1623. (org-table-goto-column thiscol)
  1624. (when otc (org-table-toggle-coordinate-overlays))
  1625. (message "%d lines sorted, based on column %d" (length lns) column)))
  1626. ;;;###autoload
  1627. (defun org-table-cut-region (beg end)
  1628. "Copy region in table to the clipboard and blank all relevant fields.
  1629. If there is no active region, use just the field at point."
  1630. (interactive (list
  1631. (if (org-region-active-p) (region-beginning) (point))
  1632. (if (org-region-active-p) (region-end) (point))))
  1633. (org-table-copy-region beg end 'cut))
  1634. ;;;###autoload
  1635. (defun org-table-copy-region (beg end &optional cut)
  1636. "Copy rectangular region in table to clipboard.
  1637. A special clipboard is used which can only be accessed
  1638. with `org-table-paste-rectangle'."
  1639. (interactive (list
  1640. (if (org-region-active-p) (region-beginning) (point))
  1641. (if (org-region-active-p) (region-end) (point))
  1642. current-prefix-arg))
  1643. (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
  1644. region cols
  1645. (rpl (if cut " " nil)))
  1646. (goto-char beg)
  1647. (org-table-check-inside-data-field)
  1648. (setq l01 (org-current-line)
  1649. c01 (org-table-current-column))
  1650. (goto-char end)
  1651. (org-table-check-inside-data-field)
  1652. (setq l02 (org-current-line)
  1653. c02 (org-table-current-column))
  1654. (setq l1 (min l01 l02) l2 (max l01 l02)
  1655. c1 (min c01 c02) c2 (max c01 c02))
  1656. (catch 'exit
  1657. (while t
  1658. (catch 'nextline
  1659. (if (> l1 l2) (throw 'exit t))
  1660. (org-goto-line l1)
  1661. (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
  1662. (setq cols nil ic1 c1 ic2 c2)
  1663. (while (< ic1 (1+ ic2))
  1664. (push (org-table-get-field ic1 rpl) cols)
  1665. (setq ic1 (1+ ic1)))
  1666. (push (nreverse cols) region)
  1667. (setq l1 (1+ l1)))))
  1668. (setq org-table-clip (nreverse region))
  1669. (if cut (org-table-align))
  1670. org-table-clip))
  1671. ;;;###autoload
  1672. (defun org-table-paste-rectangle ()
  1673. "Paste a rectangular region into a table.
  1674. The upper right corner ends up in the current field. All involved fields
  1675. will be overwritten. If the rectangle does not fit into the present table,
  1676. the table is enlarged as needed. The process ignores horizontal separator
  1677. lines."
  1678. (interactive)
  1679. (unless (and org-table-clip (listp org-table-clip))
  1680. (user-error "First cut/copy a region to paste!"))
  1681. (org-table-check-inside-data-field)
  1682. (let* ((clip org-table-clip)
  1683. (line (org-current-line))
  1684. (col (org-table-current-column))
  1685. (org-enable-table-editor t)
  1686. (org-table-automatic-realign nil)
  1687. c cols field)
  1688. (while (setq cols (pop clip))
  1689. (while (org-at-table-hline-p) (beginning-of-line 2))
  1690. (if (not (org-at-table-p))
  1691. (progn (end-of-line 0) (org-table-next-field)))
  1692. (setq c col)
  1693. (while (setq field (pop cols))
  1694. (org-table-goto-column c nil 'force)
  1695. (org-table-get-field nil field)
  1696. (setq c (1+ c)))
  1697. (beginning-of-line 2))
  1698. (org-goto-line line)
  1699. (org-table-goto-column col)
  1700. (org-table-align)))
  1701. ;;;###autoload
  1702. (defun org-table-convert ()
  1703. "Convert from `org-mode' table to table.el and back.
  1704. Obviously, this only works within limits. When an Org-mode table is
  1705. converted to table.el, all horizontal separator lines get lost, because
  1706. table.el uses these as cell boundaries and has no notion of horizontal lines.
  1707. A table.el table can be converted to an Org-mode table only if it does not
  1708. do row or column spanning. Multiline cells will become multiple cells.
  1709. Beware, Org-mode does not test if the table can be successfully converted - it
  1710. blindly applies a recipe that works for simple tables."
  1711. (interactive)
  1712. (require 'table)
  1713. (if (org-at-table.el-p)
  1714. ;; convert to Org-mode table
  1715. (let ((beg (move-marker (make-marker) (org-table-begin t)))
  1716. (end (move-marker (make-marker) (org-table-end t))))
  1717. (table-unrecognize-region beg end)
  1718. (goto-char beg)
  1719. (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
  1720. (replace-match ""))
  1721. (goto-char beg))
  1722. (if (org-at-table-p)
  1723. ;; convert to table.el table
  1724. (let ((beg (move-marker (make-marker) (org-table-begin)))
  1725. (end (move-marker (make-marker) (org-table-end))))
  1726. ;; first, get rid of all horizontal lines
  1727. (goto-char beg)
  1728. (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
  1729. (replace-match ""))
  1730. ;; insert a hline before first
  1731. (goto-char beg)
  1732. (org-table-insert-hline 'above)
  1733. (beginning-of-line -1)
  1734. ;; insert a hline after each line
  1735. (while (progn (beginning-of-line 3) (< (point) end))
  1736. (org-table-insert-hline))
  1737. (goto-char beg)
  1738. (setq end (move-marker end (org-table-end)))
  1739. ;; replace "+" at beginning and ending of hlines
  1740. (while (re-search-forward "^\\([ \t]*\\)|-" end t)
  1741. (replace-match "\\1+-"))
  1742. (goto-char beg)
  1743. (while (re-search-forward "-|[ \t]*$" end t)
  1744. (replace-match "-+"))
  1745. (goto-char beg)))))
  1746. (defun org-table-transpose-table-at-point ()
  1747. "Transpose Org table at point and eliminate hlines.
  1748. So a table like
  1749. | 1 | 2 | 4 | 5 |
  1750. |---+---+---+---|
  1751. | a | b | c | d |
  1752. | e | f | g | h |
  1753. will be transposed as
  1754. | 1 | a | e |
  1755. | 2 | b | f |
  1756. | 4 | c | g |
  1757. | 5 | d | h |
  1758. Note that horizontal lines disappear."
  1759. (interactive)
  1760. (let* ((table (delete 'hline (org-table-to-lisp)))
  1761. (dline_old (org-table-current-line))
  1762. (col_old (org-table-current-column))
  1763. (contents (mapcar (lambda (p)
  1764. (let ((tp table))
  1765. (mapcar
  1766. (lambda (rown)
  1767. (prog1
  1768. (pop (car tp))
  1769. (setq tp (cdr tp))))
  1770. table)))
  1771. (car table))))
  1772. (goto-char (org-table-begin))
  1773. (re-search-forward "|")
  1774. (backward-char)
  1775. (delete-region (point) (org-table-end))
  1776. (insert (mapconcat
  1777. (lambda(x)
  1778. (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
  1779. contents ""))
  1780. (org-table-goto-line col_old)
  1781. (org-table-goto-column dline_old))
  1782. (org-table-align))
  1783. ;;;###autoload
  1784. (defun org-table-wrap-region (arg)
  1785. "Wrap several fields in a column like a paragraph.
  1786. This is useful if you'd like to spread the contents of a field over several
  1787. lines, in order to keep the table compact.
  1788. If there is an active region, and both point and mark are in the same column,
  1789. the text in the column is wrapped to minimum width for the given number of
  1790. lines. Generally, this makes the table more compact. A prefix ARG may be
  1791. used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
  1792. formats the selected text to two lines. If the region was longer than two
  1793. lines, the remaining lines remain empty. A negative prefix argument reduces
  1794. the current number of lines by that amount. The wrapped text is pasted back
  1795. into the table. If you formatted it to more lines than it was before, fields
  1796. further down in the table get overwritten - so you might need to make space in
  1797. the table first.
  1798. If there is no region, the current field is split at the cursor position and
  1799. the text fragment to the right of the cursor is prepended to the field one
  1800. line down.
  1801. If there is no region, but you specify a prefix ARG, the current field gets
  1802. blank, and the content is appended to the field above."
  1803. (interactive "P")
  1804. (org-table-check-inside-data-field)
  1805. (if (org-region-active-p)
  1806. ;; There is a region: fill as a paragraph
  1807. (let* ((beg (region-beginning))
  1808. (cline (save-excursion (goto-char beg) (org-current-line)))
  1809. (ccol (save-excursion (goto-char beg) (org-table-current-column)))
  1810. nlines)
  1811. (org-table-cut-region (region-beginning) (region-end))
  1812. (if (> (length (car org-table-clip)) 1)
  1813. (user-error "Region must be limited to single column"))
  1814. (setq nlines (if arg
  1815. (if (< arg 1)
  1816. (+ (length org-table-clip) arg)
  1817. arg)
  1818. (length org-table-clip)))
  1819. (setq org-table-clip
  1820. (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
  1821. nil nlines)))
  1822. (org-goto-line cline)
  1823. (org-table-goto-column ccol)
  1824. (org-table-paste-rectangle))
  1825. ;; No region, split the current field at point
  1826. (unless (org-get-alist-option org-M-RET-may-split-line 'table)
  1827. (skip-chars-forward "^\r\n|"))
  1828. (if arg
  1829. ;; combine with field above
  1830. (let ((s (org-table-blank-field))
  1831. (col (org-table-current-column)))
  1832. (beginning-of-line 0)
  1833. (while (org-at-table-hline-p) (beginning-of-line 0))
  1834. (org-table-goto-column col)
  1835. (skip-chars-forward "^|")
  1836. (skip-chars-backward " ")
  1837. (insert " " (org-trim s))
  1838. (org-table-align))
  1839. ;; split field
  1840. (if (looking-at "\\([^|]+\\)+|")
  1841. (let ((s (match-string 1)))
  1842. (replace-match " |")
  1843. (goto-char (match-beginning 0))
  1844. (org-table-next-row)
  1845. (insert (org-trim s) " ")
  1846. (org-table-align))
  1847. (org-table-next-row)))))
  1848. (defvar org-field-marker nil)
  1849. ;;;###autoload
  1850. (defun org-table-edit-field (arg)
  1851. "Edit table field in a different window.
  1852. This is mainly useful for fields that contain hidden parts.
  1853. When called with a \\[universal-argument] prefix, just make the full field visible so that
  1854. it can be edited in place."
  1855. (interactive "P")
  1856. (cond
  1857. ((equal arg '(16))
  1858. (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
  1859. (arg
  1860. (let ((b (save-excursion (skip-chars-backward "^|") (point)))
  1861. (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
  1862. (remove-text-properties b e '(org-cwidth t invisible t
  1863. display t intangible t))
  1864. (if (and (boundp 'font-lock-mode) font-lock-mode)
  1865. (font-lock-fontify-block))))
  1866. (t
  1867. (let ((pos (point-marker))
  1868. (coord
  1869. (if (eq org-table-use-standard-references t)
  1870. (concat (org-number-to-letters (org-table-current-column))
  1871. (int-to-string (org-table-current-dline)))
  1872. (concat "@" (int-to-string (org-table-current-dline))
  1873. "$" (int-to-string (org-table-current-column)))))
  1874. (field (org-table-get-field))
  1875. (cw (current-window-configuration))
  1876. p)
  1877. (goto-char pos)
  1878. (org-switch-to-buffer-other-window "*Org Table Edit Field*")
  1879. (when (and (local-variable-p 'org-field-marker)
  1880. (markerp org-field-marker))
  1881. (move-marker org-field-marker nil))
  1882. (erase-buffer)
  1883. (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
  1884. (let ((org-inhibit-startup t)) (org-mode))
  1885. (auto-fill-mode -1)
  1886. (setq truncate-lines nil)
  1887. (setq word-wrap t)
  1888. (goto-char (setq p (point-max)))
  1889. (insert (org-trim field))
  1890. (remove-text-properties p (point-max)
  1891. '(invisible t org-cwidth t display t
  1892. intangible t))
  1893. (goto-char p)
  1894. (org-set-local 'org-finish-function 'org-table-finish-edit-field)
  1895. (org-set-local 'org-window-configuration cw)
  1896. (org-set-local 'org-field-marker pos)
  1897. (message "Edit and finish with C-c C-c")))))
  1898. (defun org-table-finish-edit-field ()
  1899. "Finish editing a table data field.
  1900. Remove all newline characters, insert the result into the table, realign
  1901. the table and kill the editing buffer."
  1902. (let ((pos org-field-marker)
  1903. (cw org-window-configuration)
  1904. (cb (current-buffer))
  1905. text)
  1906. (goto-char (point-min))
  1907. (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
  1908. (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
  1909. (replace-match " "))
  1910. (setq text (org-trim (buffer-string)))
  1911. (set-window-configuration cw)
  1912. (kill-buffer cb)
  1913. (select-window (get-buffer-window (marker-buffer pos)))
  1914. (goto-char pos)
  1915. (move-marker pos nil)
  1916. (org-table-check-inside-data-field)
  1917. (org-table-get-field nil text)
  1918. (org-table-align)
  1919. (message "New field value inserted")))
  1920. (define-minor-mode org-table-follow-field-mode
  1921. "Minor mode to make the table field editor window follow the cursor.
  1922. When this mode is active, the field editor window will always show the
  1923. current field. The mode exits automatically when the cursor leaves the
  1924. table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
  1925. nil " TblFollow" nil
  1926. (if org-table-follow-field-mode
  1927. (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
  1928. 'append 'local)
  1929. (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
  1930. (let* ((buf (get-buffer "*Org Table Edit Field*"))
  1931. (win (and buf (get-buffer-window buf))))
  1932. (when win (delete-window win))
  1933. (when buf
  1934. (with-current-buffer buf
  1935. (move-marker org-field-marker nil))
  1936. (kill-buffer buf)))))
  1937. (defun org-table-follow-fields-with-editor ()
  1938. (if (and org-table-exit-follow-field-mode-when-leaving-table
  1939. (not (org-at-table-p)))
  1940. ;; We have left the table, exit the follow mode
  1941. (org-table-follow-field-mode -1)
  1942. (when (org-table-check-inside-data-field 'noerror)
  1943. (let ((win (selected-window)))
  1944. (org-table-edit-field nil)
  1945. (org-fit-window-to-buffer)
  1946. (select-window win)))))
  1947. (defvar org-timecnt) ; dynamically scoped parameter
  1948. ;;;###autoload
  1949. (defun org-table-sum (&optional beg end nlast)
  1950. "Sum numbers in region of current table column.
  1951. The result will be displayed in the echo area, and will be available
  1952. as kill to be inserted with \\[yank].
  1953. If there is an active region, it is interpreted as a rectangle and all
  1954. numbers in that rectangle will be summed. If there is no active
  1955. region and point is located in a table column, sum all numbers in that
  1956. column.
  1957. If at least one number looks like a time HH:MM or HH:MM:SS, all other
  1958. numbers are assumed to be times as well (in decimal hours) and the
  1959. numbers are added as such.
  1960. If NLAST is a number, only the NLAST fields will actually be summed."
  1961. (interactive)
  1962. (save-excursion
  1963. (let (col (org-timecnt 0) diff h m s org-table-clip)
  1964. (cond
  1965. ((and beg end)) ; beg and end given explicitly
  1966. ((org-region-active-p)
  1967. (setq beg (region-beginning) end (region-end)))
  1968. (t
  1969. (setq col (org-table-current-column))
  1970. (goto-char (org-table-begin))
  1971. (unless (re-search-forward "^[ \t]*|[^-]" nil t)
  1972. (user-error "No table data"))
  1973. (org-table-goto-column col)
  1974. (setq beg (point))
  1975. (goto-char (org-table-end))
  1976. (unless (re-search-backward "^[ \t]*|[^-]" nil t)
  1977. (user-error "No table data"))
  1978. (org-table-goto-column col)
  1979. (setq end (point))))
  1980. (let* ((items (apply 'append (org-table-copy-region beg end)))
  1981. (items1 (cond ((not nlast) items)
  1982. ((>= nlast (length items)) items)
  1983. (t (setq items (reverse items))
  1984. (setcdr (nthcdr (1- nlast) items) nil)
  1985. (nreverse items))))
  1986. (numbers (delq nil (mapcar 'org-table-get-number-for-summing
  1987. items1)))
  1988. (res (apply '+ numbers))
  1989. (sres (if (= org-timecnt 0)
  1990. (number-to-string res)
  1991. (setq diff (* 3600 res)
  1992. h (floor (/ diff 3600)) diff (mod diff 3600)
  1993. m (floor (/ diff 60)) diff (mod diff 60)
  1994. s diff)
  1995. (format "%.0f:%02.0f:%02.0f" h m s))))
  1996. (kill-new sres)
  1997. (if (org-called-interactively-p 'interactive)
  1998. (message "%s"
  1999. (substitute-command-keys
  2000. (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
  2001. (length numbers) sres))))
  2002. sres))))
  2003. (defun org-table-get-number-for-summing (s)
  2004. (let (n)
  2005. (if (string-match "^ *|? *" s)
  2006. (setq s (replace-match "" nil nil s)))
  2007. (if (string-match " *|? *$" s)
  2008. (setq s (replace-match "" nil nil s)))
  2009. (setq n (string-to-number s))
  2010. (cond
  2011. ((and (string-match "0" s)
  2012. (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
  2013. ((string-match "\\`[ \t]+\\'" s) nil)
  2014. ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
  2015. (let ((h (string-to-number (or (match-string 1 s) "0")))
  2016. (m (string-to-number (or (match-string 2 s) "0")))
  2017. (s (string-to-number (or (match-string 4 s) "0"))))
  2018. (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
  2019. (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
  2020. ((equal n 0) nil)
  2021. (t n))))
  2022. (defun org-table-current-field-formula (&optional key noerror)
  2023. "Return the formula active for the current field.
  2024. Assumes that specials are in place.
  2025. If KEY is given, return the key to this formula.
  2026. Otherwise return the formula preceded with \"=\" or \":=\"."
  2027. (let* ((name (car (rassoc (list (org-current-line)
  2028. (org-table-current-column))
  2029. org-table-named-field-locations)))
  2030. (col (org-table-current-column))
  2031. (scol (int-to-string col))
  2032. (ref (format "@%d$%d" (org-table-current-dline) col))
  2033. (stored-list (org-table-get-stored-formulas noerror))
  2034. (ass (or (assoc name stored-list)
  2035. (assoc ref stored-list)
  2036. (assoc scol stored-list))))
  2037. (if key
  2038. (car ass)
  2039. (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
  2040. (cdr ass))))))
  2041. (defun org-table-get-formula (&optional equation named)
  2042. "Read a formula from the minibuffer, offer stored formula as default.
  2043. When NAMED is non-nil, look for a named equation."
  2044. (let* ((stored-list (org-table-get-stored-formulas))
  2045. (name (car (rassoc (list (org-current-line)
  2046. (org-table-current-column))
  2047. org-table-named-field-locations)))
  2048. (ref (format "@%d$%d" (org-table-current-dline)
  2049. (org-table-current-column)))
  2050. (refass (assoc ref stored-list))
  2051. (nameass (assoc name stored-list))
  2052. (scol (if named
  2053. (if (and name (not (string-match "^LR[0-9]+$" name)))
  2054. name
  2055. ref)
  2056. (int-to-string (org-table-current-column))))
  2057. (dummy (and (or nameass refass) (not named)
  2058. (not (y-or-n-p "Replace existing field formula with column formula? " ))
  2059. (message "Formula not replaced")))
  2060. (name (or name ref))
  2061. (org-table-may-need-update nil)
  2062. (stored (cdr (assoc scol stored-list)))
  2063. (eq (cond
  2064. ((and stored equation (string-match "^ *=? *$" equation))
  2065. stored)
  2066. ((stringp equation)
  2067. equation)
  2068. (t (org-table-formula-from-user
  2069. (read-string
  2070. (org-table-formula-to-user
  2071. (format "%s formula %s%s="
  2072. (if named "Field" "Column")
  2073. (if (member (string-to-char scol) '(?$ ?@)) "" "$")
  2074. scol))
  2075. (if stored (org-table-formula-to-user stored) "")
  2076. 'org-table-formula-history
  2077. )))))
  2078. mustsave)
  2079. (when (not (string-match "\\S-" eq))
  2080. ;; remove formula
  2081. (setq stored-list (delq (assoc scol stored-list) stored-list))
  2082. (org-table-store-formulas stored-list)
  2083. (user-error "Formula removed"))
  2084. (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  2085. (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  2086. (if (and name (not named))
  2087. ;; We set the column equation, delete the named one.
  2088. (setq stored-list (delq (assoc name stored-list) stored-list)
  2089. mustsave t))
  2090. (if stored
  2091. (setcdr (assoc scol stored-list) eq)
  2092. (setq stored-list (cons (cons scol eq) stored-list)))
  2093. (if (or mustsave (not (equal stored eq)))
  2094. (org-table-store-formulas stored-list))
  2095. eq))
  2096. (defun org-table-store-formulas (alist)
  2097. "Store the list of formulas below the current table."
  2098. (setq alist (sort alist 'org-table-formula-less-p))
  2099. (let ((case-fold-search t))
  2100. (save-excursion
  2101. (goto-char (org-table-end))
  2102. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
  2103. (progn
  2104. ;; don't overwrite TBLFM, we might use text properties to store stuff
  2105. (goto-char (match-beginning 3))
  2106. (delete-region (match-beginning 3) (match-end 0)))
  2107. (org-indent-line)
  2108. (insert (or (match-string 2) "#+TBLFM:")))
  2109. (insert " "
  2110. (mapconcat (lambda (x)
  2111. (concat
  2112. (if (equal (string-to-char (car x)) ?@) "" "$")
  2113. (car x) "=" (cdr x)))
  2114. alist "::")
  2115. "\n"))))
  2116. (defsubst org-table-formula-make-cmp-string (a)
  2117. (when (string-match "\\`$[<>]" a)
  2118. (let ((arrow (string-to-char (substring a 1))))
  2119. ;; Fake a high number to make sure this is sorted at the end.
  2120. (setq a (org-table-formula-handle-first/last-rc a))
  2121. (setq a (format "$%d" (+ 10000
  2122. (if (= arrow ?<) -1000 0)
  2123. (string-to-number (substring a 1)))))))
  2124. (when (string-match
  2125. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  2126. a)
  2127. (concat
  2128. (if (match-end 2)
  2129. (format "@%05d" (string-to-number (match-string 2 a))) "")
  2130. (if (match-end 4)
  2131. (format "$%05d" (string-to-number (match-string 4 a))) "")
  2132. (if (match-end 5)
  2133. (concat "@@" (match-string 5 a))))))
  2134. (defun org-table-formula-less-p (a b)
  2135. "Compare two formulas for sorting."
  2136. (let ((as (org-table-formula-make-cmp-string (car a)))
  2137. (bs (org-table-formula-make-cmp-string (car b))))
  2138. (and as bs (string< as bs))))
  2139. ;;;###autoload
  2140. (defun org-table-get-stored-formulas (&optional noerror)
  2141. "Return an alist with the stored formulas directly after current table."
  2142. (interactive) ;; FIXME interactive?
  2143. (let ((case-fold-search t) scol eq eq-alist strings string seen)
  2144. (save-excursion
  2145. (goto-char (org-table-end))
  2146. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
  2147. (setq strings (org-split-string (org-match-string-no-properties 2)
  2148. " *:: *"))
  2149. (while (setq string (pop strings))
  2150. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
  2151. (setq scol (if (match-end 2)
  2152. (match-string 2 string)
  2153. (match-string 1 string))
  2154. scol (if (member (string-to-char scol) '(?< ?>))
  2155. (concat "$" scol) scol)
  2156. eq (match-string 3 string)
  2157. eq-alist (cons (cons scol eq) eq-alist))
  2158. (if (member scol seen)
  2159. (if noerror
  2160. (progn
  2161. (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
  2162. (ding)
  2163. (sit-for 2))
  2164. (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
  2165. (push scol seen))))))
  2166. (nreverse eq-alist)))
  2167. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2168. "Modify the equations after the table structure has been edited.
  2169. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2170. For all numbers larger than LIMIT, shift them by DELTA."
  2171. (save-excursion
  2172. (goto-char (org-table-end))
  2173. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2174. (let ((msg "The formulas in #+TBLFM have been updated")
  2175. (re (concat key "\\([0-9]+\\)"))
  2176. (re2
  2177. (when remove
  2178. (if (or (equal key "$") (equal key "$LR"))
  2179. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2180. (regexp-quote key) remove)
  2181. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2182. s n a)
  2183. (when remove
  2184. (while (re-search-forward re2 (point-at-eol) t)
  2185. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2186. (if (equal (char-before (match-beginning 0)) ?.)
  2187. (user-error
  2188. "Change makes TBLFM term %s invalid, use undo to recover"
  2189. (match-string 0))
  2190. (replace-match "")))))
  2191. (while (re-search-forward re (point-at-eol) t)
  2192. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2193. (setq s (match-string 1) n (string-to-number s))
  2194. (cond
  2195. ((setq a (assoc s replace))
  2196. (replace-match (concat key (cdr a)) t t)
  2197. (message msg))
  2198. ((and limit (> n limit))
  2199. (replace-match (concat key (int-to-string (+ n delta))) t t)
  2200. (message msg))))))
  2201. (forward-line))))
  2202. (defun org-table-get-specials ()
  2203. "Get the column names and local parameters for this table."
  2204. (save-excursion
  2205. (let ((beg (org-table-begin)) (end (org-table-end))
  2206. names name fields fields1 field cnt
  2207. c v l line col types dlines hlines last-dline)
  2208. (setq org-table-column-names nil
  2209. org-table-local-parameters nil
  2210. org-table-named-field-locations nil
  2211. org-table-current-begin-line nil
  2212. org-table-current-begin-pos nil
  2213. org-table-current-line-types nil
  2214. org-table-current-ncol 0)
  2215. (goto-char beg)
  2216. (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
  2217. (setq names (org-split-string (match-string 1) " *| *")
  2218. cnt 1)
  2219. (while (setq name (pop names))
  2220. (setq cnt (1+ cnt))
  2221. (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
  2222. (push (cons name (int-to-string cnt)) org-table-column-names))))
  2223. (setq org-table-column-names (nreverse org-table-column-names))
  2224. (setq org-table-column-name-regexp
  2225. (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
  2226. (goto-char beg)
  2227. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  2228. (setq fields (org-split-string (match-string 1) " *| *"))
  2229. (while (setq field (pop fields))
  2230. (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  2231. (push (cons (match-string 1 field) (match-string 2 field))
  2232. org-table-local-parameters))))
  2233. (goto-char beg)
  2234. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  2235. (setq c (match-string 1)
  2236. fields (org-split-string (match-string 2) " *| *"))
  2237. (save-excursion
  2238. (beginning-of-line (if (equal c "_") 2 0))
  2239. (setq line (org-current-line) col 1)
  2240. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  2241. (setq fields1 (org-split-string (match-string 1) " *| *"))))
  2242. (while (and fields1 (setq field (pop fields)))
  2243. (setq v (pop fields1) col (1+ col))
  2244. (when (and (stringp field) (stringp v)
  2245. (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
  2246. (push (cons field v) org-table-local-parameters)
  2247. (push (list field line col) org-table-named-field-locations))))
  2248. ;; Analyse the line types
  2249. (goto-char beg)
  2250. (setq org-table-current-begin-line (org-current-line)
  2251. org-table-current-begin-pos (point)
  2252. l org-table-current-begin-line)
  2253. (while (looking-at "[ \t]*|\\(-\\)?")
  2254. (push (if (match-end 1) 'hline 'dline) types)
  2255. (if (match-end 1) (push l hlines) (push l dlines))
  2256. (beginning-of-line 2)
  2257. (setq l (1+ l)))
  2258. (push 'hline types) ;; add an imaginary extra hline to the end
  2259. (setq org-table-current-line-types (apply 'vector (nreverse types))
  2260. last-dline (car dlines)
  2261. org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
  2262. org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
  2263. (org-goto-line last-dline)
  2264. (let* ((l last-dline)
  2265. (fields (org-split-string
  2266. (buffer-substring (point-at-bol) (point-at-eol))
  2267. "[ \t]*|[ \t]*"))
  2268. (nfields (length fields))
  2269. al al2)
  2270. (setq org-table-current-ncol nfields)
  2271. (loop for i from 1 to nfields do
  2272. (push (list (format "LR%d" i) l i) al)
  2273. (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
  2274. (setq org-table-named-field-locations
  2275. (append org-table-named-field-locations al))
  2276. (setq org-table-local-parameters
  2277. (append org-table-local-parameters al2))))))
  2278. ;;;###autoload
  2279. (defun org-table-maybe-eval-formula ()
  2280. "Check if the current field starts with \"=\" or \":=\".
  2281. If yes, store the formula and apply it."
  2282. ;; We already know we are in a table. Get field will only return a formula
  2283. ;; when appropriate. It might return a separator line, but no problem.
  2284. (when org-table-formula-evaluate-inline
  2285. (let* ((field (org-trim (or (org-table-get-field) "")))
  2286. named eq)
  2287. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2288. (setq named (equal (string-to-char field) ?:)
  2289. eq (match-string 1 field))
  2290. (if (or (fboundp 'calc-eval)
  2291. (equal (substring eq 0 (min 2 (length eq))) "'("))
  2292. (org-table-eval-formula (if named '(4) nil)
  2293. (org-table-formula-from-user eq))
  2294. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
  2295. (defvar org-recalc-commands nil
  2296. "List of commands triggering the recalculation of a line.
  2297. Will be filled automatically during use.")
  2298. (defvar org-recalc-marks
  2299. '((" " . "Unmarked: no special line, no automatic recalculation")
  2300. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  2301. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  2302. ("!" . "Column name definition line. Reference in formula as $name.")
  2303. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  2304. ("_" . "Names for values in row below this one.")
  2305. ("^" . "Names for values in row above this one.")))
  2306. ;;;###autoload
  2307. (defun org-table-rotate-recalc-marks (&optional newchar)
  2308. "Rotate the recalculation mark in the first column.
  2309. If in any row, the first field is not consistent with a mark,
  2310. insert a new column for the markers.
  2311. When there is an active region, change all the lines in the region,
  2312. after prompting for the marking character.
  2313. After each change, a message will be displayed indicating the meaning
  2314. of the new mark."
  2315. (interactive)
  2316. (unless (org-at-table-p) (user-error "Not at a table"))
  2317. (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
  2318. (beg (org-table-begin))
  2319. (end (org-table-end))
  2320. (l (org-current-line))
  2321. (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
  2322. (l2 (if (org-region-active-p) (org-current-line (region-end))))
  2323. (have-col
  2324. (save-excursion
  2325. (goto-char beg)
  2326. (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
  2327. (col (org-table-current-column))
  2328. (forcenew (car (assoc newchar org-recalc-marks)))
  2329. epos new)
  2330. (when l1
  2331. (message "Change region to what mark? Type # * ! $ or SPC: ")
  2332. (setq newchar (char-to-string (read-char-exclusive))
  2333. forcenew (car (assoc newchar org-recalc-marks))))
  2334. (if (and newchar (not forcenew))
  2335. (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
  2336. newchar))
  2337. (if l1 (org-goto-line l1))
  2338. (save-excursion
  2339. (beginning-of-line 1)
  2340. (unless (looking-at org-table-dataline-regexp)
  2341. (user-error "Not at a table data line")))
  2342. (unless have-col
  2343. (org-table-goto-column 1)
  2344. (org-table-insert-column)
  2345. (org-table-goto-column (1+ col)))
  2346. (setq epos (point-at-eol))
  2347. (save-excursion
  2348. (beginning-of-line 1)
  2349. (org-table-get-field
  2350. 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
  2351. (concat " "
  2352. (setq new (or forcenew
  2353. (cadr (member (match-string 1) marks))))
  2354. " ")
  2355. " # ")))
  2356. (if (and l1 l2)
  2357. (progn
  2358. (org-goto-line l1)
  2359. (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
  2360. (and (looking-at org-table-dataline-regexp)
  2361. (org-table-get-field 1 (concat " " new " "))))
  2362. (org-goto-line l1)))
  2363. (if (not (= epos (point-at-eol))) (org-table-align))
  2364. (org-goto-line l)
  2365. (and (org-called-interactively-p 'interactive)
  2366. (message "%s" (cdr (assoc new org-recalc-marks))))))
  2367. ;;;###autoload
  2368. (defun org-table-maybe-recalculate-line ()
  2369. "Recompute the current line if marked for it, and if we haven't just done it."
  2370. (interactive)
  2371. (and org-table-allow-automatic-line-recalculation
  2372. (not (and (memq last-command org-recalc-commands)
  2373. (equal org-last-recalc-line (org-current-line))))
  2374. (save-excursion (beginning-of-line 1)
  2375. (looking-at org-table-auto-recalculate-regexp))
  2376. (org-table-recalculate) t))
  2377. (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
  2378. (defsubst org-set-calc-mode (var &optional value)
  2379. (if (stringp var)
  2380. (setq var (assoc var '(("D" calc-angle-mode deg)
  2381. ("R" calc-angle-mode rad)
  2382. ("F" calc-prefer-frac t)
  2383. ("S" calc-symbolic-mode t)))
  2384. value (nth 2 var) var (nth 1 var)))
  2385. (if (memq var org-tbl-calc-modes)
  2386. (setcar (cdr (memq var org-tbl-calc-modes)) value)
  2387. (cons var (cons value org-tbl-calc-modes)))
  2388. org-tbl-calc-modes)
  2389. ;;;###autoload
  2390. (defun org-table-eval-formula (&optional arg equation
  2391. suppress-align suppress-const
  2392. suppress-store suppress-analysis)
  2393. "Replace the table field value at the cursor by the result of a calculation.
  2394. This function makes use of Dave Gillespie's Calc package, in my view the
  2395. most exciting program ever written for GNU Emacs. So you need to have Calc
  2396. installed in order to use this function.
  2397. In a table, this command replaces the value in the current field with the
  2398. result of a formula. It also installs the formula as the \"current\" column
  2399. formula, by storing it in a special line below the table. When called
  2400. with a `C-u' prefix, the current field must be a named field, and the
  2401. formula is installed as valid in only this specific field.
  2402. When called with two `C-u' prefixes, insert the active equation
  2403. for the field back into the current field, so that it can be
  2404. edited there. This is useful in order to use \\[org-table-show-reference]
  2405. to check the referenced fields.
  2406. When called, the command first prompts for a formula, which is read in
  2407. the minibuffer. Previously entered formulas are available through the
  2408. history list, and the last used formula is offered as a default.
  2409. These stored formulas are adapted correctly when moving, inserting, or
  2410. deleting columns with the corresponding commands.
  2411. The formula can be any algebraic expression understood by the Calc package.
  2412. For details, see the Org-mode manual.
  2413. This function can also be called from Lisp programs and offers
  2414. additional arguments: EQUATION can be the formula to apply. If this
  2415. argument is given, the user will not be prompted. SUPPRESS-ALIGN is
  2416. used to speed-up recursive calls by by-passing unnecessary aligns.
  2417. SUPPRESS-CONST suppresses the interpretation of constants in the
  2418. formula, assuming that this has been done already outside the function.
  2419. SUPPRESS-STORE means the formula should not be stored, either because
  2420. it is already stored, or because it is a modified equation that should
  2421. not overwrite the stored one."
  2422. (interactive "P")
  2423. (org-table-check-inside-data-field)
  2424. (or suppress-analysis (org-table-get-specials))
  2425. (if (equal arg '(16))
  2426. (let ((eq (org-table-current-field-formula)))
  2427. (or eq (user-error "No equation active for current field"))
  2428. (org-table-get-field nil eq)
  2429. (org-table-align)
  2430. (setq org-table-may-need-update t))
  2431. (let* (fields
  2432. (ndown (if (integerp arg) arg 1))
  2433. (org-table-automatic-realign nil)
  2434. (case-fold-search nil)
  2435. (down (> ndown 1))
  2436. (formula (if (and equation suppress-store)
  2437. equation
  2438. (org-table-get-formula equation (equal arg '(4)))))
  2439. (n0 (org-table-current-column))
  2440. (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
  2441. (numbers nil) ; was a variable, now fixed default
  2442. (keep-empty nil)
  2443. n form form0 formrpl formrg bw fmt x ev orig c lispp literal
  2444. duration duration-output-format)
  2445. ;; Parse the format string. Since we have a lot of modes, this is
  2446. ;; a lot of work. However, I think calc still uses most of the time.
  2447. (if (string-match ";" formula)
  2448. (let ((tmp (org-split-string formula ";")))
  2449. (setq formula (car tmp)
  2450. fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2451. (nth 1 tmp)))
  2452. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2453. (setq c (string-to-char (match-string 1 fmt))
  2454. n (string-to-number (match-string 2 fmt)))
  2455. (if (= c ?p)
  2456. (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
  2457. (setq org-tbl-calc-modes
  2458. (org-set-calc-mode
  2459. 'calc-float-format
  2460. (list (cdr (assoc c '((?n . float) (?f . fix)
  2461. (?s . sci) (?e . eng))))
  2462. n))))
  2463. (setq fmt (replace-match "" t t fmt)))
  2464. (if (string-match "T" fmt)
  2465. (setq duration t numbers t
  2466. duration-output-format nil
  2467. fmt (replace-match "" t t fmt)))
  2468. (if (string-match "t" fmt)
  2469. (setq duration t
  2470. duration-output-format org-table-duration-custom-format
  2471. numbers t
  2472. fmt (replace-match "" t t fmt)))
  2473. (if (string-match "N" fmt)
  2474. (setq numbers t
  2475. fmt (replace-match "" t t fmt)))
  2476. (if (string-match "L" fmt)
  2477. (setq literal t
  2478. fmt (replace-match "" t t fmt)))
  2479. (if (string-match "E" fmt)
  2480. (setq keep-empty t
  2481. fmt (replace-match "" t t fmt)))
  2482. (while (string-match "[DRFS]" fmt)
  2483. (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
  2484. (setq fmt (replace-match "" t t fmt)))
  2485. (unless (string-match "\\S-" fmt)
  2486. (setq fmt nil))))
  2487. (if (and (not suppress-const) org-table-formula-use-constants)
  2488. (setq formula (org-table-formula-substitute-names formula)))
  2489. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2490. (while (> ndown 0)
  2491. (setq fields (org-split-string
  2492. (buffer-substring-no-properties (point-at-bol) (point-at-eol))
  2493. " *| *"))
  2494. ;; replace fields with duration values if relevant
  2495. (if duration
  2496. (setq fields
  2497. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2498. fields)))
  2499. (if (eq numbers t)
  2500. (setq fields (mapcar
  2501. (lambda (x)
  2502. (if (string-match "\\S-" x)
  2503. (number-to-string (string-to-number x))
  2504. x))
  2505. fields)))
  2506. (setq ndown (1- ndown))
  2507. (setq form (copy-sequence formula)
  2508. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2509. (if (and lispp literal) (setq lispp 'literal))
  2510. ;; Insert row and column number of formula result field
  2511. (while (string-match "[@$]#" form)
  2512. (setq form
  2513. (replace-match
  2514. (format "%d"
  2515. (save-match-data
  2516. (if (equal (substring form (match-beginning 0)
  2517. (1+ (match-beginning 0)))
  2518. "@")
  2519. (org-table-current-dline)
  2520. (org-table-current-column))))
  2521. t t form)))
  2522. ;; Check for old vertical references
  2523. (org-table--error-on-old-row-references form)
  2524. ;; Insert remote references
  2525. (setq form (org-table-remote-reference-indirection form))
  2526. (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2527. (setq form
  2528. (replace-match
  2529. (save-match-data
  2530. (org-table-make-reference
  2531. (let ((rmtrng (org-table-get-remote-range
  2532. (match-string 1 form) (match-string 2 form))))
  2533. (if duration
  2534. (if (listp rmtrng)
  2535. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2536. (org-table-time-string-to-seconds rmtrng))
  2537. rmtrng))
  2538. keep-empty numbers lispp))
  2539. t t form)))
  2540. ;; Insert complex ranges
  2541. (while (and (string-match org-table-range-regexp form)
  2542. (> (length (match-string 0 form)) 1))
  2543. (setq formrg (save-match-data
  2544. (org-table-get-range (match-string 0 form) nil n0)))
  2545. (setq formrpl
  2546. (save-match-data
  2547. (org-table-make-reference
  2548. ;; possibly handle durations
  2549. (if duration
  2550. (if (listp formrg)
  2551. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2552. (org-table-time-string-to-seconds formrg))
  2553. formrg)
  2554. keep-empty numbers lispp)))
  2555. (if (not (save-match-data
  2556. (string-match (regexp-quote form) formrpl)))
  2557. (setq form (replace-match formrpl t t form))
  2558. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2559. ;; Insert simple ranges
  2560. (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
  2561. (setq form
  2562. (replace-match
  2563. (save-match-data
  2564. (org-table-make-reference
  2565. (org-sublist
  2566. fields (string-to-number (match-string 1 form))
  2567. (string-to-number (match-string 2 form)))
  2568. keep-empty numbers lispp))
  2569. t t form)))
  2570. (setq form0 form)
  2571. ;; Insert the references to fields in same row
  2572. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2573. (setq n (+ (string-to-number (match-string 1 form))
  2574. (if (match-end 2) n0 0))
  2575. x (nth (1- (if (= n 0) n0 (max n 1))) fields)
  2576. formrpl (save-match-data
  2577. (org-table-make-reference
  2578. x keep-empty numbers lispp)))
  2579. (when (or (not x)
  2580. (save-match-data
  2581. (string-match (regexp-quote formula) formrpl)))
  2582. (user-error "Invalid field specifier \"%s\""
  2583. (match-string 0 form)))
  2584. (setq form (replace-match formrpl t t form)))
  2585. (if lispp
  2586. (setq ev (condition-case nil
  2587. (eval (eval (read form)))
  2588. (error "#ERROR"))
  2589. ev (if (numberp ev) (number-to-string ev) ev)
  2590. ev (if duration (org-table-time-seconds-to-string
  2591. (string-to-number ev)
  2592. duration-output-format) ev))
  2593. (or (fboundp 'calc-eval)
  2594. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
  2595. ;; Use <...> time-stamps so that Calc can handle them
  2596. (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
  2597. (setq form (replace-match "<\\1>" nil nil form)))
  2598. ;; I18n-ize local time-stamps by setting (system-time-locale "C")
  2599. (when (string-match org-ts-regexp2 form)
  2600. (let* ((ts (match-string 0 form))
  2601. (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
  2602. (system-time-locale "C")
  2603. (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2604. (cdr org-time-stamp-formats))
  2605. (car org-time-stamp-formats))))
  2606. (setq form (replace-match (format-time-string tf tsp) t t form))))
  2607. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2608. form
  2609. (calc-eval (cons form org-tbl-calc-modes)
  2610. (when (and (not keep-empty) numbers) 'num)))
  2611. ev (if duration (org-table-time-seconds-to-string
  2612. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2613. (string-to-number (org-table-time-string-to-seconds ev))
  2614. (string-to-number ev))
  2615. duration-output-format)
  2616. ev)))
  2617. (when org-table-formula-debug
  2618. (with-output-to-temp-buffer "*Substitution History*"
  2619. (princ (format "Substitution history of formula
  2620. Orig: %s
  2621. $xyz-> %s
  2622. @r$c-> %s
  2623. $1-> %s\n" orig formula form0 form))
  2624. (if (consp ev)
  2625. (princ (format " %s^\nError: %s"
  2626. (make-string (car ev) ?\-) (nth 1 ev)))
  2627. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2628. ev (or fmt "NONE")
  2629. (if fmt (format fmt (string-to-number ev)) ev)))))
  2630. (setq bw (get-buffer-window "*Substitution History*"))
  2631. (org-fit-window-to-buffer bw)
  2632. (unless (and (org-called-interactively-p 'any) (not ndown))
  2633. (unless (let (inhibit-redisplay)
  2634. (y-or-n-p "Debugging Formula. Continue to next? "))
  2635. (org-table-align)
  2636. (user-error "Abort"))
  2637. (delete-window bw)
  2638. (message "")))
  2639. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2640. (org-table-justify-field-maybe
  2641. (format org-table-formula-field-format
  2642. (if fmt (format fmt (string-to-number ev)) ev)))
  2643. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2644. (call-interactively 'org-return)
  2645. (setq ndown 0)))
  2646. (and down (org-table-maybe-recalculate-line))
  2647. (or suppress-align (and org-table-may-need-update
  2648. (org-table-align))))))
  2649. (defun org-table-put-field-property (prop value)
  2650. (save-excursion
  2651. (put-text-property (progn (skip-chars-backward "^|") (point))
  2652. (progn (skip-chars-forward "^|") (point))
  2653. prop value)))
  2654. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2655. "Get a calc vector from a column, according to descriptor DESC.
  2656. Optional arguments TBEG and COL can give the beginning of the table and
  2657. the current column, to avoid unnecessary parsing.
  2658. HIGHLIGHT means just highlight the range.
  2659. When CORNERS-ONLY is set, only return the corners of the range as
  2660. a list (line1 column1 line2 column2) where line1 and line2 are line numbers
  2661. in the buffer and column1 and column2 are table column numbers."
  2662. (if (not (equal (string-to-char desc) ?@))
  2663. (setq desc (concat "@" desc)))
  2664. (save-excursion
  2665. (or tbeg (setq tbeg (org-table-begin)))
  2666. (or col (setq col (org-table-current-column)))
  2667. (let ((thisline (org-current-line))
  2668. beg end c1 c2 r1 r2 rangep tmp)
  2669. (unless (string-match org-table-range-regexp desc)
  2670. (user-error "Invalid table range specifier `%s'" desc))
  2671. (setq rangep (match-end 3)
  2672. r1 (and (match-end 1) (match-string 1 desc))
  2673. r2 (and (match-end 4) (match-string 4 desc))
  2674. c1 (and (match-end 2) (substring (match-string 2 desc) 1))
  2675. c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
  2676. (and c1 (setq c1 (+ (string-to-number c1)
  2677. (if (memq (string-to-char c1) '(?- ?+)) col 0))))
  2678. (and c2 (setq c2 (+ (string-to-number c2)
  2679. (if (memq (string-to-char c2) '(?- ?+)) col 0))))
  2680. (if (equal r1 "") (setq r1 nil))
  2681. (if (equal r2 "") (setq r2 nil))
  2682. (if r1 (setq r1 (org-table-get-descriptor-line r1)))
  2683. (if r2 (setq r2 (org-table-get-descriptor-line r2)))
  2684. ; (setq r2 (or r2 r1) c2 (or c2 c1))
  2685. (if (not r1) (setq r1 thisline))
  2686. (if (not r2) (setq r2 thisline))
  2687. (if (or (not c1) (= 0 c1)) (setq c1 col))
  2688. (if (or (not c2) (= 0 c2)) (setq c2 col))
  2689. (if (and (not corners-only)
  2690. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2691. ;; just one field
  2692. (progn
  2693. (org-goto-line r1)
  2694. (while (not (looking-at org-table-dataline-regexp))
  2695. (beginning-of-line 2))
  2696. (prog1 (org-trim (org-table-get-field c1))
  2697. (if highlight (org-table-highlight-rectangle (point) (point)))))
  2698. ;; A range, return a vector
  2699. ;; First sort the numbers to get a regular rectangle
  2700. (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
  2701. (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
  2702. (if corners-only
  2703. ;; Only return the corners of the range
  2704. (list r1 c1 r2 c2)
  2705. ;; Copy the range values into a list
  2706. (org-goto-line r1)
  2707. (while (not (looking-at org-table-dataline-regexp))
  2708. (beginning-of-line 2))
  2709. (org-table-goto-column c1)
  2710. (setq beg (point))
  2711. (org-goto-line r2)
  2712. (while (not (looking-at org-table-dataline-regexp))
  2713. (beginning-of-line 0))
  2714. (org-table-goto-column c2)
  2715. (setq end (point))
  2716. (if highlight
  2717. (org-table-highlight-rectangle
  2718. beg (progn (skip-chars-forward "^|\n") (point))))
  2719. ;; return string representation of calc vector
  2720. (mapcar 'org-trim
  2721. (apply 'append (org-table-copy-region beg end))))))))
  2722. (defun org-table-get-descriptor-line (desc &optional cline bline table)
  2723. "Analyze descriptor DESC and retrieve the corresponding line number.
  2724. The cursor is currently in line CLINE, the table begins in line BLINE,
  2725. and TABLE is a vector with line types."
  2726. (if (string-match "^[0-9]+$" desc)
  2727. (aref org-table-dlines (string-to-number desc))
  2728. (setq cline (or cline (org-current-line))
  2729. bline (or bline org-table-current-begin-line)
  2730. table (or table org-table-current-line-types))
  2731. (if (or
  2732. (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
  2733. ;; 1 2 3 4 5 6
  2734. (and (not (match-end 3)) (not (match-end 6)))
  2735. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2736. (user-error "Invalid row descriptor `%s'" desc))
  2737. (let* ((hdir (and (match-end 2) (match-string 2 desc)))
  2738. (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
  2739. (odir (and (match-end 5) (match-string 5 desc)))
  2740. (on (if (match-end 6) (string-to-number (match-string 6 desc))))
  2741. (i (- cline bline))
  2742. (rel (and (match-end 6)
  2743. (or (and (match-end 1) (not (match-end 3)))
  2744. (match-end 5)))))
  2745. (if (and hn (not hdir))
  2746. (progn
  2747. (setq i 0 hdir "+")
  2748. (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
  2749. (if (and (not hn) on (not odir))
  2750. (user-error "Should never happen");;(aref org-table-dlines on)
  2751. (if (and hn (> hn 0))
  2752. (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
  2753. nil hn cline desc)))
  2754. (if on
  2755. (setq i (org-table-find-row-type table i 'dline (equal odir "-")
  2756. rel on cline desc)))
  2757. (+ bline i)))))
  2758. (defun org-table-find-row-type (table i type backwards relative n cline desc)
  2759. "FIXME: Needs more documentation."
  2760. (let ((l (length table)))
  2761. (while (> n 0)
  2762. (while (and (setq i (+ i (if backwards -1 1)))
  2763. (>= i 0) (< i l)
  2764. (not (eq (aref table i) type))
  2765. (if (and relative (eq (aref table i) 'hline))
  2766. (cond
  2767. ((eq org-table-relative-ref-may-cross-hline t) t)
  2768. ((eq org-table-relative-ref-may-cross-hline 'error)
  2769. (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
  2770. (t (setq i (- i (if backwards -1 1))
  2771. n 1)
  2772. nil))
  2773. t)))
  2774. (setq n (1- n)))
  2775. (if (or (< i 0) (>= i l))
  2776. (user-error "Row descriptor %s used in line %d leads outside table"
  2777. desc cline)
  2778. i)))
  2779. (defun org-table--error-on-old-row-references (s)
  2780. (when (string-match "&[-+0-9I]" s)
  2781. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2782. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2783. "Convert list ELEMENTS to something appropriate to insert into formula.
  2784. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2785. NUMBERS indicates that everything should be converted to numbers.
  2786. LISPP non-nil means to return something appropriate for a Lisp
  2787. list, 'literal is for the format specifier L."
  2788. ;; Calc nan (not a number) is used for the conversion of the empty
  2789. ;; field to a reference for several reasons: (i) It is accepted in a
  2790. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2791. ;; (ii) In a single field (not in range) it can be distinguished
  2792. ;; from "(nan)" which is the reference made from a single field
  2793. ;; containing "nan".
  2794. (if (stringp elements)
  2795. ;; field reference
  2796. (if lispp
  2797. (if (eq lispp 'literal)
  2798. elements
  2799. (if (and (eq elements "") (not keep-empty))
  2800. ""
  2801. (prin1-to-string
  2802. (if numbers (string-to-number elements) elements))))
  2803. (if (string-match "\\S-" elements)
  2804. (progn
  2805. (when numbers (setq elements (number-to-string
  2806. (string-to-number elements))))
  2807. (concat "(" elements ")"))
  2808. (if (or (not keep-empty) numbers) "(0)" "nan")))
  2809. ;; range reference
  2810. (unless keep-empty
  2811. (setq elements
  2812. (delq nil
  2813. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2814. elements))))
  2815. (setq elements (or elements '())) ; if delq returns nil then we need '()
  2816. (if lispp
  2817. (mapconcat
  2818. (lambda (x)
  2819. (if (eq lispp 'literal)
  2820. x
  2821. (prin1-to-string (if numbers (string-to-number x) x))))
  2822. elements " ")
  2823. (concat "[" (mapconcat
  2824. (lambda (x)
  2825. (if (string-match "\\S-" x)
  2826. (if numbers
  2827. (number-to-string (string-to-number x))
  2828. x)
  2829. (if (or (not keep-empty) numbers) "0" "nan")))
  2830. elements
  2831. ",") "]"))))
  2832. (defun org-table-message-once-per-second (t1 &rest args)
  2833. "If there has been more than one second since T1, display message.
  2834. ARGS are passed as arguments to the `message' function. Returns
  2835. current time if a message is printed, otherwise returns T1. If
  2836. T1 is nil, always messages."
  2837. (let ((curtime (current-time)))
  2838. (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
  2839. (progn (apply 'message args)
  2840. curtime)
  2841. t1)))
  2842. ;;;###autoload
  2843. (defun org-table-recalculate (&optional all noalign)
  2844. "Recalculate the current table line by applying all stored formulas.
  2845. With prefix arg ALL, do this for all lines in the table.
  2846. With the prefix argument ALL is `(16)' \
  2847. \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
  2848. it is the symbol `iterate', recompute the table until it no longer changes.
  2849. If NOALIGN is not nil, do not re-align the table after the computations
  2850. are done. This is typically used internally to save time, if it is
  2851. known that the table will be realigned a little later anyway."
  2852. (interactive "P")
  2853. (or (memq this-command org-recalc-commands)
  2854. (setq org-recalc-commands (cons this-command org-recalc-commands)))
  2855. (unless (org-at-table-p) (user-error "Not at a table"))
  2856. (if (or (eq all 'iterate) (equal all '(16)))
  2857. (org-table-iterate)
  2858. (org-table-get-specials)
  2859. (let* ((eqlist (sort (org-table-get-stored-formulas)
  2860. (lambda (a b) (string< (car a) (car b)))))
  2861. (eqlist1 (copy-sequence eqlist))
  2862. (inhibit-redisplay (not debug-on-error))
  2863. (line-re org-table-dataline-regexp)
  2864. (thisline (org-current-line))
  2865. (thiscol (org-table-current-column))
  2866. (log-first-time (current-time))
  2867. (log-last-time log-first-time)
  2868. seen-fields lhs1
  2869. beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
  2870. ;; Insert constants in all formulas
  2871. (when eqlist
  2872. (setq eqlist
  2873. (mapcar
  2874. (lambda (x)
  2875. (if (string-match "^@-?I+" (car x))
  2876. (user-error "Can't assign to hline relative reference"))
  2877. (when (string-match "\\`$[<>]" (car x))
  2878. (setq lhs1 (car x))
  2879. (setq x (cons (substring
  2880. (org-table-formula-handle-first/last-rc
  2881. (car x)) 1)
  2882. (cdr x)))
  2883. (if (assoc (car x) eqlist1)
  2884. (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
  2885. lhs1 (car x))))
  2886. (cons
  2887. (org-table-formula-handle-first/last-rc (car x))
  2888. (org-table-formula-substitute-names
  2889. (org-table-formula-handle-first/last-rc (cdr x)))))
  2890. eqlist))
  2891. ;; Split the equation list
  2892. (while (setq eq (pop eqlist))
  2893. (if (<= (string-to-char (car eq)) ?9)
  2894. (push eq eqlnum)
  2895. (push eq eqlname)))
  2896. (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
  2897. ;; Expand ranges in lhs of formulas
  2898. (setq eqlname (org-table-expand-lhs-ranges eqlname))
  2899. ;; Get the correct line range to process
  2900. (if all
  2901. (progn
  2902. (setq end (move-marker (make-marker) (1+ (org-table-end))))
  2903. (goto-char (setq beg (org-table-begin)))
  2904. (if (re-search-forward org-table-calculate-mark-regexp end t)
  2905. ;; This is a table with marked lines, compute selected lines
  2906. (setq line-re org-table-recalculate-regexp)
  2907. ;; Move forward to the first non-header line
  2908. (if (and (re-search-forward org-table-dataline-regexp end t)
  2909. (re-search-forward org-table-hline-regexp end t)
  2910. (re-search-forward org-table-dataline-regexp end t))
  2911. (setq beg (match-beginning 0))
  2912. nil))) ;; just leave beg where it is
  2913. (setq beg (point-at-bol)
  2914. end (move-marker (make-marker) (1+ (point-at-eol)))))
  2915. (goto-char beg)
  2916. ;; First find the named fields, and mark them untouchable.
  2917. ;; Also check if several field/range formulas try to set the same field.
  2918. (remove-text-properties beg end '(org-untouchable t))
  2919. (while (setq eq (pop eqlname))
  2920. (setq name (car eq)
  2921. a (assoc name org-table-named-field-locations))
  2922. (setq name1 name)
  2923. (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
  2924. (nth 2 a))))
  2925. (when (member name1 seen-fields)
  2926. (user-error "Several field/range formulas try to set %s" name1))
  2927. (push name1 seen-fields)
  2928. (and (not a)
  2929. (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
  2930. (setq a (list name
  2931. (condition-case nil
  2932. (aref org-table-dlines
  2933. (string-to-number (match-string 1 name)))
  2934. (error (user-error "Invalid row number in %s"
  2935. name)))
  2936. (string-to-number (match-string 2 name)))))
  2937. (when (and a (or all (equal (nth 1 a) thisline)))
  2938. (setq log-last-time
  2939. (org-table-message-once-per-second
  2940. (and all log-last-time)
  2941. "Re-applying formula to field: %s" name))
  2942. (org-goto-line (nth 1 a))
  2943. (org-table-goto-column (nth 2 a))
  2944. (push (append a (list (cdr eq))) eqlname1)
  2945. (org-table-put-field-property :org-untouchable t)))
  2946. (setq eqlname1 (nreverse eqlname1))
  2947. ;; Now evaluate the column formulas, but skip fields covered
  2948. ;; by field formulas
  2949. (goto-char beg)
  2950. (while (re-search-forward line-re end t)
  2951. (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
  2952. ;; Unprotected line, recalculate
  2953. (setq cnt (1+ cnt))
  2954. (and all (setq log-last-time
  2955. (org-table-message-once-per-second
  2956. log-last-time
  2957. "Re-applying formulas to full table...(line %d)" cnt)))
  2958. (setq org-last-recalc-line (org-current-line))
  2959. (setq eql eqlnum)
  2960. (while (setq entry (pop eql))
  2961. (org-goto-line org-last-recalc-line)
  2962. (org-table-goto-column (string-to-number (car entry)) nil 'force)
  2963. (unless (get-text-property (point) :org-untouchable)
  2964. (org-table-eval-formula
  2965. nil (cdr entry)
  2966. 'noalign 'nocst 'nostore 'noanalysis)))))
  2967. ;; Now evaluate the field formulas
  2968. (while (setq eq (pop eqlname1))
  2969. (setq log-last-time
  2970. (org-table-message-once-per-second
  2971. (and all log-last-time)
  2972. "Re-applying formula to field: %s" (car eq)))
  2973. (org-goto-line (nth 1 eq))
  2974. (let ((column-target (nth 2 eq)))
  2975. (when (> column-target 1000)
  2976. (user-error "Formula column target too large"))
  2977. (let* ((column-count (progn (end-of-line)
  2978. (1- (org-table-current-column))))
  2979. (create-new-column
  2980. (and (> column-target column-count)
  2981. (or (eq org-table-formula-create-columns t)
  2982. (and
  2983. (eq org-table-formula-create-columns 'warn)
  2984. (progn
  2985. (org-display-warning
  2986. "Out-of-bounds formula added columns")
  2987. t))
  2988. (and
  2989. (eq org-table-formula-create-columns 'prompt)
  2990. (yes-or-no-p
  2991. "Out-of-bounds formula. Add columns?"))))))
  2992. (org-table-goto-column column-target nil create-new-column))
  2993. (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
  2994. 'nostore 'noanalysis)))
  2995. (org-goto-line thisline)
  2996. (org-table-goto-column thiscol)
  2997. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  2998. (or noalign (and org-table-may-need-update (org-table-align))
  2999. (and all (org-table-message-once-per-second
  3000. log-first-time
  3001. "Re-applying formulas to %d lines...done" cnt)))
  3002. ;; back to initial position
  3003. (org-table-message-once-per-second
  3004. (and all log-first-time)
  3005. "Re-applying formulas...done")
  3006. (org-goto-line thisline)
  3007. (org-table-goto-column thiscol)
  3008. (or noalign (and org-table-may-need-update (org-table-align)))))))
  3009. ;;;###autoload
  3010. (defun org-table-iterate (&optional arg)
  3011. "Recalculate the table until it does not change anymore.
  3012. The maximum number of iterations is 10, but you can choose a different value
  3013. with the prefix ARG."
  3014. (interactive "P")
  3015. (let ((imax (if arg (prefix-numeric-value arg) 10))
  3016. (i 0)
  3017. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  3018. thistbl)
  3019. (catch 'exit
  3020. (while (< i imax)
  3021. (setq i (1+ i))
  3022. (org-table-recalculate 'all)
  3023. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  3024. (if (not (string= lasttbl thistbl))
  3025. (setq lasttbl thistbl)
  3026. (if (> i 1)
  3027. (message "Convergence after %d iterations" i)
  3028. (message "Table was already stable"))
  3029. (throw 'exit t)))
  3030. (user-error "No convergence after %d iterations" i))))
  3031. ;;;###autoload
  3032. (defun org-table-recalculate-buffer-tables ()
  3033. "Recalculate all tables in the current buffer."
  3034. (interactive)
  3035. (save-excursion
  3036. (save-restriction
  3037. (widen)
  3038. (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
  3039. ;;;###autoload
  3040. (defun org-table-iterate-buffer-tables ()
  3041. "Iterate all tables in the buffer, to converge inter-table dependencies."
  3042. (interactive)
  3043. (let* ((imax 10)
  3044. (i imax)
  3045. (checksum (md5 (buffer-string)))
  3046. c1)
  3047. (save-excursion
  3048. (save-restriction
  3049. (widen)
  3050. (catch 'exit
  3051. (while (> i 0)
  3052. (setq i (1- i))
  3053. (org-table-map-tables (lambda () (org-table-recalculate t)) t)
  3054. (if (equal checksum (setq c1 (md5 (buffer-string))))
  3055. (progn
  3056. (message "Convergence after %d iterations" (- imax i))
  3057. (throw 'exit t))
  3058. (setq checksum c1)))
  3059. (user-error "No convergence after %d iterations" imax))))))
  3060. (defun org-table-calc-current-TBLFM (&optional arg)
  3061. "Apply the #+TBLFM in the line at point to the table."
  3062. (interactive "P")
  3063. (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
  3064. (let ((formula (buffer-substring
  3065. (point-at-bol)
  3066. (point-at-eol)))
  3067. s e)
  3068. (save-excursion
  3069. ;; Insert a temporary formula at right after the table
  3070. (goto-char (org-table-TBLFM-begin))
  3071. (setq s (set-marker (make-marker) (point)))
  3072. (insert (concat formula "\n"))
  3073. (setq e (set-marker (make-marker) (point)))
  3074. ;; Recalculate the table
  3075. (beginning-of-line 0) ; move to the inserted line
  3076. (skip-chars-backward " \r\n\t")
  3077. (if (org-at-table-p)
  3078. (unwind-protect
  3079. (org-call-with-arg 'org-table-recalculate (or arg t))
  3080. ;; delete the formula inserted temporarily
  3081. (delete-region s e))))))
  3082. (defun org-table-TBLFM-begin ()
  3083. "Find the beginning of the TBLFM lines and return its position.
  3084. Return nil when the beginning of TBLFM line was not found."
  3085. (save-excursion
  3086. (when (progn (forward-line 1)
  3087. (re-search-backward
  3088. org-table-TBLFM-begin-regexp
  3089. nil t))
  3090. (point-at-bol 2))))
  3091. (defun org-table-expand-lhs-ranges (equations)
  3092. "Expand list of formulas.
  3093. If some of the RHS in the formulas are ranges or a row reference, expand
  3094. them to individual field equations for each field."
  3095. (let (e res lhs rhs range r1 r2 c1 c2)
  3096. (while (setq e (pop equations))
  3097. (setq lhs (car e) rhs (cdr e))
  3098. (cond
  3099. ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
  3100. ;; This just refers to one fixed field
  3101. (push e res))
  3102. ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
  3103. ;; This just refers to one fixed named field
  3104. (push e res))
  3105. ((string-match "^@[0-9]+$" lhs)
  3106. (loop for ic from 1 to org-table-current-ncol do
  3107. (push (cons (format "%s$%d" lhs ic) rhs) res)
  3108. (put-text-property 0 (length (caar res))
  3109. :orig-eqn e (caar res))))
  3110. (t
  3111. (setq range (org-table-get-range lhs org-table-current-begin-pos
  3112. 1 nil 'corners))
  3113. (setq r1 (nth 0 range) c1 (nth 1 range)
  3114. r2 (nth 2 range) c2 (nth 3 range))
  3115. (setq r1 (org-table-line-to-dline r1))
  3116. (setq r2 (org-table-line-to-dline r2 'above))
  3117. (loop for ir from r1 to r2 do
  3118. (loop for ic from c1 to c2 do
  3119. (push (cons (format "@%d$%d" ir ic) rhs) res)
  3120. (put-text-property 0 (length (caar res))
  3121. :orig-eqn e (caar res)))))))
  3122. (nreverse res)))
  3123. (defun org-table-formula-handle-first/last-rc (s)
  3124. "Replace @<, @>, $<, $> with first/last row/column of the table.
  3125. So @< and $< will always be replaced with @1 and $1, respectively.
  3126. The advantage of these special markers are that structure editing of
  3127. the table will not change them, while @1 and $1 will be modified
  3128. when a line/row is swapped out of that privileged position. So for
  3129. formulas that use a range of rows or columns, it may often be better
  3130. to anchor the formula with \"I\" row markers, or to offset from the
  3131. borders of the table using the @< @> $< $> makers."
  3132. (let (n nmax len char (start 0))
  3133. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
  3134. s start)
  3135. (if (match-end 3)
  3136. (setq start (match-end 3))
  3137. (setq nmax (if (equal (match-string 1 s) "@")
  3138. (1- (length org-table-dlines))
  3139. org-table-current-ncol)
  3140. len (- (match-end 2) (match-beginning 2))
  3141. char (string-to-char (match-string 2 s))
  3142. n (if (= char ?<)
  3143. len
  3144. (- nmax len -1)))
  3145. (if (or (< n 1) (> n nmax))
  3146. (user-error "Reference \"%s\" in expression \"%s\" points outside table"
  3147. (match-string 0 s) s))
  3148. (setq start (match-beginning 0))
  3149. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
  3150. s)
  3151. (defun org-table-formula-substitute-names (f)
  3152. "Replace $const with values in string F."
  3153. (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
  3154. ;; First, check for column names
  3155. (while (setq start (string-match org-table-column-name-regexp f start))
  3156. (setq start (1+ start))
  3157. (setq a (assoc (match-string 1 f) org-table-column-names))
  3158. (setq f (replace-match (concat "$" (cdr a)) t t f)))
  3159. ;; Parameters and constants
  3160. (setq start 0)
  3161. (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
  3162. (if (match-end 2)
  3163. (setq start (match-end 2))
  3164. (setq start (1+ start))
  3165. (if (setq a (save-match-data
  3166. (org-table-get-constant (match-string 1 f))))
  3167. (setq f (replace-match
  3168. (concat (if pp "(") a (if pp ")")) t t f)))))
  3169. (if org-table-formula-debug
  3170. (put-text-property 0 (length f) :orig-formula f1 f))
  3171. f))
  3172. (defun org-table-get-constant (const)
  3173. "Find the value for a parameter or constant in a formula.
  3174. Parameters get priority."
  3175. (or (cdr (assoc const org-table-local-parameters))
  3176. (cdr (assoc const org-table-formula-constants-local))
  3177. (cdr (assoc const org-table-formula-constants))
  3178. (and (fboundp 'constants-get) (constants-get const))
  3179. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  3180. (org-entry-get nil (substring const 5) 'inherit))
  3181. "#UNDEFINED_NAME"))
  3182. (defvar org-table-fedit-map
  3183. (let ((map (make-sparse-keymap)))
  3184. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  3185. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  3186. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  3187. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  3188. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  3189. (org-defkey map "\C-c?" 'org-table-show-reference)
  3190. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  3191. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  3192. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  3193. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  3194. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  3195. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  3196. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  3197. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  3198. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  3199. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  3200. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  3201. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  3202. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  3203. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  3204. map))
  3205. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
  3206. '("Edit-Formulas"
  3207. ["Finish and Install" org-table-fedit-finish t]
  3208. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  3209. ["Abort" org-table-fedit-abort t]
  3210. "--"
  3211. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  3212. ["Complete Lisp Symbol" lisp-complete-symbol t]
  3213. "--"
  3214. "Shift Reference at Point"
  3215. ["Up" org-table-fedit-ref-up t]
  3216. ["Down" org-table-fedit-ref-down t]
  3217. ["Left" org-table-fedit-ref-left t]
  3218. ["Right" org-table-fedit-ref-right t]
  3219. "-"
  3220. "Change Test Row for Column Formulas"
  3221. ["Up" org-table-fedit-line-up t]
  3222. ["Down" org-table-fedit-line-down t]
  3223. "--"
  3224. ["Scroll Table Window" org-table-fedit-scroll t]
  3225. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  3226. ["Show Table Grid" org-table-fedit-toggle-coordinates
  3227. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  3228. org-table-overlay-coordinates)]
  3229. "--"
  3230. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  3231. :style toggle :selected org-table-buffer-is-an]))
  3232. (defvar org-pos)
  3233. ;;;###autoload
  3234. (defun org-table-edit-formulas ()
  3235. "Edit the formulas of the current table in a separate buffer."
  3236. (interactive)
  3237. (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
  3238. (beginning-of-line 0))
  3239. (unless (org-at-table-p) (user-error "Not at a table"))
  3240. (org-table-get-specials)
  3241. (let ((key (org-table-current-field-formula 'key 'noerror))
  3242. (eql (sort (org-table-get-stored-formulas 'noerror)
  3243. 'org-table-formula-less-p))
  3244. (pos (point-marker))
  3245. (startline 1)
  3246. (wc (current-window-configuration))
  3247. (sel-win (selected-window))
  3248. (titles '((column . "# Column Formulas\n")
  3249. (field . "# Field and Range Formulas\n")
  3250. (named . "# Named Field Formulas\n")))
  3251. entry s type title)
  3252. (org-switch-to-buffer-other-window "*Edit Formulas*")
  3253. (erase-buffer)
  3254. ;; Keep global-font-lock-mode from turning on font-lock-mode
  3255. (let ((font-lock-global-modes '(not fundamental-mode)))
  3256. (fundamental-mode))
  3257. (org-set-local 'font-lock-global-modes (list 'not major-mode))
  3258. (org-set-local 'org-pos pos)
  3259. (org-set-local 'org-window-configuration wc)
  3260. (org-set-local 'org-selected-window sel-win)
  3261. (use-local-map org-table-fedit-map)
  3262. (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
  3263. (easy-menu-add org-table-fedit-menu)
  3264. (setq startline (org-current-line))
  3265. (while (setq entry (pop eql))
  3266. (setq type (cond
  3267. ((string-match "\\`$[<>]" (car entry)) 'column)
  3268. ((equal (string-to-char (car entry)) ?@) 'field)
  3269. ((string-match "^[0-9]" (car entry)) 'column)
  3270. (t 'named)))
  3271. (when (setq title (assq type titles))
  3272. (or (bobp) (insert "\n"))
  3273. (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
  3274. (setq titles (remove title titles)))
  3275. (if (equal key (car entry)) (setq startline (org-current-line)))
  3276. (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
  3277. (car entry) " = " (cdr entry) "\n"))
  3278. (remove-text-properties 0 (length s) '(face nil) s)
  3279. (insert s))
  3280. (if (eq org-table-use-standard-references t)
  3281. (org-table-fedit-toggle-ref-type))
  3282. (org-goto-line startline)
  3283. (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
  3284. (defun org-table-fedit-post-command ()
  3285. (when (not (memq this-command '(lisp-complete-symbol)))
  3286. (let ((win (selected-window)))
  3287. (save-excursion
  3288. (condition-case nil
  3289. (org-table-show-reference)
  3290. (error nil))
  3291. (select-window win)))))
  3292. (defun org-table-formula-to-user (s)
  3293. "Convert a formula from internal to user representation."
  3294. (if (eq org-table-use-standard-references t)
  3295. (org-table-convert-refs-to-an s)
  3296. s))
  3297. (defun org-table-formula-from-user (s)
  3298. "Convert a formula from user to internal representation."
  3299. (if org-table-use-standard-references
  3300. (org-table-convert-refs-to-rc s)
  3301. s))
  3302. (defun org-table-convert-refs-to-rc (s)
  3303. "Convert spreadsheet references from A7 to @7$28.
  3304. Works for single references, but also for entire formulas and even the
  3305. full TBLFM line."
  3306. (let ((start 0))
  3307. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
  3308. (cond
  3309. ((match-end 3)
  3310. ;; format match, just advance
  3311. (setq start (match-end 0)))
  3312. ((and (> (match-beginning 0) 0)
  3313. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  3314. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  3315. ;; 3.e5 or something like this.
  3316. (setq start (match-end 0)))
  3317. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  3318. ;; (member (match-string 1 s)
  3319. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  3320. )
  3321. ;; function name, just advance
  3322. (setq start (match-end 0)))
  3323. (t
  3324. (setq start (match-beginning 0)
  3325. s (replace-match
  3326. (if (equal (match-string 2 s) "&")
  3327. (format "$%d" (org-letters-to-number (match-string 1 s)))
  3328. (format "@%d$%d"
  3329. (string-to-number (match-string 2 s))
  3330. (org-letters-to-number (match-string 1 s))))
  3331. t t s)))))
  3332. s))
  3333. (defun org-table-convert-refs-to-an (s)
  3334. "Convert spreadsheet references from to @7$28 to AB7.
  3335. Works for single references, but also for entire formulas and even the
  3336. full TBLFM line."
  3337. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  3338. (setq s (replace-match
  3339. (format "%s%d"
  3340. (org-number-to-letters
  3341. (string-to-number (match-string 2 s)))
  3342. (string-to-number (match-string 1 s)))
  3343. t t s)))
  3344. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  3345. (setq s (replace-match (concat "\\1"
  3346. (org-number-to-letters
  3347. (string-to-number (match-string 2 s))) "&")
  3348. t nil s)))
  3349. s)
  3350. (defun org-letters-to-number (s)
  3351. "Convert a base 26 number represented by letters into an integer.
  3352. For example: AB -> 28."
  3353. (let ((n 0))
  3354. (setq s (upcase s))
  3355. (while (> (length s) 0)
  3356. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3357. s (substring s 1)))
  3358. n))
  3359. (defun org-number-to-letters (n)
  3360. "Convert an integer into a base 26 number represented by letters.
  3361. For example: 28 -> AB."
  3362. (let ((s ""))
  3363. (while (> n 0)
  3364. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3365. n (/ (1- n) 26)))
  3366. s))
  3367. (defun org-table-time-string-to-seconds (s)
  3368. "Convert a time string into numerical duration in seconds.
  3369. S can be a string matching either -?HH:MM:SS or -?HH:MM.
  3370. If S is a string representing a number, keep this number."
  3371. (if (equal s "")
  3372. s
  3373. (let (hour minus min sec res)
  3374. (cond
  3375. ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3376. (setq minus (< 0 (length (match-string 1 s)))
  3377. hour (string-to-number (match-string 2 s))
  3378. min (string-to-number (match-string 3 s))
  3379. sec (string-to-number (match-string 4 s)))
  3380. (if minus
  3381. (setq res (- (+ (* hour 3600) (* min 60) sec)))
  3382. (setq res (+ (* hour 3600) (* min 60) sec))))
  3383. ((and (not (string-match org-ts-regexp-both s))
  3384. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3385. (setq minus (< 0 (length (match-string 1 s)))
  3386. hour (string-to-number (match-string 2 s))
  3387. min (string-to-number (match-string 3 s)))
  3388. (if minus
  3389. (setq res (- (+ (* hour 3600) (* min 60))))
  3390. (setq res (+ (* hour 3600) (* min 60)))))
  3391. (t (setq res (string-to-number s))))
  3392. (number-to-string res))))
  3393. (defun org-table-time-seconds-to-string (secs &optional output-format)
  3394. "Convert a number of seconds to a time string.
  3395. If OUTPUT-FORMAT is non-nil, return a number of days, hours,
  3396. minutes or seconds."
  3397. (let* ((secs0 (abs secs))
  3398. (res
  3399. (cond ((eq output-format 'days)
  3400. (format "%.3f" (/ (float secs0) 86400)))
  3401. ((eq output-format 'hours)
  3402. (format "%.2f" (/ (float secs0) 3600)))
  3403. ((eq output-format 'minutes)
  3404. (format "%.1f" (/ (float secs0) 60)))
  3405. ((eq output-format 'seconds)
  3406. (format "%d" secs0))
  3407. (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
  3408. (if (< secs 0) (concat "-" res) res)))
  3409. (defun org-table-fedit-convert-buffer (function)
  3410. "Convert all references in this buffer, using FUNCTION."
  3411. (let ((line (org-current-line)))
  3412. (goto-char (point-min))
  3413. (while (not (eobp))
  3414. (insert (funcall function (buffer-substring (point) (point-at-eol))))
  3415. (delete-region (point) (point-at-eol))
  3416. (or (eobp) (forward-char 1)))
  3417. (org-goto-line line)))
  3418. (defun org-table-fedit-toggle-ref-type ()
  3419. "Convert all references in the buffer from B3 to @3$2 and back."
  3420. (interactive)
  3421. (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
  3422. (org-table-fedit-convert-buffer
  3423. (if org-table-buffer-is-an
  3424. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3425. (message "Reference type switched to %s"
  3426. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3427. (defun org-table-fedit-ref-up ()
  3428. "Shift the reference at point one row/hline up."
  3429. (interactive)
  3430. (org-table-fedit-shift-reference 'up))
  3431. (defun org-table-fedit-ref-down ()
  3432. "Shift the reference at point one row/hline down."
  3433. (interactive)
  3434. (org-table-fedit-shift-reference 'down))
  3435. (defun org-table-fedit-ref-left ()
  3436. "Shift the reference at point one field to the left."
  3437. (interactive)
  3438. (org-table-fedit-shift-reference 'left))
  3439. (defun org-table-fedit-ref-right ()
  3440. "Shift the reference at point one field to the right."
  3441. (interactive)
  3442. (org-table-fedit-shift-reference 'right))
  3443. (defun org-table-fedit-shift-reference (dir)
  3444. (cond
  3445. ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
  3446. (if (memq dir '(left right))
  3447. (org-rematch-and-replace 1 (eq dir 'left))
  3448. (user-error "Cannot shift reference in this direction")))
  3449. ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3450. ;; A B3-like reference
  3451. (if (memq dir '(up down))
  3452. (org-rematch-and-replace 2 (eq dir 'up))
  3453. (org-rematch-and-replace 1 (eq dir 'left))))
  3454. ((org-at-regexp-p
  3455. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3456. ;; An internal reference
  3457. (if (memq dir '(up down))
  3458. (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3459. (org-rematch-and-replace 5 (eq dir 'left))))))
  3460. (defun org-rematch-and-replace (n &optional decr hline)
  3461. "Re-match the group N, and replace it with the shifted reference."
  3462. (or (match-end n) (user-error "Cannot shift reference in this direction"))
  3463. (goto-char (match-beginning n))
  3464. (and (looking-at (regexp-quote (match-string n)))
  3465. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  3466. t t)))
  3467. (defun org-table-shift-refpart (ref &optional decr hline)
  3468. "Shift a reference part REF.
  3469. If DECR is set, decrease the references row/column, else increase.
  3470. If HLINE is set, this may be a hline reference, it certainly is not
  3471. a translation reference."
  3472. (save-match-data
  3473. (let* ((sign (string-match "^[-+]" ref)) n)
  3474. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  3475. (cond
  3476. ((and hline (string-match "^I+" ref))
  3477. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  3478. (setq n (+ n (if decr -1 1)))
  3479. (if (= n 0) (setq n (+ n (if decr -1 1))))
  3480. (if sign
  3481. (setq sign (if (< n 0) "-" "+") n (abs n))
  3482. (setq n (max 1 n)))
  3483. (concat sign (make-string n ?I)))
  3484. ((string-match "^[0-9]+" ref)
  3485. (setq n (string-to-number (concat sign ref)))
  3486. (setq n (+ n (if decr -1 1)))
  3487. (if sign
  3488. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  3489. (number-to-string (max 1 n))))
  3490. ((string-match "^[a-zA-Z]+" ref)
  3491. (org-number-to-letters
  3492. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  3493. (t (user-error "Cannot shift reference"))))))
  3494. (defun org-table-fedit-toggle-coordinates ()
  3495. "Toggle the display of coordinates in the referenced table."
  3496. (interactive)
  3497. (let ((pos (marker-position org-pos)))
  3498. (with-current-buffer (marker-buffer org-pos)
  3499. (save-excursion
  3500. (goto-char pos)
  3501. (org-table-toggle-coordinate-overlays)))))
  3502. (defun org-table-fedit-finish (&optional arg)
  3503. "Parse the buffer for formula definitions and install them.
  3504. With prefix ARG, apply the new formulas to the table."
  3505. (interactive "P")
  3506. (org-table-remove-rectangle-highlight)
  3507. (if org-table-use-standard-references
  3508. (progn
  3509. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  3510. (setq org-table-buffer-is-an nil)))
  3511. (let ((pos org-pos) (sel-win org-selected-window) eql var form)
  3512. (goto-char (point-min))
  3513. (while (re-search-forward
  3514. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  3515. nil t)
  3516. (setq var (if (match-end 2) (match-string 2) (match-string 1))
  3517. form (match-string 3))
  3518. (setq form (org-trim form))
  3519. (when (not (equal form ""))
  3520. (while (string-match "[ \t]*\n[ \t]*" form)
  3521. (setq form (replace-match " " t t form)))
  3522. (when (assoc var eql)
  3523. (user-error "Double formulas for %s" var))
  3524. (push (cons var form) eql)))
  3525. (setq org-pos nil)
  3526. (set-window-configuration org-window-configuration)
  3527. (select-window sel-win)
  3528. (goto-char pos)
  3529. (unless (org-at-table-p)
  3530. (user-error "Lost table position - cannot install formulas"))
  3531. (org-table-store-formulas eql)
  3532. (move-marker pos nil)
  3533. (kill-buffer "*Edit Formulas*")
  3534. (if arg
  3535. (org-table-recalculate 'all)
  3536. (message "New formulas installed - press C-u C-c C-c to apply."))))
  3537. (defun org-table-fedit-abort ()
  3538. "Abort editing formulas, without installing the changes."
  3539. (interactive)
  3540. (org-table-remove-rectangle-highlight)
  3541. (let ((pos org-pos) (sel-win org-selected-window))
  3542. (set-window-configuration org-window-configuration)
  3543. (select-window sel-win)
  3544. (goto-char pos)
  3545. (move-marker pos nil)
  3546. (message "Formula editing aborted without installing changes")))
  3547. (defun org-table-fedit-lisp-indent ()
  3548. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  3549. (interactive)
  3550. (let ((pos (point)) beg end ind)
  3551. (beginning-of-line 1)
  3552. (cond
  3553. ((looking-at "[ \t]")
  3554. (goto-char pos)
  3555. (call-interactively 'lisp-indent-line))
  3556. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  3557. ((not (fboundp 'pp-buffer))
  3558. (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
  3559. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  3560. (goto-char (- (match-end 0) 2))
  3561. (setq beg (point))
  3562. (setq ind (make-string (current-column) ?\ ))
  3563. (condition-case nil (forward-sexp 1)
  3564. (error
  3565. (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  3566. (setq end (point))
  3567. (save-restriction
  3568. (narrow-to-region beg end)
  3569. (if (eq last-command this-command)
  3570. (progn
  3571. (goto-char (point-min))
  3572. (setq this-command nil)
  3573. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  3574. (replace-match " ")))
  3575. (pp-buffer)
  3576. (untabify (point-min) (point-max))
  3577. (goto-char (1+ (point-min)))
  3578. (while (re-search-forward "^." nil t)
  3579. (beginning-of-line 1)
  3580. (insert ind))
  3581. (goto-char (point-max))
  3582. (org-delete-backward-char 1)))
  3583. (goto-char beg))
  3584. (t nil))))
  3585. (defvar org-show-positions nil)
  3586. (defun org-table-show-reference (&optional local)
  3587. "Show the location/value of the $ expression at point."
  3588. (interactive)
  3589. (org-table-remove-rectangle-highlight)
  3590. (catch 'exit
  3591. (let ((pos (if local (point) org-pos))
  3592. (face2 'highlight)
  3593. (org-inhibit-highlight-removal t)
  3594. (win (selected-window))
  3595. (org-show-positions nil)
  3596. var name e what match dest)
  3597. (if local (org-table-get-specials))
  3598. (setq what (cond
  3599. ((org-at-regexp-p "^@[0-9]+[ \t=]")
  3600. (setq match (concat (substring (match-string 0) 0 -1)
  3601. "$1.."
  3602. (substring (match-string 0) 0 -1)
  3603. "$100"))
  3604. 'range)
  3605. ((or (org-at-regexp-p org-table-range-regexp2)
  3606. (org-at-regexp-p org-table-translate-regexp)
  3607. (org-at-regexp-p org-table-range-regexp))
  3608. (setq match
  3609. (save-match-data
  3610. (org-table-convert-refs-to-rc (match-string 0))))
  3611. 'range)
  3612. ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  3613. ((org-at-regexp-p "\\$[0-9]+") 'column)
  3614. ((not local) nil)
  3615. (t (user-error "No reference at point")))
  3616. match (and what (or match (match-string 0))))
  3617. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  3618. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  3619. 'secondary-selection))
  3620. (org-add-hook 'before-change-functions
  3621. 'org-table-remove-rectangle-highlight)
  3622. (if (eq what 'name) (setq var (substring match 1)))
  3623. (when (eq what 'range)
  3624. (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
  3625. (setq match (org-table-formula-substitute-names match)))
  3626. (unless local
  3627. (save-excursion
  3628. (end-of-line 1)
  3629. (re-search-backward "^\\S-" nil t)
  3630. (beginning-of-line 1)
  3631. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
  3632. (setq dest
  3633. (save-match-data
  3634. (org-table-convert-refs-to-rc (match-string 1))))
  3635. (org-table-add-rectangle-overlay
  3636. (match-beginning 1) (match-end 1) face2))))
  3637. (if (and (markerp pos) (marker-buffer pos))
  3638. (if (get-buffer-window (marker-buffer pos))
  3639. (select-window (get-buffer-window (marker-buffer pos)))
  3640. (org-switch-to-buffer-other-window (get-buffer-window
  3641. (marker-buffer pos)))))
  3642. (goto-char pos)
  3643. (org-table-force-dataline)
  3644. (when dest
  3645. (setq name (substring dest 1))
  3646. (cond
  3647. ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  3648. (setq e (assoc name org-table-named-field-locations))
  3649. (org-goto-line (nth 1 e))
  3650. (org-table-goto-column (nth 2 e)))
  3651. ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
  3652. (let ((l (string-to-number (match-string 1 dest)))
  3653. (c (string-to-number (match-string 2 dest))))
  3654. (org-goto-line (aref org-table-dlines l))
  3655. (org-table-goto-column c)))
  3656. (t (org-table-goto-column (string-to-number name))))
  3657. (move-marker pos (point))
  3658. (org-table-highlight-rectangle nil nil face2))
  3659. (cond
  3660. ((equal dest match))
  3661. ((not match))
  3662. ((eq what 'range)
  3663. (condition-case nil
  3664. (save-excursion
  3665. (org-table-get-range match nil nil 'highlight))
  3666. (error nil)))
  3667. ((setq e (assoc var org-table-named-field-locations))
  3668. (org-goto-line (nth 1 e))
  3669. (org-table-goto-column (nth 2 e))
  3670. (org-table-highlight-rectangle (point) (point))
  3671. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  3672. ((setq e (assoc var org-table-column-names))
  3673. (org-table-goto-column (string-to-number (cdr e)))
  3674. (org-table-highlight-rectangle (point) (point))
  3675. (goto-char (org-table-begin))
  3676. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  3677. (org-table-end) t)
  3678. (progn
  3679. (goto-char (match-beginning 1))
  3680. (org-table-highlight-rectangle)
  3681. (message "Named column (column %s)" (cdr e)))
  3682. (user-error "Column name not found")))
  3683. ((eq what 'column)
  3684. ;; column number
  3685. (org-table-goto-column (string-to-number (substring match 1)))
  3686. (org-table-highlight-rectangle (point) (point))
  3687. (message "Column %s" (substring match 1)))
  3688. ((setq e (assoc var org-table-local-parameters))
  3689. (goto-char (org-table-begin))
  3690. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  3691. (progn
  3692. (goto-char (match-beginning 1))
  3693. (org-table-highlight-rectangle)
  3694. (message "Local parameter."))
  3695. (user-error "Parameter not found")))
  3696. (t
  3697. (cond
  3698. ((not var) (user-error "No reference at point"))
  3699. ((setq e (assoc var org-table-formula-constants-local))
  3700. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  3701. var (cdr e)))
  3702. ((setq e (assoc var org-table-formula-constants))
  3703. (message "Constant: $%s=%s in `org-table-formula-constants'."
  3704. var (cdr e)))
  3705. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  3706. (message "Constant: $%s=%s, from `constants.el'%s."
  3707. var e (format " (%s units)" constants-unit-system)))
  3708. (t (user-error "Undefined name $%s" var)))))
  3709. (goto-char pos)
  3710. (when (and org-show-positions
  3711. (not (memq this-command '(org-table-fedit-scroll
  3712. org-table-fedit-scroll-down))))
  3713. (push pos org-show-positions)
  3714. (push org-table-current-begin-pos org-show-positions)
  3715. (let ((min (apply 'min org-show-positions))
  3716. (max (apply 'max org-show-positions)))
  3717. (set-window-start (selected-window) min)
  3718. (goto-char max)
  3719. (or (pos-visible-in-window-p max)
  3720. (set-window-start (selected-window) max))))
  3721. (select-window win))))
  3722. (defun org-table-force-dataline ()
  3723. "Make sure the cursor is in a dataline in a table."
  3724. (unless (save-excursion
  3725. (beginning-of-line 1)
  3726. (looking-at org-table-dataline-regexp))
  3727. (let* ((re org-table-dataline-regexp)
  3728. (p1 (save-excursion (re-search-forward re nil 'move)))
  3729. (p2 (save-excursion (re-search-backward re nil 'move))))
  3730. (cond ((and p1 p2)
  3731. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  3732. p1 p2)))
  3733. ((or p1 p2) (goto-char (or p1 p2)))
  3734. (t (user-error "No table dataline around here"))))))
  3735. (defun org-table-fedit-line-up ()
  3736. "Move cursor one line up in the window showing the table."
  3737. (interactive)
  3738. (org-table-fedit-move 'previous-line))
  3739. (defun org-table-fedit-line-down ()
  3740. "Move cursor one line down in the window showing the table."
  3741. (interactive)
  3742. (org-table-fedit-move 'next-line))
  3743. (defun org-table-fedit-move (command)
  3744. "Move the cursor in the window showing the table.
  3745. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  3746. (let ((org-table-allow-automatic-line-recalculation nil)
  3747. (pos org-pos) (win (selected-window)) p)
  3748. (select-window (get-buffer-window (marker-buffer org-pos)))
  3749. (setq p (point))
  3750. (call-interactively command)
  3751. (while (and (org-at-table-p)
  3752. (org-at-table-hline-p))
  3753. (call-interactively command))
  3754. (or (org-at-table-p) (goto-char p))
  3755. (move-marker pos (point))
  3756. (select-window win)))
  3757. (defun org-table-fedit-scroll (N)
  3758. (interactive "p")
  3759. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  3760. (scroll-other-window N)))
  3761. (defun org-table-fedit-scroll-down (N)
  3762. (interactive "p")
  3763. (org-table-fedit-scroll (- N)))
  3764. (defvar org-table-rectangle-overlays nil)
  3765. (defun org-table-add-rectangle-overlay (beg end &optional face)
  3766. "Add a new overlay."
  3767. (let ((ov (make-overlay beg end)))
  3768. (overlay-put ov 'face (or face 'secondary-selection))
  3769. (push ov org-table-rectangle-overlays)))
  3770. (defun org-table-highlight-rectangle (&optional beg end face)
  3771. "Highlight rectangular region in a table."
  3772. (setq beg (or beg (point)) end (or end (point)))
  3773. (let ((b (min beg end))
  3774. (e (max beg end))
  3775. l1 c1 l2 c2 tmp)
  3776. (and (boundp 'org-show-positions)
  3777. (setq org-show-positions (cons b (cons e org-show-positions))))
  3778. (goto-char (min beg end))
  3779. (setq l1 (org-current-line)
  3780. c1 (org-table-current-column))
  3781. (goto-char (max beg end))
  3782. (setq l2 (org-current-line)
  3783. c2 (org-table-current-column))
  3784. (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
  3785. (org-goto-line l1)
  3786. (beginning-of-line 1)
  3787. (loop for line from l1 to l2 do
  3788. (when (looking-at org-table-dataline-regexp)
  3789. (org-table-goto-column c1)
  3790. (skip-chars-backward "^|\n") (setq beg (point))
  3791. (org-table-goto-column c2)
  3792. (skip-chars-forward "^|\n") (setq end (point))
  3793. (org-table-add-rectangle-overlay beg end face))
  3794. (beginning-of-line 2))
  3795. (goto-char b))
  3796. (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
  3797. (defun org-table-remove-rectangle-highlight (&rest ignore)
  3798. "Remove the rectangle overlays."
  3799. (unless org-inhibit-highlight-removal
  3800. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  3801. (mapc 'delete-overlay org-table-rectangle-overlays)
  3802. (setq org-table-rectangle-overlays nil)))
  3803. (defvar org-table-coordinate-overlays nil
  3804. "Collects the coordinate grid overlays, so that they can be removed.")
  3805. (make-variable-buffer-local 'org-table-coordinate-overlays)
  3806. (defun org-table-overlay-coordinates ()
  3807. "Add overlays to the table at point, to show row/column coordinates."
  3808. (interactive)
  3809. (mapc 'delete-overlay org-table-coordinate-overlays)
  3810. (setq org-table-coordinate-overlays nil)
  3811. (save-excursion
  3812. (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
  3813. (goto-char (org-table-begin))
  3814. (while (org-at-table-p)
  3815. (setq eol (point-at-eol))
  3816. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  3817. (push ov org-table-coordinate-overlays)
  3818. (setq hline (looking-at org-table-hline-regexp))
  3819. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  3820. (format "%4d" (setq id (1+ id)))))
  3821. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  3822. (when hline
  3823. (setq ic 0)
  3824. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  3825. (setq beg (1+ (match-beginning 0))
  3826. ic (1+ ic)
  3827. s1 (concat "$" (int-to-string ic))
  3828. s2 (org-number-to-letters ic)
  3829. str (if (eq org-table-use-standard-references t) s2 s1))
  3830. (setq ov (make-overlay beg (+ beg (length str))))
  3831. (push ov org-table-coordinate-overlays)
  3832. (org-overlay-display ov str 'org-special-keyword 'evaporate)))
  3833. (beginning-of-line 2)))))
  3834. ;;;###autoload
  3835. (defun org-table-toggle-coordinate-overlays ()
  3836. "Toggle the display of Row/Column numbers in tables."
  3837. (interactive)
  3838. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  3839. (message "Tables Row/Column numbers display turned %s"
  3840. (if org-table-overlay-coordinates "on" "off"))
  3841. (if (and (org-at-table-p) org-table-overlay-coordinates)
  3842. (org-table-align))
  3843. (unless org-table-overlay-coordinates
  3844. (mapc 'delete-overlay org-table-coordinate-overlays)
  3845. (setq org-table-coordinate-overlays nil)))
  3846. ;;;###autoload
  3847. (defun org-table-toggle-formula-debugger ()
  3848. "Toggle the formula debugger in tables."
  3849. (interactive)
  3850. (setq org-table-formula-debug (not org-table-formula-debug))
  3851. (message "Formula debugging has been turned %s"
  3852. (if org-table-formula-debug "on" "off")))
  3853. ;;; The orgtbl minor mode
  3854. ;; Define a minor mode which can be used in other modes in order to
  3855. ;; integrate the org-mode table editor.
  3856. ;; This is really a hack, because the org-mode table editor uses several
  3857. ;; keys which normally belong to the major mode, for example the TAB and
  3858. ;; RET keys. Here is how it works: The minor mode defines all the keys
  3859. ;; necessary to operate the table editor, but wraps the commands into a
  3860. ;; function which tests if the cursor is currently inside a table. If that
  3861. ;; is the case, the table editor command is executed. However, when any of
  3862. ;; those keys is used outside a table, the function uses `key-binding' to
  3863. ;; look up if the key has an associated command in another currently active
  3864. ;; keymap (minor modes, major mode, global), and executes that command.
  3865. ;; There might be problems if any of the keys used by the table editor is
  3866. ;; otherwise used as a prefix key.
  3867. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  3868. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  3869. ;; addresses this by checking explicitly for both bindings.
  3870. ;; The optimized version (see variable `orgtbl-optimized') takes over
  3871. ;; all keys which are bound to `self-insert-command' in the *global map*.
  3872. ;; Some modes bind other commands to simple characters, for example
  3873. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  3874. ;; active, this binding is ignored inside tables and replaced with a
  3875. ;; modified self-insert.
  3876. (defvar orgtbl-mode-map (make-keymap)
  3877. "Keymap for `orgtbl-mode'.")
  3878. (defvar org-old-auto-fill-inhibit-regexp nil
  3879. "Local variable used by `orgtbl-mode'.")
  3880. (defconst orgtbl-line-start-regexp
  3881. "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
  3882. "Matches a line belonging to an orgtbl.")
  3883. (defconst orgtbl-extra-font-lock-keywords
  3884. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  3885. 0 (quote 'org-table) 'prepend))
  3886. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  3887. ;; Install it as a minor mode.
  3888. (put 'orgtbl-mode :included t)
  3889. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  3890. ;;;###autoload
  3891. (define-minor-mode orgtbl-mode
  3892. "The `org-mode' table editor as a minor mode for use in other modes."
  3893. :lighter " OrgTbl" :keymap orgtbl-mode-map
  3894. (org-load-modules-maybe)
  3895. (cond
  3896. ((derived-mode-p 'org-mode)
  3897. ;; Exit without error, in case some hook functions calls this
  3898. ;; by accident in org-mode.
  3899. (message "Orgtbl-mode is not useful in org-mode, command ignored"))
  3900. (orgtbl-mode
  3901. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  3902. ;; Make sure we are first in minor-mode-map-alist
  3903. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  3904. ;; FIXME: maybe it should use emulation-mode-map-alists?
  3905. (and c (setq minor-mode-map-alist
  3906. (cons c (delq c minor-mode-map-alist)))))
  3907. (org-set-local (quote org-table-may-need-update) t)
  3908. (org-add-hook 'before-change-functions 'org-before-change-function
  3909. nil 'local)
  3910. (org-set-local 'org-old-auto-fill-inhibit-regexp
  3911. auto-fill-inhibit-regexp)
  3912. (org-set-local 'auto-fill-inhibit-regexp
  3913. (if auto-fill-inhibit-regexp
  3914. (concat orgtbl-line-start-regexp "\\|"
  3915. auto-fill-inhibit-regexp)
  3916. orgtbl-line-start-regexp))
  3917. (add-to-invisibility-spec '(org-cwidth))
  3918. (when (fboundp 'font-lock-add-keywords)
  3919. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  3920. (org-restart-font-lock))
  3921. (easy-menu-add orgtbl-mode-menu))
  3922. (t
  3923. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  3924. (org-table-cleanup-narrow-column-properties)
  3925. (org-remove-from-invisibility-spec '(org-cwidth))
  3926. (remove-hook 'before-change-functions 'org-before-change-function t)
  3927. (when (fboundp 'font-lock-remove-keywords)
  3928. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  3929. (org-restart-font-lock))
  3930. (easy-menu-remove orgtbl-mode-menu)
  3931. (force-mode-line-update 'all))))
  3932. (defun org-table-cleanup-narrow-column-properties ()
  3933. "Remove all properties related to narrow-column invisibility."
  3934. (let ((s (point-min)))
  3935. (while (setq s (text-property-any s (point-max)
  3936. 'display org-narrow-column-arrow))
  3937. (remove-text-properties s (1+ s) '(display t)))
  3938. (setq s (point-min))
  3939. (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
  3940. (remove-text-properties s (1+ s) '(org-cwidth t)))
  3941. (setq s (point-min))
  3942. (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
  3943. (remove-text-properties s (1+ s) '(invisible t)))))
  3944. (defun orgtbl-make-binding (fun n &rest keys)
  3945. "Create a function for binding in the table minor mode.
  3946. FUN is the command to call inside a table. N is used to create a unique
  3947. command name. KEYS are keys that should be checked in for a command
  3948. to execute outside of tables."
  3949. (eval
  3950. (list 'defun
  3951. (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
  3952. '(arg)
  3953. (concat "In tables, run `" (symbol-name fun) "'.\n"
  3954. "Outside of tables, run the binding of `"
  3955. (mapconcat #'key-description keys "' or `")
  3956. "'.")
  3957. '(interactive "p")
  3958. (list 'if
  3959. '(org-at-table-p)
  3960. (list 'call-interactively (list 'quote fun))
  3961. (list 'let '(orgtbl-mode)
  3962. (list 'call-interactively
  3963. (append '(or)
  3964. (mapcar (lambda (k)
  3965. (list 'key-binding k))
  3966. keys)
  3967. '('orgtbl-error))))))))
  3968. (defun orgtbl-error ()
  3969. "Error when there is no default binding for a table key."
  3970. (interactive)
  3971. (user-error "This key has no function outside tables"))
  3972. (defun orgtbl-setup ()
  3973. "Setup orgtbl keymaps."
  3974. (let ((nfunc 0)
  3975. (bindings
  3976. '(([(meta shift left)] org-table-delete-column)
  3977. ([(meta left)] org-table-move-column-left)
  3978. ([(meta right)] org-table-move-column-right)
  3979. ([(meta shift right)] org-table-insert-column)
  3980. ([(meta shift up)] org-table-kill-row)
  3981. ([(meta shift down)] org-table-insert-row)
  3982. ([(meta up)] org-table-move-row-up)
  3983. ([(meta down)] org-table-move-row-down)
  3984. ("\C-c\C-w" org-table-cut-region)
  3985. ("\C-c\M-w" org-table-copy-region)
  3986. ("\C-c\C-y" org-table-paste-rectangle)
  3987. ("\C-c\C-w" org-table-wrap-region)
  3988. ("\C-c-" org-table-insert-hline)
  3989. ("\C-c}" org-table-toggle-coordinate-overlays)
  3990. ("\C-c{" org-table-toggle-formula-debugger)
  3991. ("\C-m" org-table-next-row)
  3992. ([(shift return)] org-table-copy-down)
  3993. ("\C-c?" org-table-field-info)
  3994. ("\C-c " org-table-blank-field)
  3995. ("\C-c+" org-table-sum)
  3996. ("\C-c=" org-table-eval-formula)
  3997. ("\C-c'" org-table-edit-formulas)
  3998. ("\C-c`" org-table-edit-field)
  3999. ("\C-c*" org-table-recalculate)
  4000. ("\C-c^" org-table-sort-lines)
  4001. ("\M-a" org-table-beginning-of-field)
  4002. ("\M-e" org-table-end-of-field)
  4003. ([(control ?#)] org-table-rotate-recalc-marks)))
  4004. elt key fun cmd)
  4005. (while (setq elt (pop bindings))
  4006. (setq nfunc (1+ nfunc))
  4007. (setq key (org-key (car elt))
  4008. fun (nth 1 elt)
  4009. cmd (orgtbl-make-binding fun nfunc key))
  4010. (org-defkey orgtbl-mode-map key cmd))
  4011. ;; Special treatment needed for TAB and RET
  4012. (org-defkey orgtbl-mode-map [(return)]
  4013. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  4014. (org-defkey orgtbl-mode-map "\C-m"
  4015. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  4016. (org-defkey orgtbl-mode-map [(tab)]
  4017. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  4018. (org-defkey orgtbl-mode-map "\C-i"
  4019. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  4020. (org-defkey orgtbl-mode-map [(shift tab)]
  4021. (orgtbl-make-binding 'org-table-previous-field 104
  4022. [(shift tab)] [(tab)] "\C-i"))
  4023. (unless (featurep 'xemacs)
  4024. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  4025. (orgtbl-make-binding 'org-table-previous-field 107
  4026. [S-iso-lefttab] [backtab] [(shift tab)]
  4027. [(tab)] "\C-i")))
  4028. (org-defkey orgtbl-mode-map [backtab]
  4029. (orgtbl-make-binding 'org-table-previous-field 108
  4030. [backtab] [S-iso-lefttab] [(shift tab)]
  4031. [(tab)] "\C-i"))
  4032. (org-defkey orgtbl-mode-map "\M-\C-m"
  4033. (orgtbl-make-binding 'org-table-wrap-region 105
  4034. "\M-\C-m" [(meta return)]))
  4035. (org-defkey orgtbl-mode-map [(meta return)]
  4036. (orgtbl-make-binding 'org-table-wrap-region 106
  4037. [(meta return)] "\M-\C-m"))
  4038. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  4039. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  4040. (when orgtbl-optimized
  4041. ;; If the user wants maximum table support, we need to hijack
  4042. ;; some standard editing functions
  4043. (org-remap orgtbl-mode-map
  4044. 'self-insert-command 'orgtbl-self-insert-command
  4045. 'delete-char 'org-delete-char
  4046. 'delete-backward-char 'org-delete-backward-char)
  4047. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  4048. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
  4049. '("OrgTbl"
  4050. ["Create or convert" org-table-create-or-convert-from-region
  4051. :active (not (org-at-table-p)) :keys "C-c |" ]
  4052. "--"
  4053. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  4054. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  4055. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  4056. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  4057. "--"
  4058. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  4059. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  4060. ["Copy Field from Above"
  4061. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  4062. "--"
  4063. ("Column"
  4064. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  4065. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  4066. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  4067. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  4068. ("Row"
  4069. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  4070. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  4071. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  4072. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  4073. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  4074. "--"
  4075. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  4076. ("Rectangle"
  4077. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  4078. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  4079. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  4080. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  4081. "--"
  4082. ("Radio tables"
  4083. ["Insert table template" orgtbl-insert-radio-table
  4084. (assq major-mode orgtbl-radio-table-templates)]
  4085. ["Comment/uncomment table" orgtbl-toggle-comment t])
  4086. "--"
  4087. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  4088. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  4089. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  4090. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  4091. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  4092. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  4093. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  4094. ["Sum Column/Rectangle" org-table-sum
  4095. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  4096. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  4097. ["Debug Formulas"
  4098. org-table-toggle-formula-debugger :active (org-at-table-p)
  4099. :keys "C-c {"
  4100. :style toggle :selected org-table-formula-debug]
  4101. ["Show Col/Row Numbers"
  4102. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  4103. :keys "C-c }"
  4104. :style toggle :selected org-table-overlay-coordinates]
  4105. "--"
  4106. ("Plot"
  4107. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4108. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4109. t))
  4110. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4111. "If the cursor is inside a table, realign the table.
  4112. If it is a table to be sent away to a receiver, do it.
  4113. With prefix arg, also recompute table."
  4114. (interactive "P")
  4115. (let ((case-fold-search t) (pos (point)) action)
  4116. (save-excursion
  4117. (beginning-of-line 1)
  4118. (setq action (cond
  4119. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4120. ((looking-at "[ \t]*|") pos)
  4121. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4122. (cond
  4123. ((integerp action)
  4124. (goto-char action)
  4125. (org-table-maybe-eval-formula)
  4126. (if arg
  4127. (call-interactively 'org-table-recalculate)
  4128. (org-table-maybe-recalculate-line))
  4129. (call-interactively 'org-table-align)
  4130. (when (orgtbl-send-table 'maybe)
  4131. (run-hooks 'orgtbl-after-send-table-hook)))
  4132. ((eq action 'recalc)
  4133. (save-excursion
  4134. (beginning-of-line 1)
  4135. (skip-chars-backward " \r\n\t")
  4136. (if (org-at-table-p)
  4137. (org-call-with-arg 'org-table-recalculate t))))
  4138. (t (let (orgtbl-mode)
  4139. (call-interactively (key-binding "\C-c\C-c")))))))
  4140. (defun orgtbl-create-or-convert-from-region (arg)
  4141. "Create table or convert region to table, if no conflicting binding.
  4142. This installs the table binding `C-c |', but only if there is no
  4143. conflicting binding to this key outside orgtbl-mode."
  4144. (interactive "P")
  4145. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4146. (if cmd
  4147. (call-interactively cmd)
  4148. (call-interactively 'org-table-create-or-convert-from-region))))
  4149. (defun orgtbl-tab (arg)
  4150. "Justification and field motion for `orgtbl-mode'."
  4151. (interactive "P")
  4152. (if arg (org-table-edit-field t)
  4153. (org-table-justify-field-maybe)
  4154. (org-table-next-field)))
  4155. (defun orgtbl-ret ()
  4156. "Justification and field motion for `orgtbl-mode'."
  4157. (interactive)
  4158. (if (bobp)
  4159. (newline)
  4160. (org-table-justify-field-maybe)
  4161. (org-table-next-row)))
  4162. (defun orgtbl-self-insert-command (N)
  4163. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4164. If the cursor is in a table looking at whitespace, the whitespace is
  4165. overwritten, and the table is not marked as requiring realignment."
  4166. (interactive "p")
  4167. (if (and (org-at-table-p)
  4168. (or
  4169. (and org-table-auto-blank-field
  4170. (member last-command
  4171. '(orgtbl-hijacker-command-100
  4172. orgtbl-hijacker-command-101
  4173. orgtbl-hijacker-command-102
  4174. orgtbl-hijacker-command-103
  4175. orgtbl-hijacker-command-104
  4176. orgtbl-hijacker-command-105
  4177. yas/expand))
  4178. (org-table-blank-field))
  4179. t)
  4180. (eq N 1)
  4181. (looking-at "[^|\n]* +|"))
  4182. (let (org-table-may-need-update)
  4183. (goto-char (1- (match-end 0)))
  4184. (org-delete-backward-char 1)
  4185. (goto-char (match-beginning 0))
  4186. (self-insert-command N))
  4187. (setq org-table-may-need-update t)
  4188. (let* (orgtbl-mode
  4189. a
  4190. (cmd (or (key-binding
  4191. (or (and (listp function-key-map)
  4192. (setq a (assoc last-input-event function-key-map))
  4193. (cdr a))
  4194. (vector last-input-event)))
  4195. 'self-insert-command)))
  4196. (call-interactively cmd)
  4197. (if (and org-self-insert-cluster-for-undo
  4198. (eq cmd 'self-insert-command))
  4199. (if (not (eq last-command 'orgtbl-self-insert-command))
  4200. (setq org-self-insert-command-undo-counter 1)
  4201. (if (>= org-self-insert-command-undo-counter 20)
  4202. (setq org-self-insert-command-undo-counter 1)
  4203. (and (> org-self-insert-command-undo-counter 0)
  4204. buffer-undo-list
  4205. (not (cadr buffer-undo-list)) ; remove nil entry
  4206. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  4207. (setq org-self-insert-command-undo-counter
  4208. (1+ org-self-insert-command-undo-counter))))))))
  4209. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  4210. "Regular expression matching exponentials as produced by calc.")
  4211. (defun orgtbl-gather-send-defs ()
  4212. "Gather a plist of :name, :transform, :params for each destination before
  4213. a radio table."
  4214. (save-excursion
  4215. (goto-char (org-table-begin))
  4216. (let (rtn)
  4217. (beginning-of-line 0)
  4218. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  4219. (let ((name (org-no-properties (match-string 1)))
  4220. (transform (intern (match-string 2)))
  4221. (params (if (match-end 3)
  4222. (read (concat "(" (match-string 3) ")")))))
  4223. (push (list :name name :transform transform :params params)
  4224. rtn)
  4225. (beginning-of-line 0)))
  4226. rtn)))
  4227. (defun orgtbl-send-replace-tbl (name txt)
  4228. "Find and replace table NAME with TXT."
  4229. (save-excursion
  4230. (goto-char (point-min))
  4231. (unless (re-search-forward
  4232. (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
  4233. (user-error "Don't know where to insert translated table"))
  4234. (let ((beg (line-beginning-position 2)))
  4235. (unless (re-search-forward
  4236. (concat "END +RECEIVE +ORGTBL +" name) nil t)
  4237. (user-error "Cannot find end of insertion region"))
  4238. (beginning-of-line)
  4239. (delete-region beg (point)))
  4240. (insert txt "\n")))
  4241. ;;;###autoload
  4242. (defun org-table-to-lisp (&optional txt)
  4243. "Convert the table at point to a Lisp structure.
  4244. The structure will be a list. Each item is either the symbol `hline'
  4245. for a horizontal separator line, or a list of field values as strings.
  4246. The table is taken from the parameter TXT, or from the buffer at point."
  4247. (unless (or txt (org-at-table-p)) (user-error "No table at point"))
  4248. (let ((txt (or txt
  4249. (buffer-substring-no-properties (org-table-begin)
  4250. (org-table-end)))))
  4251. (mapcar (lambda (x)
  4252. (if (string-match org-table-hline-regexp x) 'hline
  4253. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  4254. (org-split-string txt "[ \t]*\n[ \t]*"))))
  4255. (defun orgtbl-send-table (&optional maybe)
  4256. "Send a transformed version of table at point to the receiver position.
  4257. With argument MAYBE, fail quietly if no transformation is defined
  4258. for this table."
  4259. (interactive)
  4260. (catch 'exit
  4261. (unless (org-at-table-p) (user-error "Not at a table"))
  4262. ;; when non-interactive, we assume align has just happened.
  4263. (when (org-called-interactively-p 'any) (org-table-align))
  4264. (let ((dests (orgtbl-gather-send-defs))
  4265. (table (org-table-to-lisp
  4266. (buffer-substring-no-properties (org-table-begin)
  4267. (org-table-end))))
  4268. (ntbl 0))
  4269. (unless dests
  4270. (if maybe (throw 'exit nil)
  4271. (user-error "Don't know how to transform this table")))
  4272. (dolist (dest dests)
  4273. (let ((name (plist-get dest :name))
  4274. (transform (plist-get dest :transform))
  4275. (params (plist-get dest :params)))
  4276. (unless (fboundp transform)
  4277. (user-error "No such transformation function %s" transform))
  4278. (orgtbl-send-replace-tbl name (funcall transform table params)))
  4279. (incf ntbl))
  4280. (message "Table converted and installed at %d receiver location%s"
  4281. ntbl (if (> ntbl 1) "s" ""))
  4282. (and (> ntbl 0) ntbl))))
  4283. (defun org-remove-by-index (list indices &optional i0)
  4284. "Remove the elements in LIST with indices in INDICES.
  4285. First element has index 0, or I0 if given."
  4286. (if (not indices)
  4287. list
  4288. (if (integerp indices) (setq indices (list indices)))
  4289. (setq i0 (1- (or i0 0)))
  4290. (delq :rm (mapcar (lambda (x)
  4291. (setq i0 (1+ i0))
  4292. (if (memq i0 indices) :rm x))
  4293. list))))
  4294. (defun orgtbl-toggle-comment ()
  4295. "Comment or uncomment the orgtbl at point."
  4296. (interactive)
  4297. (let* ((case-fold-search t)
  4298. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  4299. (re2 (concat "^" orgtbl-line-start-regexp))
  4300. (commented (save-excursion (beginning-of-line 1)
  4301. (cond ((looking-at re1) t)
  4302. ((looking-at re2) nil)
  4303. (t (user-error "Not at an org table")))))
  4304. (re (if commented re1 re2))
  4305. beg end)
  4306. (save-excursion
  4307. (beginning-of-line 1)
  4308. (while (looking-at re) (beginning-of-line 0))
  4309. (beginning-of-line 2)
  4310. (setq beg (point))
  4311. (while (looking-at re) (beginning-of-line 2))
  4312. (setq end (point)))
  4313. (comment-region beg end (if commented '(4) nil))))
  4314. (defun orgtbl-insert-radio-table ()
  4315. "Insert a radio table template appropriate for this major mode."
  4316. (interactive)
  4317. (let* ((e (assq major-mode orgtbl-radio-table-templates))
  4318. (txt (nth 1 e))
  4319. name pos)
  4320. (unless e (user-error "No radio table setup defined for %s" major-mode))
  4321. (setq name (read-string "Table name: "))
  4322. (while (string-match "%n" txt)
  4323. (setq txt (replace-match name t t txt)))
  4324. (or (bolp) (insert "\n"))
  4325. (setq pos (point))
  4326. (insert txt)
  4327. (goto-char pos)))
  4328. ;;;###autoload
  4329. (defun orgtbl-to-generic (table params)
  4330. "Convert the orgtbl-mode TABLE to some other format.
  4331. This generic routine can be used for many standard cases.
  4332. TABLE is a list, each entry either the symbol `hline' for
  4333. a horizontal separator line, or a list of fields for that
  4334. line. PARAMS is a property list of parameters that can
  4335. influence the conversion.
  4336. Valid parameters are:
  4337. :backend, :raw
  4338. Export back-end used as a basis to transcode elements of the
  4339. table, when no specific parameter applies to it. It is also
  4340. used to translate cells contents. You can prevent this by
  4341. setting :raw property to a non-nil value.
  4342. :splice
  4343. When non-nil, only convert rows, not the table itself. This is
  4344. equivalent to setting to the empty string both :tstart
  4345. and :tend, which see.
  4346. :skip
  4347. When set to an integer N, skip the first N lines of the table.
  4348. Horizontal separation lines do count for this parameter!
  4349. :skipcols
  4350. List of columns that should be skipped. If the table has
  4351. a column with calculation marks, that column is automatically
  4352. discarded beforehand.
  4353. :hline
  4354. String to be inserted on horizontal separation lines. May be
  4355. nil to ignore these lines altogether.
  4356. :sep
  4357. Separator between two fields, as a string.
  4358. Each in the following group may be either a string or a function
  4359. of no arguments returning a string:
  4360. :tstart, :tend
  4361. Strings to start and end the table. Ignored when :splice is t.
  4362. :lstart, :lend
  4363. Strings to start and end a new table line.
  4364. :llstart, :llend
  4365. Strings to start and end the last table line. Default,
  4366. respectively, to :lstart and :lend.
  4367. Each in the following group may be a string or a function of one
  4368. argument (either the cells in the current row, as a list of
  4369. strings, or the current cell) returning a string:
  4370. :lfmt
  4371. Format string for an entire row, with enough %s to capture all
  4372. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  4373. :llfmt
  4374. Format for the entire last line, defaults to :lfmt.
  4375. :fmt
  4376. A format to be used to wrap the field, should contain %s for
  4377. the original field value. For example, to wrap everything in
  4378. dollars, you could use :fmt \"$%s$\". This may also be
  4379. a property list with column numbers and format strings, or
  4380. functions, e.g.,
  4381. \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  4382. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  4383. Same as above, specific for the header lines in the table.
  4384. All lines before the first hline are treated as header. If
  4385. any of these is not present, the data line value is used.
  4386. This may be either a string or a function of two arguments:
  4387. :efmt
  4388. Use this format to print numbers with exponential. The format
  4389. should have %s twice for inserting mantissa and exponent, for
  4390. example \"%s\\\\times10^{%s}\". This may also be a property
  4391. list with column numbers and format strings or functions.
  4392. :fmt will still be applied after :efmt."
  4393. (let ((backend (plist-get params :backend)))
  4394. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  4395. (user-error "Unknown :backend value"))
  4396. (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
  4397. (org-trim
  4398. (org-export-string-as
  4399. ;; Return TABLE as Org syntax. Tolerate non-string cells.
  4400. (with-output-to-string
  4401. (dolist (e table)
  4402. (cond ((eq e 'hline) (princ "|--\n"))
  4403. ((consp e)
  4404. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  4405. (princ "\n")))))
  4406. ;; Build a custom back-end according to PARAMS. Before defining
  4407. ;; a translator, check if there is anything to do. When there
  4408. ;; isn't, let BACKEND handle the element.
  4409. (org-export-create-backend
  4410. :parent (or backend 'org)
  4411. :filters
  4412. '((:filter-parse-tree
  4413. ;; Handle :skip parameter.
  4414. (lambda (tree backend info)
  4415. (let ((skip (plist-get info :skip)))
  4416. (when skip
  4417. (unless (wholenump skip) (user-error "Wrong :skip value"))
  4418. (let ((n 0))
  4419. (org-element-map tree 'table-row
  4420. (lambda (row)
  4421. (if (>= n skip) t
  4422. (org-element-extract-element row)
  4423. (incf n)
  4424. nil))
  4425. info t))
  4426. tree)))
  4427. ;; Handle :skipcols parameter.
  4428. (lambda (tree backend info)
  4429. (let ((skipcols (plist-get info :skipcols)))
  4430. (when skipcols
  4431. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  4432. (org-element-map tree 'table
  4433. (lambda (table)
  4434. (let ((specialp
  4435. (org-export-table-has-special-column-p table)))
  4436. (dolist (row (org-element-contents table))
  4437. (when (eq (org-element-property :type row) 'standard)
  4438. (let ((c 1))
  4439. (dolist (cell (nthcdr (if specialp 1 0)
  4440. (org-element-contents row)))
  4441. (when (memq c skipcols)
  4442. (org-element-extract-element cell))
  4443. (incf c)))))))
  4444. info)
  4445. tree)))))
  4446. :transcoders
  4447. `((table . ,(org-table--to-generic-table params))
  4448. (table-row . ,(org-table--to-generic-row params))
  4449. (table-cell . ,(org-table--to-generic-cell params))
  4450. ;; Section. Return contents to avoid garbage around table.
  4451. (section . (lambda (s c i) c))))
  4452. 'body-only (org-combine-plists params '(:with-tables t))))))
  4453. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  4454. (cond ((null value) nil)
  4455. ((functionp value) `(funcall ',value ,@args))
  4456. ((stringp value)
  4457. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  4458. (args `(format ,value ,@args))
  4459. (t value)))
  4460. ((and with-cons (consp value))
  4461. `(let ((val (cadr (memq column ',value))))
  4462. (cond ((null val) contents)
  4463. ((stringp val) (format val ,@args))
  4464. ((functionp val) (funcall val ,@args))
  4465. (t (user-error "Wrong %s value" ,name)))))
  4466. (t (user-error "Wrong %s value" name))))
  4467. (defun org-table--to-generic-table (params)
  4468. "Return custom table transcoder according to PARAMS.
  4469. PARAMS is a plist. See `orgtbl-to-generic' for more
  4470. information."
  4471. (let ((backend (plist-get params :backend))
  4472. (splice (plist-get params :splice))
  4473. (tstart (plist-get params :tstart))
  4474. (tend (plist-get params :tend)))
  4475. `(lambda (table contents info)
  4476. (concat
  4477. ,(and tstart (not splice)
  4478. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  4479. ,(if (or (not backend) tstart tend splice) 'contents
  4480. `(org-export-with-backend ',backend table contents info))
  4481. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  4482. (defun org-table--to-generic-row (params)
  4483. "Return custom table row transcoder according to PARAMS.
  4484. PARAMS is a plist. See `orgtbl-to-generic' for more
  4485. information."
  4486. (let* ((backend (plist-get params :backend))
  4487. (lstart (plist-get params :lstart))
  4488. (llstart (plist-get params :llstart))
  4489. (hlstart (plist-get params :hlstart))
  4490. (hllstart (plist-get params :hllstart))
  4491. (lend (plist-get params :lend))
  4492. (llend (plist-get params :llend))
  4493. (hlend (plist-get params :hlend))
  4494. (hllend (plist-get params :hllend))
  4495. (lfmt (plist-get params :lfmt))
  4496. (llfmt (plist-get params :llfmt))
  4497. (hlfmt (plist-get params :hlfmt))
  4498. (hllfmt (plist-get params :hllfmt)))
  4499. `(lambda (row contents info)
  4500. (if (eq (org-element-property :type row) 'rule)
  4501. ,(cond
  4502. ((plist-member params :hline)
  4503. (org-table--generic-apply (plist-get params :hline) ":hline"))
  4504. (backend `(org-export-with-backend ',backend row nil info)))
  4505. (let ((headerp (org-export-table-row-in-header-p row info))
  4506. (lastp (not (org-export-get-next-element row info)))
  4507. (last-header-p (org-export-table-row-ends-header-p row info)))
  4508. (when contents
  4509. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  4510. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  4511. ;; `:lstart', `:lend' and their relatives.
  4512. ,(let ((cells
  4513. '(org-element-map row 'table-cell
  4514. (lambda (cell)
  4515. ;; Export all cells, without separators.
  4516. ;;
  4517. ;; Use `org-export-data-with-backend'
  4518. ;; instead of `org-export-data' to eschew
  4519. ;; cached values, which
  4520. ;; ignore :orgtbl-ignore-sep parameter.
  4521. (org-export-data-with-backend
  4522. cell
  4523. (plist-get info :back-end)
  4524. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  4525. info)))
  4526. `(cond
  4527. ,(and hllfmt
  4528. `(last-header-p ,(org-table--generic-apply
  4529. hllfmt ":hllfmt" nil cells)))
  4530. ,(and hlfmt
  4531. `(headerp ,(org-table--generic-apply
  4532. hlfmt ":hlfmt" nil cells)))
  4533. ,(and llfmt
  4534. `(lastp ,(org-table--generic-apply
  4535. llfmt ":llfmt" nil cells)))
  4536. (t
  4537. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  4538. `(concat
  4539. (cond
  4540. ,(and
  4541. (or hllstart hllend)
  4542. `(last-header-p
  4543. (concat
  4544. ,(org-table--generic-apply hllstart ":hllstart")
  4545. contents
  4546. ,(org-table--generic-apply hllend ":hllend"))))
  4547. ,(and
  4548. (or hlstart hlend)
  4549. `(headerp
  4550. (concat
  4551. ,(org-table--generic-apply hlstart ":hlstart")
  4552. contents
  4553. ,(org-table--generic-apply hlend ":hlend"))))
  4554. ,(and
  4555. (or llstart llend)
  4556. `(lastp
  4557. (concat
  4558. ,(org-table--generic-apply llstart ":llstart")
  4559. contents
  4560. ,(org-table--generic-apply llend ":llend"))))
  4561. (t
  4562. ,(cond
  4563. ((or lstart lend)
  4564. `(concat
  4565. ,(org-table--generic-apply lstart ":lstart")
  4566. contents
  4567. ,(org-table--generic-apply lend ":lend")))
  4568. (backend
  4569. `(org-export-with-backend
  4570. ',backend row contents info))
  4571. (t 'contents)))))))))))))))
  4572. (defun org-table--to-generic-cell (params)
  4573. "Return custom table cell transcoder according to PARAMS.
  4574. PARAMS is a plist. See `orgtbl-to-generic' for more
  4575. information."
  4576. (let* ((backend (plist-get params :backend))
  4577. (efmt (plist-get params :efmt))
  4578. (fmt (plist-get params :fmt))
  4579. (hfmt (plist-get params :hfmt))
  4580. (sep (plist-get params :sep))
  4581. (hsep (plist-get params :hsep)))
  4582. `(lambda (cell contents info)
  4583. (let ((headerp (org-export-table-row-in-header-p
  4584. (org-export-get-parent-element cell) info))
  4585. (column (1+ (cdr (org-export-table-cell-address cell info)))))
  4586. ;; Make sure that contents are exported as Org data when :raw
  4587. ;; parameter is non-nil.
  4588. ,(when (and backend (plist-get params :raw))
  4589. `(setq contents
  4590. ;; Since we don't know what are the pseudo object
  4591. ;; types defined in backend, we cannot pass them to
  4592. ;; `org-element-interpret-data'. As a consequence,
  4593. ;; they will be treated as pseudo elements, and
  4594. ;; will have newlines appended instead of spaces.
  4595. ;; Therefore, we must make sure :post-blank value
  4596. ;; is really turned into spaces.
  4597. (replace-regexp-in-string
  4598. "\n" " "
  4599. (org-trim
  4600. (org-element-interpret-data
  4601. (org-element-contents cell))))))
  4602. (when contents
  4603. ;; Check if we can apply `:efmt' on CONTENTS.
  4604. ,(when efmt
  4605. `(when (string-match orgtbl-exp-regexp contents)
  4606. (let ((mantissa (match-string 1 contents))
  4607. (exponent (match-string 2 contents)))
  4608. (setq contents ,(org-table--generic-apply
  4609. efmt ":efmt" t 'mantissa 'exponent)))))
  4610. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  4611. (cond
  4612. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  4613. hfmt ":hfmt" t 'contents))))
  4614. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  4615. fmt ":fmt" t 'contents))))))
  4616. ;; If a separator is provided, use it instead of BACKEND's.
  4617. ;; Separators are ignored when LFMT (or equivalent) is
  4618. ;; provided.
  4619. ,(cond
  4620. ((or hsep sep)
  4621. `(if (or ,(and (not sep) '(not headerp))
  4622. (plist-get info :orgtbl-ignore-sep)
  4623. (not (org-export-get-next-element cell info)))
  4624. ,(if (not backend) 'contents
  4625. `(org-export-with-backend ',backend cell contents info))
  4626. (concat contents
  4627. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  4628. (or hsep sep)))))
  4629. (backend `(org-export-with-backend ',backend cell contents info))
  4630. (t 'contents))))))
  4631. ;;;###autoload
  4632. (defun orgtbl-to-tsv (table params)
  4633. "Convert the orgtbl-mode table to TAB separated material."
  4634. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  4635. ;;;###autoload
  4636. (defun orgtbl-to-csv (table params)
  4637. "Convert the orgtbl-mode table to CSV material.
  4638. This does take care of the proper quoting of fields with comma or quotes."
  4639. (orgtbl-to-generic table
  4640. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  4641. params)))
  4642. ;;;###autoload
  4643. (defun orgtbl-to-latex (table params)
  4644. "Convert the orgtbl-mode TABLE to LaTeX.
  4645. TABLE is a list, each entry either the symbol `hline' for
  4646. a horizontal separator line, or a list of fields for that line.
  4647. PARAMS is a property list of parameters that can influence the
  4648. conversion. All parameters from `orgtbl-to-generic' are
  4649. supported. It is also possible to use the following ones:
  4650. :booktabs
  4651. When non-nil, use formal \"booktabs\" style.
  4652. :environment
  4653. Specify environment to use, as a string. If you use
  4654. \"longtable\", you may also want to specify :language property,
  4655. as a string, to get proper continuation strings."
  4656. (require 'ox-latex)
  4657. (orgtbl-to-generic
  4658. table
  4659. (org-combine-plists
  4660. ;; Provide sane default values.
  4661. (list :backend 'latex
  4662. :latex-default-table-mode 'table
  4663. :latex-tables-centered nil
  4664. :latex-tables-booktabs (plist-get params :booktabs)
  4665. :latex-table-scientific-notation nil
  4666. :latex-default-table-environment
  4667. (or (plist-get params :environment) "tabular"))
  4668. params)))
  4669. ;;;###autoload
  4670. (defun orgtbl-to-html (table params)
  4671. "Convert the orgtbl-mode TABLE to HTML.
  4672. TABLE is a list, each entry either the symbol `hline' for
  4673. a horizontal separator line, or a list of fields for that line.
  4674. PARAMS is a property list of parameters that can influence the
  4675. conversion. All parameters from `orgtbl-to-generic' are
  4676. supported. It is also possible to use the following one:
  4677. :attributes
  4678. Attributes and values, as a plist, which will be used in
  4679. <table> tag."
  4680. (require 'ox-html)
  4681. (orgtbl-to-generic
  4682. table
  4683. (org-combine-plists
  4684. ;; Provide sane default values.
  4685. (list :backend 'html
  4686. :html-table-data-tags '("<td%s>" . "</td>")
  4687. :html-table-use-header-tags-for-first-column nil
  4688. :html-table-align-individual-fields t
  4689. :html-table-row-tags '("<tr>" . "</tr>")
  4690. :html-table-attributes
  4691. (if (plist-member params :attributes)
  4692. (plist-get params :attributes)
  4693. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  4694. :frame "hsides")))
  4695. params)))
  4696. ;;;###autoload
  4697. (defun orgtbl-to-texinfo (table params)
  4698. "Convert the orgtbl-mode TABLE to Texinfo.
  4699. TABLE is a list, each entry either the symbol `hline' for
  4700. a horizontal separator line, or a list of fields for that line.
  4701. PARAMS is a property list of parameters that can influence the
  4702. conversion. All parameters from `orgtbl-to-generic' are
  4703. supported. It is also possible to use the following one:
  4704. :columns
  4705. Column widths, as a string. When providing column fractions,
  4706. \"@columnfractions\" command can be omitted."
  4707. (require 'ox-texinfo)
  4708. (let ((output
  4709. (orgtbl-to-generic
  4710. table
  4711. (org-combine-plists
  4712. (list :backend 'texinfo
  4713. :texinfo-tables-verbatim nil
  4714. :texinfo-table-scientific-notation nil)
  4715. params)))
  4716. (columns (let ((w (plist-get params :columns)))
  4717. (cond ((not w) nil)
  4718. ((org-string-match-p "{\\|@columnfractions " w) w)
  4719. (t (concat "@columnfractions " w))))))
  4720. (if (not columns) output
  4721. (replace-regexp-in-string
  4722. "@multitable \\(.*\\)" columns output t nil 1))))
  4723. ;;;###autoload
  4724. (defun orgtbl-to-orgtbl (table params)
  4725. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  4726. TABLE is a list, each entry either the symbol `hline' for
  4727. a horizontal separator line, or a list of fields for that line.
  4728. PARAMS is a property list of parameters that can influence the
  4729. conversion. All parameters from `orgtbl-to-generic' are
  4730. supported.
  4731. Useful when slicing one table into many. The :hline, :sep,
  4732. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  4733. be set to provide ORGTBL directives for the generated table."
  4734. (require 'ox-org)
  4735. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  4736. (defun orgtbl-to-table.el (table params)
  4737. "Convert the orgtbl-mode TABLE into a table.el table.
  4738. TABLE is a list, each entry either the symbol `hline' for
  4739. a horizontal separator line, or a list of fields for that line.
  4740. PARAMS is a property list of parameters that can influence the
  4741. conversion. All parameters from `orgtbl-to-generic' are
  4742. supported."
  4743. (with-temp-buffer
  4744. (insert (orgtbl-to-orgtbl table params))
  4745. (org-table-align)
  4746. (replace-regexp-in-string
  4747. "-|" "-+"
  4748. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  4749. (defun orgtbl-to-unicode (table params)
  4750. "Convert the orgtbl-mode TABLE into a table with unicode characters.
  4751. TABLE is a list, each entry either the symbol `hline' for
  4752. a horizontal separator line, or a list of fields for that line.
  4753. PARAMS is a property list of parameters that can influence the
  4754. conversion. All parameters from `orgtbl-to-generic' are
  4755. supported. It is also possible to use the following ones:
  4756. :ascii-art
  4757. When non-nil, use \"ascii-art-to-unicode\" package to translate
  4758. the table. You can download it here:
  4759. http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  4760. :narrow
  4761. When non-nil, narrow columns width than provided width cookie,
  4762. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  4763. (require 'ox-ascii)
  4764. (orgtbl-to-generic
  4765. table
  4766. (org-combine-plists
  4767. (list :backend 'ascii
  4768. :ascii-charset 'utf-8
  4769. :ascii-table-keep-all-vertical-lines (plist-get params :)
  4770. :ascii-table-widen-columns (not (plist-get params :narrow))
  4771. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  4772. params)))
  4773. ;; Put the cursor in a column containing numerical values
  4774. ;; of an Org-Mode table,
  4775. ;; type C-c " a
  4776. ;; A new column is added with a bar plot.
  4777. ;; When the table is refreshed (C-u C-c *),
  4778. ;; the plot is updated to reflect the new values.
  4779. (defun orgtbl-ascii-draw (value min max &optional width characters)
  4780. "Draw an ascii bar in a table.
  4781. VALUE is a the value to plot, the width of the bar to draw. A
  4782. value equal to MIN will be displayed as empty (zero width bar).
  4783. A value equal to MAX will draw a bar filling all the WIDTH.
  4784. WIDTH is the expected width in characters of the column.
  4785. CHARACTERS is a string that will compose the bar, with shades of
  4786. grey from pure white to pure black. It defaults to a 10
  4787. characters string of regular ascii characters."
  4788. (let* ((characters (or characters " .:;c!lhVHW"))
  4789. (width (or width 12))
  4790. (value (if (numberp value) value (string-to-number value)))
  4791. (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
  4792. (cond
  4793. ((< value 0) "too small")
  4794. ((> value width) "too large")
  4795. (t
  4796. (let ((len (1- (length characters))))
  4797. (concat
  4798. (make-string (floor value) (elt characters len))
  4799. (string (elt characters
  4800. (floor (* (- value (floor value)) len))))))))))
  4801. ;;;###autoload
  4802. (defun orgtbl-ascii-plot (&optional ask)
  4803. "Draw an ascii bar plot in a column.
  4804. With cursor in a column containing numerical values, this
  4805. function will draw a plot in a new column.
  4806. ASK, if given, is a numeric prefix to override the default 12
  4807. characters width of the plot. ASK may also be the
  4808. \\[universal-argument] prefix, which will prompt for the width."
  4809. (interactive "P")
  4810. (let ((col (org-table-current-column))
  4811. (min 1e999) ; 1e999 will be converted to infinity
  4812. (max -1e999) ; which is the desired result
  4813. (table (org-table-to-lisp))
  4814. (length
  4815. (cond ((consp ask)
  4816. (read-number "Length of column " 12))
  4817. ((numberp ask) ask)
  4818. (t 12))))
  4819. ;; Skip any hline a the top of table.
  4820. (while (eq (car table) 'hline) (setq table (cdr table)))
  4821. ;; Skip table header if any.
  4822. (dolist (x (or (cdr (memq 'hline table)) table))
  4823. (when (consp x)
  4824. (setq x (nth (1- col) x))
  4825. (when (string-match
  4826. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  4827. x)
  4828. (setq x (string-to-number x))
  4829. (when (> min x) (setq min x))
  4830. (when (< max x) (setq max x)))))
  4831. (org-table-insert-column)
  4832. (org-table-move-column-right)
  4833. (org-table-store-formulas
  4834. (cons
  4835. (cons
  4836. (number-to-string (1+ col))
  4837. (format "'(%s $%s %s %s %s)"
  4838. "orgtbl-ascii-draw" col min max length))
  4839. (org-table-get-stored-formulas)))
  4840. (org-table-recalculate t)))
  4841. ;; Example of extension: unicode characters
  4842. ;; Here are two examples of different styles.
  4843. ;; Unicode block characters are used to give a smooth effect.
  4844. ;; See http://en.wikipedia.org/wiki/Block_Elements
  4845. ;; Use one of those drawing functions
  4846. ;; - orgtbl-ascii-draw (the default ascii)
  4847. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  4848. ;; - orgtbl-uc-draw-cont (smooth unicode)
  4849. ;; This is best viewed with the "DejaVu Sans Mono" font
  4850. ;; (use M-x set-default-font).
  4851. (defun orgtbl-uc-draw-grid (value min max &optional width)
  4852. "Draw a bar in a table using block unicode characters.
  4853. It is a variant of orgtbl-ascii-draw with Unicode block
  4854. characters, for a smooth display. Bars appear as grids (to the
  4855. extent the font allows)."
  4856. ;; http://en.wikipedia.org/wiki/Block_Elements
  4857. ;; best viewed with the "DejaVu Sans Mono" font.
  4858. (orgtbl-ascii-draw value min max width
  4859. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  4860. (defun orgtbl-uc-draw-cont (value min max &optional width)
  4861. "Draw a bar in a table using block unicode characters.
  4862. It is a variant of orgtbl-ascii-draw with Unicode block
  4863. characters, for a smooth display. Bars are solid (to the extent
  4864. the font allows)."
  4865. (orgtbl-ascii-draw value min max width
  4866. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  4867. (defun org-table-get-remote-range (name-or-id form)
  4868. "Get a field value or a list of values in a range from table at ID.
  4869. NAME-OR-ID may be the name of a table in the current file as set
  4870. by a \"#+NAME:\" directive. The first table following this line
  4871. will then be used. Alternatively, it may be an ID referring to
  4872. any entry, also in a different file. In this case, the first
  4873. table in that entry will be referenced.
  4874. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  4875. \"@I$2..@II$2\". All the references must be absolute, not relative.
  4876. The return value is either a single string for a single field, or a
  4877. list of the fields in the rectangle."
  4878. (save-match-data
  4879. (let ((case-fold-search t) (id-loc nil)
  4880. ;; Protect a bunch of variables from being overwritten
  4881. ;; by the context of the remote table
  4882. org-table-column-names org-table-column-name-regexp
  4883. org-table-local-parameters org-table-named-field-locations
  4884. org-table-current-line-types org-table-current-begin-line
  4885. org-table-current-begin-pos org-table-dlines
  4886. org-table-current-ncol
  4887. org-table-hlines org-table-last-alignment
  4888. org-table-last-column-widths org-table-last-alignment
  4889. org-table-last-column-widths tbeg
  4890. buffer loc)
  4891. (setq form (org-table-convert-refs-to-rc form))
  4892. (save-excursion
  4893. (save-restriction
  4894. (widen)
  4895. (save-excursion
  4896. (goto-char (point-min))
  4897. (if (re-search-forward
  4898. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  4899. (regexp-quote name-or-id) "[ \t]*$")
  4900. nil t)
  4901. (setq buffer (current-buffer) loc (match-beginning 0))
  4902. (setq id-loc (org-id-find name-or-id 'marker))
  4903. (unless (and id-loc (markerp id-loc))
  4904. (user-error "Can't find remote table \"%s\"" name-or-id))
  4905. (setq buffer (marker-buffer id-loc)
  4906. loc (marker-position id-loc))
  4907. (move-marker id-loc nil)))
  4908. (with-current-buffer buffer
  4909. (save-excursion
  4910. (save-restriction
  4911. (widen)
  4912. (goto-char loc)
  4913. (forward-char 1)
  4914. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  4915. (not (match-beginning 1)))
  4916. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  4917. (setq tbeg (point-at-bol))
  4918. (org-table-get-specials)
  4919. (setq form (org-table-formula-substitute-names
  4920. (org-table-formula-handle-first/last-rc form)))
  4921. (if (and (string-match org-table-range-regexp form)
  4922. (> (length (match-string 0 form)) 1))
  4923. (save-match-data
  4924. (org-table-get-range (match-string 0 form) tbeg 1))
  4925. form)))))))))
  4926. (defun org-table-remote-reference-indirection (form)
  4927. "Return formula with table remote references substituted by indirection.
  4928. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  4929. This indirection works only with the format @ROW$COLUMN. The
  4930. format \"B3\" is not supported because it can not be
  4931. distinguished from a plain table name or ID."
  4932. (let ((start 0))
  4933. (while (string-match (concat
  4934. ;; Same as in `org-table-eval-formula'.
  4935. "\\<remote([ \t]*\\("
  4936. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  4937. "[@$][^ \t,]+"
  4938. ;; Same as in `org-table-eval-formula'.
  4939. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
  4940. form
  4941. start)
  4942. ;; The position of the character as far as possible to the right
  4943. ;; that will not be replaced and particularly not be shifted by
  4944. ;; `replace-match'.
  4945. (setq start (match-beginning 1))
  4946. ;; Substitute the remote reference with the value found in the
  4947. ;; field.
  4948. (setq form
  4949. (replace-match
  4950. (save-match-data
  4951. (org-table-get-range (org-table-formula-handle-first/last-rc
  4952. (match-string 1 form))))
  4953. t t form 1))))
  4954. form)
  4955. (defmacro org-define-lookup-function (mode)
  4956. (let ((mode-str (symbol-name mode))
  4957. (first-p (equal mode 'first))
  4958. (all-p (equal mode 'all)))
  4959. (let ((plural-str (if all-p "s" "")))
  4960. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  4961. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  4962. If R-LIST is nil, return matching element%s of S-LIST.
  4963. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  4964. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  4965. This function is generated by a call to the macro `org-define-lookup-function'."
  4966. mode-str plural-str plural-str plural-str)
  4967. (let ,(let ((lvars '((p (or predicate 'equal))
  4968. (sl s-list)
  4969. (rl (or r-list s-list))
  4970. (ret nil))))
  4971. (if first-p (add-to-list 'lvars '(match-p nil)))
  4972. lvars)
  4973. (while ,(if first-p '(and (not match-p) sl) 'sl)
  4974. (progn
  4975. (if (funcall p val (car sl))
  4976. (progn
  4977. ,(if first-p '(setq match-p t))
  4978. (let ((rval (car rl)))
  4979. (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
  4980. (setq sl (cdr sl) rl (cdr rl))))
  4981. ret)))))
  4982. (org-define-lookup-function first)
  4983. (org-define-lookup-function last)
  4984. (org-define-lookup-function all)
  4985. (provide 'org-table)
  4986. ;; Local variables:
  4987. ;; generated-autoload-file: "org-loaddefs.el"
  4988. ;; End:
  4989. ;;; org-table.el ends here