org-table.el 143 KB

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