org-table.el 203 KB

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