org-table.el 153 KB

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