org-table.el 163 KB

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