org-table.el 180 KB

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