org-table.el 163 KB

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