org-table.el 189 KB

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