org-table.el 161 KB

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