org-table.el 175 KB

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